Skip to main content

fallow_api/diff_risk/
mod.rs

1//! Diff-risk rules of `fallow audit`.
2//!
3//! The rules compare the base and head text of each changed file. They report
4//! a fact about the change, so every finding is introduced. The pass reads the
5//! base text through one `git cat-file --batch` process at the merge base of
6//! the base ref and `HEAD`.
7//!
8//! - `weakened-tests`: a new skip or focus marker, fewer test cases across the
9//!   changed test files, fewer assertions in a test file, a less strict
10//!   coverage threshold, a less strict rule severity in the Fallow config, or
11//!   a new or broader ignore entry in the Fallow config.
12//! - `added-suppression`: a new lint, type-check, coverage or Fallow
13//!   suppression comment.
14//! - `test-only-branch`: a new test-environment branch in a non-test source
15//!   file.
16//! - `diverged-clone-sibling`: one copy of a base clone group was edited out
17//!   of the group, and no sibling changed. Needs the base snapshot.
18//! - `added-dependency`: a new `package.json` dependency. Off by default.
19
20pub mod clones;
21mod config_chain;
22mod config_change;
23pub mod rule_severity;
24pub mod text;
25mod thresholds;
26
27use std::path::{Path, PathBuf};
28
29use fallow_config::{ResolvedConfig, RulesConfig, Severity};
30use fallow_engine::changed_files::RenamedFile;
31use fallow_engine::module_graph::relative_key_path;
32use fallow_output::{
33    DiffRiskAction, DiffRiskActionType, DiffRiskFinding, DiffRiskLocation, DiffRiskReport,
34    DiffRiskRule, DiffRiskSeverity, DiffRiskSuppression, WeakenedTestsKind,
35};
36use fallow_types::duplicates::CloneGroup;
37use fallow_types::read_guard::{self, ReadRefusal};
38use fallow_types::suppress::{IssueKind, Suppression, SuppressionTarget};
39use rustc_hash::{FxHashMap, FxHashSet};
40
41use crate::audit_run::{BaseFileReader, BaseRead};
42use clones::{BaseCloneGroup, CloneSpan, CloneTexts};
43use config_chain::{ConfigChain, ConfigRead};
44use config_change::ConfigSides;
45
46/// Extensions of files that hold JavaScript-style comments, where an added
47/// suppression or a test-only branch is meaningful.
48const SOURCE_EXTENSIONS: &[&str] = &[
49    "js", "jsx", "ts", "tsx", "mjs", "cjs", "mts", "cts", "vue", "svelte", "astro",
50];
51/// Extensions where a suppression comment is meaningful. Adds styles and
52/// markup to [`SOURCE_EXTENSIONS`].
53const STYLE_EXTENSIONS: &[&str] = &["css", "scss", "sass", "less", "html"];
54
55/// Where the rule severities come from.
56#[derive(Clone, Copy)]
57pub enum DiffRiskRules<'a> {
58    /// The resolved config, with per-path `overrides`.
59    Config(&'a ResolvedConfig),
60    /// One rules table for every path.
61    Rules(&'a RulesConfig),
62}
63
64impl DiffRiskRules<'_> {
65    fn for_path(self, abs: &Path) -> RulesConfig {
66        match self {
67            Self::Config(config) => config.resolve_rules_for_path(abs),
68            Self::Rules(rules) => rules.clone(),
69        }
70    }
71}
72
73/// Inputs of one diff-risk pass.
74pub struct DiffRiskInput<'a> {
75    /// Head analysis root. Finding paths are relative to it.
76    pub root: &'a Path,
77    /// Resolved base ref of the audit.
78    pub base_ref: &'a str,
79    /// Absolute paths of the changed files.
80    pub changed_files: &'a FxHashSet<PathBuf>,
81    /// Renames between base and head.
82    pub renames: &'a [RenamedFile],
83    /// Rule severities.
84    pub rules: DiffRiskRules<'a>,
85    /// Clone groups of the base snapshot. `None` turns off
86    /// `diverged-clone-sibling`: without a base pass no copy can be compared.
87    pub base_clone_groups: Option<&'a [BaseCloneGroup]>,
88    /// Instance locations of every head clone group.
89    pub head_clone_groups: Vec<Vec<CloneSpan>>,
90}
91
92/// The instance locations of a clone group, relative to `root`.
93#[must_use]
94pub fn clone_spans(group: &CloneGroup, root: &Path) -> Vec<CloneSpan> {
95    group
96        .instances
97        .iter()
98        .map(|instance| CloneSpan {
99            path: relative_key_path(&instance.file, root),
100            start_line: u32::try_from(instance.start_line).unwrap_or(u32::MAX),
101            end_line: u32::try_from(instance.end_line).unwrap_or(u32::MAX),
102        })
103        .collect()
104}
105
106/// The base and head text of one changed file.
107struct FileTexts {
108    /// Head path relative to the analysis root.
109    rel: String,
110    /// Absolute head path.
111    abs: PathBuf,
112    /// Base text; `None` when the file is new.
113    base: Option<String>,
114    /// Head text; `None` when the change deleted the file.
115    head: Option<String>,
116}
117
118/// A finding before the severity and suppression pass.
119struct RawFinding {
120    rule: DiffRiskRule,
121    kind: Option<WeakenedTestsKind>,
122    path: String,
123    line: Option<u32>,
124    message: String,
125    evidence: String,
126    related: Vec<DiffRiskLocation>,
127    /// The lowest severity of the finding. A change that lowers the severity
128    /// of a rule must not turn off the finding that reports that change.
129    min_severity: Option<Severity>,
130}
131
132/// Run every diff-risk rule over the changed files.
133///
134/// Best-effort: a file that cannot be read is skipped, and a base-reader
135/// error stops the scan of the remaining files, so a broken pipe never reads
136/// as an empty base file.
137#[must_use]
138pub fn detect(input: &DiffRiskInput<'_>) -> DiffRiskReport {
139    let Ok(git_root) = fallow_engine::changed_files::resolve_git_toplevel(input.root) else {
140        return DiffRiskReport::default();
141    };
142    let Some(reader) = BaseFileReader::spawn(input.root) else {
143        return DiffRiskReport::default();
144    };
145    let mut base = BaseSource {
146        git_root: dunce::canonicalize(&git_root).unwrap_or(git_root),
147        reader,
148        commit: merge_base(input.root, input.base_ref),
149    };
150    let files = read_files(input, &mut base);
151
152    let mut raw = Vec::new();
153    for file in &files {
154        let rules = input.rules.for_path(&file.abs);
155        detect_file(input.root, file, &rules, &mut raw);
156    }
157    detect_config_changes(input, &mut base, &mut raw);
158    detect_removed_tests(input.root, &files, &mut raw);
159    if let Some(base_groups) = input.base_clone_groups {
160        detect_diverged_clones(input, &mut base, base_groups, &files, &mut raw);
161    }
162
163    let findings = finalize(input, &files, raw);
164    DiffRiskReport { findings }
165}
166
167/// Base-side text access: one `git cat-file --batch` reader at the merge
168/// base.
169struct BaseSource {
170    git_root: PathBuf,
171    reader: BaseFileReader,
172    commit: String,
173}
174
175impl BaseSource {
176    /// Read the base text of an absolute path. A path outside the repository
177    /// reads as an error.
178    fn read(&mut self, abs: &Path) -> BaseRead {
179        match abs.strip_prefix(&self.git_root) {
180            Ok(relative) => self.reader.read(&self.commit, relative),
181            Err(_) => BaseRead::Error,
182        }
183    }
184}
185
186/// The merge base of `base_ref` and `HEAD`, or `base_ref` when git cannot
187/// resolve one. The changed-file list uses the merge base too, so a base
188/// branch that moved on does not read as a change of this branch.
189pub(crate) fn merge_base(root: &Path, base_ref: &str) -> String {
190    let mut command = fallow_engine::changed_files::git_command_in(root);
191    command
192        .args(["merge-base", "--end-of-options", base_ref, "HEAD"])
193        .stderr(std::process::Stdio::null());
194    command
195        .output()
196        .ok()
197        .filter(|output| output.status.success())
198        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
199        .filter(|sha| !sha.is_empty())
200        .unwrap_or_else(|| base_ref.to_owned())
201}
202
203/// Whether a diff-risk rule can read this file. The rules read discovered
204/// source files (every clone group member is one), test files, test-runner
205/// and coverage configs, and package manifests. Other changed files, such as
206/// a lockfile or an image, are not read.
207fn is_rule_relevant(root: &Path, rel: &str) -> bool {
208    fallow_engine::discover::SOURCE_EXTENSIONS.contains(&extension(rel))
209        || takes_suppression_comments(rel)
210        || is_js_test_code(root, rel)
211        || text::is_coverage_config_path(rel)
212        || crate::dependency_deltas::is_manifest_path(rel)
213}
214
215/// The head text of `abs`, or `None` when the file does not exist. A file
216/// that resolves outside `root`, is not a regular file or is too large is
217/// refused, and the caller skips it.
218fn read_head(root: &Path, abs: &Path) -> Result<Option<String>, ReadRefusal> {
219    match read_guard::read_bytes_inside(root, abs, read_guard::DEFAULT_MAX_READ_BYTES) {
220        Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
221        Err(refusal) if refusal.is_not_found() => Ok(None),
222        Err(refusal) => Err(refusal),
223    }
224}
225
226fn read_files(input: &DiffRiskInput<'_>, source: &mut BaseSource) -> Vec<FileTexts> {
227    let rename_sources: FxHashSet<&Path> = input
228        .renames
229        .iter()
230        .map(|rename| rename.from.as_path())
231        .collect();
232    let rename_targets: FxHashMap<&Path, &Path> = input
233        .renames
234        .iter()
235        .map(|rename| (rename.to.as_path(), rename.from.as_path()))
236        .collect();
237    let mut paths: Vec<&PathBuf> = input.changed_files.iter().collect();
238    paths.sort();
239
240    let mut files = Vec::new();
241    for abs in paths {
242        // The old path of a rename is not a deletion: its text lives on at
243        // the new path, which reads its base text from the old path.
244        if rename_sources.contains(abs.as_path()) {
245            continue;
246        }
247        if !abs.starts_with(input.root) {
248            continue;
249        }
250        let base_abs = rename_targets
251            .get(abs.as_path())
252            .copied()
253            .unwrap_or(abs.as_path());
254        if !base_abs.starts_with(&source.git_root) {
255            continue;
256        }
257        let rel = relative_key_path(abs, input.root);
258        if !is_rule_relevant(input.root, &rel) {
259            continue;
260        }
261        let Ok(head) = read_head(input.root, abs) else {
262            continue;
263        };
264        let base = match source.read(base_abs) {
265            BaseRead::Content(base) => Some(base),
266            BaseRead::Missing => None,
267            BaseRead::Error => break,
268        };
269        if base.is_none() && head.is_none() {
270            continue;
271        }
272        files.push(FileTexts {
273            rel,
274            abs: abs.clone(),
275            base,
276            head,
277        });
278    }
279    files
280}
281
282fn extension(rel: &str) -> &str {
283    let name = rel.rsplit('/').next().unwrap_or(rel);
284    name.rsplit_once('.').map_or("", |(_, ext)| ext)
285}
286
287fn is_source_file(rel: &str) -> bool {
288    SOURCE_EXTENSIONS.contains(&extension(rel))
289}
290
291fn takes_suppression_comments(rel: &str) -> bool {
292    is_source_file(rel) || STYLE_EXTENSIONS.contains(&extension(rel))
293}
294
295/// A JavaScript-family test file, where the test rules apply. A test file in
296/// another language, such as a Rust integration test, can hold JavaScript
297/// test text in a string, so it is not read.
298fn is_js_test_code(root: &Path, rel: &str) -> bool {
299    is_source_file(rel) && fallow_engine::test_paths::is_test_code_path_str(root, rel)
300}
301
302/// A test file, or a type test of the `tsd` and Vitest conventions
303/// (`test-d/`, `*.test-d.ts`).
304fn is_type_or_test_file(root: &Path, rel: &str) -> bool {
305    fallow_engine::test_paths::is_test_path_str(root, rel)
306        || rel.split('/').any(|segment| segment == "test-d")
307        || rel.contains(".test-d.")
308}
309
310/// Directory names of test fixtures and generated code. A tool writes these
311/// files, or a test reads them as data, so their suppression comments are
312/// not a choice of the change author.
313const FIXTURE_OR_GENERATED_DIRS: &[&str] = &[
314    "fixture",
315    "fixtures",
316    "__fixtures__",
317    "__snapshots__",
318    "generated",
319    "__generated__",
320];
321
322fn is_fixture_or_generated(rel: &str) -> bool {
323    let mut dirs = rel.split('/').rev().skip(1);
324    dirs.any(|dir| FIXTURE_OR_GENERATED_DIRS.contains(&dir))
325}
326
327/// File-name markers of story files (`button.stories.tsx`).
328const STORY_FILE_MARKERS: &[&str] = &[".stories.", ".story."];
329
330/// Test or story code. Each copy there shows one case or one state, so the
331/// copies differ on purpose.
332fn is_example_copy(root: &Path, rel: &str) -> bool {
333    if fallow_engine::test_paths::is_test_path_str(root, rel) {
334        return true;
335    }
336    let name = rel.rsplit('/').next().unwrap_or(rel).to_ascii_lowercase();
337    STORY_FILE_MARKERS
338        .iter()
339        .any(|marker| name.contains(marker))
340}
341
342/// A tool config such as `vite.config.ts`. A test-environment check is
343/// normal there.
344fn is_tool_config(rel: &str) -> bool {
345    let name = rel.rsplit('/').next().unwrap_or(rel);
346    // An rc file is a dot file whose first name part ends in `rc`, such as
347    // `.eslintrc.js`. `src.ts` and `arc.ts` are not rc files.
348    let dot_rc = name.strip_prefix('.').is_some_and(|rest| {
349        rest.split_once('.')
350            .is_some_and(|(stem, _ext)| stem.ends_with("rc"))
351    });
352    name.contains(".config.") || name.contains(".conf.") || dot_rc
353}
354
355/// Changes of the Fallow config chain that make the analysis less strict.
356/// The finding keeps the base `weakened-tests` severity as its lowest
357/// severity, so a change that turns off `weakened-tests` still reports.
358fn detect_config_changes(
359    input: &DiffRiskInput<'_>,
360    source: &mut BaseSource,
361    raw: &mut Vec<RawFinding>,
362) {
363    // The config chain can reach above the analysis root, up to the git root.
364    let git_root = source.git_root.clone();
365    let mut read_head = |abs: &Path| match read_head(&git_root, abs) {
366        Ok(Some(text)) => ConfigRead::Content(text),
367        Ok(None) => ConfigRead::Missing,
368        Err(_) => ConfigRead::Unreadable,
369    };
370    // Changed-file paths start at the canonical git root, so the chain paths
371    // must start at the canonical analysis root to match them.
372    let root = dunce::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
373    let stop = source.git_root.clone();
374    let Some(head) = ConfigChain::resolve(&root, &stop, &mut read_head) else {
375        return;
376    };
377    let mut read_base = |abs: &Path| match source.read(abs) {
378        BaseRead::Content(text) => ConfigRead::Content(text),
379        BaseRead::Missing => ConfigRead::Missing,
380        BaseRead::Error => ConfigRead::Unreadable,
381    };
382    let Some(base) = ConfigChain::resolve(&root, &stop, &mut read_base) else {
383        return;
384    };
385    let sides = ConfigSides { base, head };
386    if !sides.touched_by(input.changed_files) {
387        return;
388    }
389    // An opaque base source can set `weakened-tests`. `Off` keeps the head
390    // severity and still marks the finding as one that no head comment hides.
391    let min_severity = rule_severity::weakened_tests_severity(&sides.base).unwrap_or(Severity::Off);
392    let mut read_base_text = |abs: &Path| match source.read(abs) {
393        BaseRead::Content(text) => Some(text),
394        BaseRead::Missing | BaseRead::Error => None,
395    };
396    for hit in sides.hits(&root, &mut read_base_text) {
397        raw.push(RawFinding {
398            rule: DiffRiskRule::WeakenedTests,
399            kind: Some(hit.kind),
400            path: hit.path,
401            line: hit.line,
402            message: hit.message,
403            evidence: hit.evidence,
404            related: Vec::new(),
405            min_severity: Some(min_severity),
406        });
407    }
408}
409
410fn detect_file(root: &Path, file: &FileTexts, rules: &RulesConfig, raw: &mut Vec<RawFinding>) {
411    let base = file.base.as_deref().unwrap_or("");
412    let Some(head) = file.head.as_deref() else {
413        return;
414    };
415    let rel = file.rel.as_str();
416    let is_test = is_js_test_code(root, rel);
417
418    if rules.weakened_tests != Severity::Off {
419        if is_test {
420            for hit in text::skip_only_hits(base, head) {
421                raw.push(RawFinding {
422                    rule: DiffRiskRule::WeakenedTests,
423                    kind: Some(WeakenedTestsKind::SkipOnly),
424                    path: rel.to_owned(),
425                    line: Some(hit.line),
426                    message: format!(
427                        "The change adds `{}`, so other tests or this test do not run",
428                        hit.evidence
429                    ),
430                    evidence: hit.evidence,
431                    related: Vec::new(),
432                    min_severity: None,
433                });
434            }
435        }
436        if text::is_coverage_config_path(rel) {
437            for hit in thresholds::hits_for_config(rel, base, head) {
438                raw.push(RawFinding {
439                    rule: DiffRiskRule::WeakenedTests,
440                    kind: Some(WeakenedTestsKind::CoverageThreshold),
441                    path: rel.to_owned(),
442                    line: Some(hit.line),
443                    message: format!(
444                        "The change makes a threshold less strict ({})",
445                        hit.evidence
446                    ),
447                    evidence: hit.evidence,
448                    related: Vec::new(),
449                    min_severity: None,
450                });
451            }
452        }
453    }
454
455    if rules.added_suppression != Severity::Off
456        && takes_suppression_comments(rel)
457        && !is_fixture_or_generated(rel)
458    {
459        let type_test = is_type_or_test_file(root, rel);
460        for hit in text::added_suppression_hits(base, head) {
461            // In a test, `@ts-expect-error` asserts that a type error exists.
462            if type_test && hit.evidence == "@ts-expect-error" {
463                continue;
464            }
465            raw.push(RawFinding {
466                rule: DiffRiskRule::AddedSuppression,
467                kind: None,
468                path: rel.to_owned(),
469                line: Some(hit.line),
470                message: format!("The change adds a `{}` suppression comment", hit.evidence),
471                evidence: hit.evidence,
472                related: Vec::new(),
473                min_severity: None,
474            });
475        }
476    }
477
478    if rules.test_only_branch != Severity::Off
479        && is_source_file(rel)
480        && !fallow_engine::test_paths::is_test_path_str(root, rel)
481        && !is_tool_config(rel)
482    {
483        for hit in text::test_only_branch_hits(base, head) {
484            raw.push(RawFinding {
485                rule: DiffRiskRule::TestOnlyBranch,
486                kind: None,
487                path: rel.to_owned(),
488                line: Some(hit.line),
489                message: format!(
490                    "The change adds a `{}` check to source code, so tests and production can take different paths",
491                    hit.evidence
492                ),
493                evidence: hit.evidence,
494                related: Vec::new(),
495                min_severity: None,
496            });
497        }
498    }
499
500    if rules.added_dependency != Severity::Off && crate::dependency_deltas::is_manifest_path(rel) {
501        let deltas = crate::dependency_deltas::manifest_dependency_deltas(base, head);
502        for added in deltas.added {
503            let evidence = format!("{}@{} ({})", added.name, added.to, added.section);
504            raw.push(RawFinding {
505                rule: DiffRiskRule::AddedDependency,
506                kind: None,
507                path: rel.to_owned(),
508                line: (added.line > 0).then_some(added.line),
509                message: format!("The change adds the dependency `{}`", added.name),
510                evidence,
511                related: Vec::new(),
512                min_severity: None,
513            });
514        }
515    }
516}
517
518/// The names that the change removed from the project.
519///
520/// - Identifiers that a changed non-test source file held in base and no
521///   longer holds in head, such as a deleted function or a dropped call.
522///   Identifiers of a deleted file count only when no changed non-test source
523///   file still holds them in head, and names that the deleted file imports
524///   never count.
525/// - The file stem of each deleted file without test cases, and each of its
526///   directories that is gone at head, such as a deleted fixture directory.
527///
528/// Reserved words and common globals never count.
529struct RemovedNames {
530    identifiers: FxHashSet<String>,
531    segments: FxHashSet<String>,
532}
533
534/// The shortest name that can explain a test removal. Shorter names, such as
535/// `id` or `get`, are too common to tie a test to the removed code.
536const MIN_REMOVED_NAME_LEN: usize = 4;
537
538/// JS and TS reserved words and common globals. Each source file holds them,
539/// so they do not tie a test to the removed code.
540const NOT_REMOVED_NAMES: &[&str] = &[
541    "async",
542    "await",
543    "break",
544    "case",
545    "catch",
546    "class",
547    "console",
548    "const",
549    "continue",
550    "default",
551    "delete",
552    "else",
553    "enum",
554    "export",
555    "exports",
556    "extends",
557    "false",
558    "finally",
559    "from",
560    "function",
561    "import",
562    "instanceof",
563    "interface",
564    "module",
565    "null",
566    "require",
567    "return",
568    "static",
569    "super",
570    "switch",
571    "this",
572    "throw",
573    "true",
574    "type",
575    "typeof",
576    "undefined",
577    "void",
578    "while",
579    "with",
580    "yield",
581];
582
583/// Whether a token can name removed code.
584fn is_removed_name_candidate(name: &str) -> bool {
585    name.len() >= MIN_REMOVED_NAME_LEN && !NOT_REMOVED_NAMES.contains(&name)
586}
587
588/// The names that the import statements of a file bind. An imported name is
589/// declared in another file, so its use in a deleted file does not show that
590/// the name left the project.
591fn imported_names(src: &str) -> FxHashSet<String> {
592    let mut statements = String::new();
593    let mut in_import = false;
594    for line in src.lines() {
595        let trimmed = line.trim_start();
596        if !in_import && trimmed.starts_with("import ") {
597            in_import = true;
598        }
599        if !in_import {
600            continue;
601        }
602        statements.push_str(line);
603        statements.push('\n');
604        if trimmed.ends_with(';') || trimmed.contains("from ") || trimmed.ends_with("from") {
605            in_import = false;
606        }
607    }
608    text::code_identifiers(&statements)
609}
610
611impl RemovedNames {
612    fn collect(root: &Path, files: &[FileTexts]) -> Self {
613        let mut identifiers = FxHashSet::default();
614        let mut deleted_identifiers = FxHashSet::default();
615        let mut segments = FxHashSet::default();
616        let mut head_union = FxHashSet::default();
617        for file in files {
618            // A deleted file with test cases does not explain its own removal.
619            if file.head.is_none()
620                && file
621                    .base
622                    .as_deref()
623                    .is_some_and(|base| text::test_case_count(base) == 0)
624            {
625                segments.extend(deleted_path_segments(root, &file.rel));
626            }
627            if !is_source_file(&file.rel)
628                || fallow_engine::test_paths::is_test_path_str(root, &file.rel)
629            {
630                continue;
631            }
632            if let Some(head) = file.head.as_deref() {
633                head_union.extend(text::code_identifiers(head));
634            }
635            let Some(base) = file.base.as_deref() else {
636                continue;
637            };
638            match file.head.as_deref() {
639                Some(head) => {
640                    let head = text::code_identifiers(head);
641                    identifiers.extend(
642                        text::code_identifiers(base)
643                            .into_iter()
644                            .filter(|name| is_removed_name_candidate(name) && !head.contains(name)),
645                    );
646                }
647                None => {
648                    let imported = imported_names(base);
649                    deleted_identifiers.extend(text::code_identifiers(base).into_iter().filter(
650                        |name| is_removed_name_candidate(name) && !imported.contains(name),
651                    ));
652                }
653            }
654        }
655        // A name of a deleted file that a changed source file still holds did
656        // not leave the project, for example a function that moved from the
657        // deleted file.
658        identifiers.extend(
659            deleted_identifiers
660                .into_iter()
661                .filter(|name| !head_union.contains(name)),
662        );
663        Self {
664            identifiers,
665            segments,
666        }
667    }
668
669    /// Whether the lines that a test file lost name removed code that the
670    /// head test no longer names. Then the tests left together with the code
671    /// they covered. A path segment matches only a whole token of a line, so
672    /// a deleted `core` directory does not match `score`.
673    fn explain(&self, base: &str, head: &str) -> bool {
674        let removed: Vec<&str> = text::added_lines(head, base)
675            .into_iter()
676            .map(|(_, line)| line)
677            .collect();
678        if removed.is_empty() {
679            return false;
680        }
681        let head_identifiers = text::code_identifiers(head);
682        let names_removed_identifier = removed.iter().any(|line| {
683            text::code_identifiers(line)
684                .iter()
685                .any(|name| self.identifiers.contains(name) && !head_identifiers.contains(name))
686        });
687        names_removed_identifier
688            || self.segments.iter().any(|segment| {
689                !head.contains(segment.as_str())
690                    && removed
691                        .iter()
692                        .any(|line| path_tokens(line).any(|token| token == segment))
693            })
694    }
695}
696
697/// The path segments that a deleted file takes out of the project: its file
698/// stem, and each directory that is gone at head. A directory that still
699/// exists, such as `src/components`, did not leave the project, so a test that
700/// imports another file from it is not explained.
701fn deleted_path_segments(root: &Path, rel: &str) -> Vec<String> {
702    let stem_path = rel.rsplit_once('.').map_or(rel, |(stem, _)| stem);
703    let mut found = Vec::new();
704    let mut prefix_len = 0;
705    let parts: Vec<&str> = stem_path.split('/').collect();
706    let last = parts.len().saturating_sub(1);
707    for (index, part) in parts.iter().enumerate() {
708        prefix_len += part.len();
709        let is_stem = index == last;
710        let gone = is_stem || !root.join(&rel[..prefix_len]).exists();
711        if gone && part.len() >= MIN_REMOVED_NAME_LEN {
712            found.push((*part).to_owned());
713        }
714        prefix_len += 1;
715    }
716    found
717}
718
719/// The tokens of a line split on path and string delimiters.
720fn path_tokens(line: &str) -> impl Iterator<Item = &str> {
721    line.split(['/', '.', '\'', '"', '`'])
722}
723
724/// `removed-tests` and `assertion-drop`. Both compare per file, and both
725/// report only when the total over every changed test file also dropped, so
726/// tests or assertions that moved to another changed file do not report. A
727/// drop does not report when the lost test lines name code that the change
728/// removed: the tests went together with that code. An assertion drop reports
729/// only when assertions are at least half of the code lines that the file
730/// lost. Otherwise the change rewrote the test, for example it moved setup
731/// checks into a shared helper.
732fn detect_removed_tests(root: &Path, files: &[FileTexts], raw: &mut Vec<RawFinding>) {
733    struct Counts<'a> {
734        rel: &'a str,
735        base_cases: usize,
736        head_cases: usize,
737        base_asserts: usize,
738        head_asserts: usize,
739        explained: bool,
740        assertions_led: bool,
741    }
742    let removed_names = RemovedNames::collect(root, files);
743    let counts: Vec<Counts<'_>> = files
744        .iter()
745        .filter(|file| is_js_test_code(root, &file.rel))
746        .map(|file| {
747            let base = file.base.as_deref().unwrap_or("");
748            let head = file.head.as_deref().unwrap_or("");
749            Counts {
750                rel: &file.rel,
751                base_cases: text::test_case_count(base),
752                head_cases: text::test_case_count(head),
753                base_asserts: text::assertion_count(base),
754                head_asserts: text::assertion_count(head),
755                explained: removed_names.explain(base, head),
756                assertions_led: {
757                    let (asserts, code) = text::removed_assertion_lines(base, head);
758                    asserts * 2 >= code
759                },
760            }
761        })
762        .collect();
763    let total = |pick: fn(&Counts<'_>) -> usize| counts.iter().map(pick).sum::<usize>();
764    let cases_dropped = total(|c| c.head_cases) < total(|c| c.base_cases);
765    let asserts_dropped = total(|c| c.head_asserts) < total(|c| c.base_asserts);
766    for count in counts.iter().filter(|count| !count.explained) {
767        if cases_dropped && count.head_cases < count.base_cases {
768            let evidence = format!("test cases: {} -> {}", count.base_cases, count.head_cases);
769            raw.push(RawFinding {
770                rule: DiffRiskRule::WeakenedTests,
771                kind: Some(WeakenedTestsKind::RemovedTests),
772                path: count.rel.to_owned(),
773                line: None,
774                message: format!("The change removes test cases ({evidence})"),
775                evidence,
776                related: Vec::new(),
777                min_severity: None,
778            });
779        } else if asserts_dropped
780            && count.assertions_led
781            && count.head_cases >= count.base_cases
782            && count.head_asserts < count.base_asserts
783        {
784            let evidence = format!(
785                "assertions: {} -> {}",
786                count.base_asserts, count.head_asserts
787            );
788            raw.push(RawFinding {
789                rule: DiffRiskRule::WeakenedTests,
790                kind: Some(WeakenedTestsKind::AssertionDrop),
791                path: count.rel.to_owned(),
792                line: None,
793                message: format!("The change removes assertions ({evidence})"),
794                evidence,
795                related: Vec::new(),
796                min_severity: None,
797            });
798        }
799    }
800}
801
802fn detect_diverged_clones(
803    input: &DiffRiskInput<'_>,
804    source: &mut BaseSource,
805    base_groups: &[BaseCloneGroup],
806    files: &[FileTexts],
807    raw: &mut Vec<RawFinding>,
808) {
809    let changed: FxHashSet<String> = files.iter().map(|file| file.rel.clone()).collect();
810    let renames: FxHashMap<String, String> = input
811        .renames
812        .iter()
813        .map(|rename| {
814            (
815                relative_key_path(&rename.from, input.root),
816                relative_key_path(&rename.to, input.root),
817            )
818        })
819        .collect();
820    let head_by_rel: FxHashMap<&str, Option<&str>> = files
821        .iter()
822        .map(|file| (file.rel.as_str(), file.head.as_deref()))
823        .collect();
824    let root = input.root;
825    let mut base_text = |rel: &str| match source.read(&root.join(rel)) {
826        BaseRead::Content(text) => Some(text),
827        BaseRead::Missing | BaseRead::Error => None,
828    };
829    let mut head_text = |rel: &str| match head_by_rel.get(rel) {
830        Some(head) => head.map(str::to_owned),
831        None => read_head(root, &root.join(rel)).ok().flatten(),
832    };
833    let found = clones::diverged_clone_siblings(
834        base_groups,
835        &input.head_clone_groups,
836        &changed,
837        &renames,
838        &mut CloneTexts {
839            base: &mut base_text,
840            head: &mut head_text,
841        },
842    );
843    for diverged in found {
844        // Test and story copies differ case by case on purpose, so an edit to
845        // one of them is not a missed sibling.
846        if is_example_copy(root, &diverged.path) {
847            continue;
848        }
849        let rules = input.rules.for_path(&root.join(&diverged.path));
850        if rules.diverged_clone_sibling == Severity::Off {
851            continue;
852        }
853        let related: Vec<DiffRiskLocation> = diverged
854            .siblings
855            .iter()
856            .map(|sibling| DiffRiskLocation {
857                path: sibling.path.clone(),
858                line: sibling.start_line,
859            })
860            .collect();
861        let evidence = related
862            .iter()
863            .map(|location| format!("{}:{}", location.path, location.line))
864            .collect::<Vec<_>>()
865            .join(", ");
866        raw.push(RawFinding {
867            rule: DiffRiskRule::DivergedCloneSibling,
868            kind: None,
869            path: diverged.path,
870            line: diverged.line,
871            message: format!(
872                "The change edits one copy of duplicated code, and its {} unchanged copies no longer match",
873                related.len()
874            ),
875            evidence: format!("unchanged copies: {evidence}"),
876            related,
877            min_severity: None,
878        });
879    }
880}
881
882const fn issue_kind(rule: DiffRiskRule) -> IssueKind {
883    match rule {
884        DiffRiskRule::WeakenedTests => IssueKind::WeakenedTests,
885        DiffRiskRule::AddedSuppression => IssueKind::AddedSuppression,
886        DiffRiskRule::TestOnlyBranch => IssueKind::TestOnlyBranch,
887        DiffRiskRule::DivergedCloneSibling => IssueKind::DivergedCloneSibling,
888        DiffRiskRule::AddedDependency => IssueKind::AddedDependency,
889    }
890}
891
892const fn rule_severity(rules: &RulesConfig, rule: DiffRiskRule) -> Severity {
893    rules.severity_for_kind(issue_kind(rule))
894}
895
896fn stricter(severity: Severity, min_severity: Option<Severity>) -> Severity {
897    match min_severity {
898        Some(min) if rule_severity::strictness(min) > rule_severity::strictness(severity) => min,
899        _ => severity,
900    }
901}
902
903/// Whether a head suppression covers the finding. An `added-suppression`
904/// finding honors only a suppression that names its rule: a new blanket
905/// `fallow-ignore` comment must not hide itself.
906fn is_suppressed(suppressions: &[Suppression], rule: DiffRiskRule, line: Option<u32>) -> bool {
907    let kind = issue_kind(rule);
908    suppressions.iter().any(|suppression| {
909        let names_rule = matches!(
910            &suppression.target,
911            Some(SuppressionTarget::Issue(target)) if *target == kind
912        );
913        if rule == DiffRiskRule::AddedSuppression && !names_rule {
914            return false;
915        }
916        let line = line.unwrap_or(0);
917        if line == 0 {
918            suppression.line == 0 && suppression.matches_issue_kind(0, kind)
919        } else {
920            suppression.matches_issue_kind(line, kind)
921        }
922    })
923}
924
925const SECURITY_WITHOUT_REASON_MESSAGE: &str = "The change adds a `fallow-ignore` comment that hides a security finding and gives no `-- <reason>`";
926
927/// The parsed `fallow-ignore` comment of an `added-suppression` finding, or
928/// `None` for another rule, another suppression token, or a comment that the
929/// suppression parser does not read (for example a trailing comment).
930///
931/// Only a comment that names a security kind sets `security_without_reason`.
932/// A blanket comment also hides security findings, but it does not set the
933/// flag, so projects without security analysis get no extra signal.
934fn added_fallow_ignore(list: &[Suppression], finding: &RawFinding) -> Option<DiffRiskSuppression> {
935    if finding.rule != DiffRiskRule::AddedSuppression
936        || finding.evidence != text::FALLOW_IGNORE_TOKEN
937    {
938        return None;
939    }
940    let line = finding.line?;
941    let mut on_line = list
942        .iter()
943        .filter(|suppression| suppression.comment_line == line)
944        .peekable();
945    on_line.peek()?;
946    let mut kinds = Vec::new();
947    let mut reason = None;
948    let mut names_security = false;
949    for suppression in on_line {
950        reason = reason.or_else(|| suppression.reason.clone());
951        names_security |= matches!(
952            suppression.issue_kind_target(),
953            Some(IssueKind::SecuritySink | IssueKind::SecurityClientServerLeak)
954        );
955        if let Some(token) = suppression.target_token() {
956            kinds.push(token);
957        }
958    }
959    let security_without_reason = names_security && reason.is_none();
960    Some(DiffRiskSuppression {
961        kinds,
962        reason,
963        security_without_reason,
964    })
965}
966
967fn finalize(
968    input: &DiffRiskInput<'_>,
969    files: &[FileTexts],
970    raw: Vec<RawFinding>,
971) -> Vec<DiffRiskFinding> {
972    let mut suppressions: FxHashMap<&str, Vec<Suppression>> = FxHashMap::default();
973    let head_exists: FxHashMap<&str, bool> = files
974        .iter()
975        .map(|file| (file.rel.as_str(), file.head.is_some()))
976        .collect();
977    for file in files {
978        if let Some(head) = file.head.as_deref() {
979            suppressions.insert(
980                file.rel.as_str(),
981                fallow_engine::source::suppressions_from_text(&file.abs, head),
982            );
983        }
984    }
985    let mut findings: Vec<DiffRiskFinding> = raw
986        .into_iter()
987        .filter_map(|finding| {
988            let rules = input.rules.for_path(&input.root.join(&finding.path));
989            let severity = stricter(rule_severity(&rules, finding.rule), finding.min_severity);
990            let severity = match severity {
991                Severity::Off => return None,
992                Severity::Warn => DiffRiskSeverity::Warn,
993                Severity::Error => DiffRiskSeverity::Error,
994            };
995            // A finding with a base severity floor reports a change of the
996            // config that judges it. A head comment or a head override cannot
997            // hide it, so it offers no suppression action.
998            let fixed_by_base = finding.min_severity.is_some();
999            let head_list = suppressions.get(finding.path.as_str());
1000            if !fixed_by_base
1001                && head_list.is_some_and(|list| is_suppressed(list, finding.rule, finding.line))
1002            {
1003                return None;
1004            }
1005            let exists = head_exists
1006                .get(finding.path.as_str())
1007                .copied()
1008                .unwrap_or(true);
1009            let actions = if fixed_by_base {
1010                Vec::new()
1011            } else {
1012                suppression_actions(finding.rule, &finding.path, finding.line, exists)
1013            };
1014            let suppression = head_list.and_then(|list| added_fallow_ignore(list, &finding));
1015            let message = if suppression
1016                .as_ref()
1017                .is_some_and(|detail| detail.security_without_reason)
1018            {
1019                SECURITY_WITHOUT_REASON_MESSAGE.to_owned()
1020            } else {
1021                finding.message
1022            };
1023            Some(DiffRiskFinding {
1024                rule: finding.rule,
1025                kind: finding.kind,
1026                path: finding.path,
1027                line: finding.line,
1028                message,
1029                evidence: finding.evidence,
1030                severity,
1031                introduced: true,
1032                related: finding.related,
1033                actions,
1034                suppression,
1035            })
1036        })
1037        .collect();
1038    findings.sort_by(|a, b| {
1039        a.path
1040            .cmp(&b.path)
1041            .then(a.line.cmp(&b.line))
1042            .then(a.rule.cmp(&b.rule))
1043            .then(a.kind.cmp(&b.kind))
1044            .then(a.evidence.cmp(&b.evidence))
1045    });
1046    findings
1047}
1048
1049/// The comment markers of a file type, `None` when the file cannot hold a
1050/// suppression comment.
1051fn comment_markers(rel: &str) -> Option<(&'static str, &'static str)> {
1052    match extension(rel) {
1053        "css" | "scss" | "sass" | "less" => Some(("/* ", " */")),
1054        "html" => Some(("<!-- ", " -->")),
1055        _ if is_source_file(rel) => Some(("// ", "")),
1056        _ => None,
1057    }
1058}
1059
1060fn suppression_actions(
1061    rule: DiffRiskRule,
1062    path: &str,
1063    line: Option<u32>,
1064    head_exists: bool,
1065) -> Vec<DiffRiskAction> {
1066    let code = rule.code();
1067    let markers = comment_markers(path).filter(|_| head_exists);
1068    let Some((open, close)) = markers else {
1069        return vec![DiffRiskAction {
1070            kind: DiffRiskActionType::SuppressInConfig,
1071            auto_fixable: false,
1072            description: format!(
1073                "Set `{code}` to `off` for `{path}` in an `overrides` entry of the Fallow config"
1074            ),
1075            comment: None,
1076        }];
1077    };
1078    let mut actions = Vec::new();
1079    if line.is_some() {
1080        actions.push(DiffRiskAction {
1081            kind: DiffRiskActionType::SuppressLine,
1082            auto_fixable: false,
1083            description: format!("Suppress this `{code}` finding with a comment above the line"),
1084            comment: Some(format!("{open}fallow-ignore-next-line {code}{close}")),
1085        });
1086    }
1087    actions.push(DiffRiskAction {
1088        kind: DiffRiskActionType::SuppressFile,
1089        auto_fixable: false,
1090        description: format!("Suppress `{code}` for the whole file"),
1091        comment: Some(format!("{open}fallow-ignore-file {code}{close}")),
1092    });
1093    actions
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098    use super::*;
1099
1100    fn suppressions(src: &str) -> Vec<Suppression> {
1101        fallow_engine::source::suppressions_from_text(Path::new("src/a.test.ts"), src)
1102    }
1103
1104    fn file(rel: &str, base: &str, head: &str) -> FileTexts {
1105        FileTexts {
1106            rel: rel.to_owned(),
1107            abs: PathBuf::from("/project").join(rel),
1108            base: Some(base.to_owned()),
1109            head: Some(head.to_owned()),
1110        }
1111    }
1112
1113    fn rules_of(raw: &[RawFinding]) -> Vec<(DiffRiskRule, &str)> {
1114        raw.iter()
1115            .map(|finding| (finding.rule, finding.evidence.as_str()))
1116            .collect()
1117    }
1118
1119    #[test]
1120    fn only_files_a_rule_reads_are_relevant() {
1121        let root = Path::new("/project");
1122        for rel in [
1123            "src/a.ts",
1124            "src/a.test.ts",
1125            "src/page.mdx",
1126            "src/query.graphql",
1127            "styles/app.css",
1128            "package.json",
1129            "packages/ui/package.json",
1130            "vitest.config.ts",
1131            ".nycrc",
1132            ".fallowrc.json",
1133        ] {
1134            assert!(is_rule_relevant(root, rel), "{rel} must be read");
1135        }
1136        for rel in [
1137            "pnpm-lock.yaml",
1138            "package-lock.json",
1139            "yarn.lock",
1140            "assets/logo.png",
1141            "fonts/inter.woff2",
1142            "README.md",
1143        ] {
1144            assert!(!is_rule_relevant(root, rel), "{rel} must not be read");
1145        }
1146    }
1147
1148    fn removed_test_findings(files: &[FileTexts]) -> Vec<(String, String)> {
1149        removed_test_findings_in(Path::new("/project"), files)
1150    }
1151
1152    fn removed_test_findings_in(root: &Path, files: &[FileTexts]) -> Vec<(String, String)> {
1153        let mut raw = Vec::new();
1154        detect_removed_tests(root, files, &mut raw);
1155        let mut found: Vec<(String, String)> = raw
1156            .into_iter()
1157            .map(|finding| (finding.path, finding.evidence))
1158            .collect();
1159        found.sort_unstable();
1160        found
1161    }
1162
1163    fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
1164        list.iter()
1165            .map(|(a, b)| ((*a).to_owned(), (*b).to_owned()))
1166            .collect()
1167    }
1168
1169    const ERRORS_BASE: &str = "export const ERR_A = 'a';\nexport const ERR_GONE = 'gone';\n";
1170    const ERRORS_HEAD: &str = "export const ERR_A = 'a';\n";
1171    const ERRORS_TEST_BASE: &str = "test('ERR_A', () => {\n  expect(ERR_A).toBe('a');\n});\ntest('ERR_GONE', () => {\n  expect(ERR_GONE).toBe('gone');\n});\n";
1172    const ERRORS_TEST_HEAD: &str = "test('ERR_A', () => {\n  expect(ERR_A).toBe('a');\n});\n";
1173
1174    #[test]
1175    fn tests_removed_with_the_source_name_they_cover_are_not_reported() {
1176        let files = [
1177            file("src/errors.ts", ERRORS_BASE, ERRORS_HEAD),
1178            file("src/errors.test.ts", ERRORS_TEST_BASE, ERRORS_TEST_HEAD),
1179        ];
1180        assert!(removed_test_findings(&files).is_empty());
1181    }
1182
1183    #[test]
1184    fn tests_removed_while_their_source_name_stays_are_reported() {
1185        let files = [
1186            file("src/errors.ts", ERRORS_BASE, ERRORS_BASE),
1187            file("src/errors.test.ts", ERRORS_TEST_BASE, ERRORS_TEST_HEAD),
1188        ];
1189        assert_eq!(
1190            removed_test_findings(&files),
1191            pairs(&[("src/errors.test.ts", "test cases: 2 -> 1")])
1192        );
1193    }
1194
1195    #[test]
1196    fn assertions_removed_with_the_source_name_they_cover_are_not_reported() {
1197        let base = "test('errors', () => {\n  expect(ERR_A).toBe('a');\n  expect(ERR_GONE).toBe('gone');\n});\n";
1198        let head = "test('errors', () => {\n  expect(ERR_A).toBe('a');\n});\n";
1199        let files = [
1200            file("src/errors.ts", ERRORS_BASE, ERRORS_HEAD),
1201            file("src/errors.test.ts", base, head),
1202        ];
1203        assert!(removed_test_findings(&files).is_empty());
1204        let files = [
1205            file("src/errors.ts", ERRORS_BASE, ERRORS_BASE),
1206            file("src/errors.test.ts", base, head),
1207        ];
1208        assert_eq!(
1209            removed_test_findings(&files),
1210            pairs(&[("src/errors.test.ts", "assertions: 2 -> 1")])
1211        );
1212    }
1213
1214    #[test]
1215    fn tests_removed_with_a_deleted_fixture_directory_are_not_reported() {
1216        let base = "test('a', () => run('basic'));\ntest('legacy', () => run('legacy-types'));\n";
1217        let head = "test('a', () => run('basic'));\n";
1218        let files = [
1219            file("test/package.spec.js", base, head),
1220            FileTexts {
1221                rel: "test/fixtures/legacy-types/src/index.ts".to_owned(),
1222                abs: PathBuf::from("/project/test/fixtures/legacy-types/src/index.ts"),
1223                base: Some("export const a = 1;\n".to_owned()),
1224                head: None,
1225            },
1226        ];
1227        assert!(removed_test_findings(&files).is_empty());
1228    }
1229
1230    #[test]
1231    fn assertions_that_leave_with_rewritten_setup_code_are_not_reported() {
1232        let base = "test('creates', async () => {\n  const response = await client.post('/api').send({ query: CREATE });\n  expect(response.body.errors).toBeUndefined();\n  const id = response.body.data.create.id;\n  expect(await read(id)).toEqual({ id });\n});\n";
1233        let head = "test('creates', async () => {\n  const { id } = await createRecord();\n  expect(await read(id)).toEqual({ id });\n});\n";
1234        let files = [file("test/create.spec.ts", base, head)];
1235        assert!(removed_test_findings(&files).is_empty());
1236        let head = "test('creates', async () => {\n  const response = await client.post('/api').send({ query: CREATE });\n  const id = response.body.data.create.id;\n});\n";
1237        let files = [file("test/create.spec.ts", base, head)];
1238        assert_eq!(
1239            removed_test_findings(&files),
1240            pairs(&[("test/create.spec.ts", "assertions: 2 -> 0")])
1241        );
1242    }
1243
1244    #[test]
1245    fn tests_of_a_call_that_one_source_file_dropped_are_not_reported() {
1246        let hook_base = "export const useCommands = () => {\n  const enabled = useIsFeatureEnabled('CORE');\n  return enabled ? commands : [];\n};\n";
1247        let hook_head = "export const useCommands = () => commands;\n";
1248        let other = "export const usePage = () => useIsFeatureEnabled('PAGE');\n";
1249        let test_base = "jest.mock('./flags', () => ({ useIsFeatureEnabled: () => flag() }));\nit('shows commands', () => {\n  expect(useCommands()).toEqual(commands);\n});\nit('hides commands with the flag off', () => {\n  flag.mockReturnValue(false);\n  expect(useCommands()).toEqual([]);\n});\n";
1250        let test_head =
1251            "it('shows commands', () => {\n  expect(useCommands()).toEqual(commands);\n});\n";
1252        let files = [
1253            file("src/useCommands.ts", hook_base, hook_head),
1254            file("src/usePage.ts", other, other),
1255            file("src/useCommands.test.ts", test_base, test_head),
1256        ];
1257        assert!(removed_test_findings(&files).is_empty());
1258    }
1259
1260    #[test]
1261    fn words_in_comments_and_test_titles_do_not_explain_a_removal() {
1262        let source_base =
1263            "// Hide the items when the page is disabled.\nexport const items = (all) => all;\n";
1264        let source_head = "export const items = (all) => all;\n";
1265        let test_base = "it('keeps items', () => {\n  expect(items([1])).toEqual([1]);\n});\nit('keeps items when the page is disabled', () => {\n  expect(items([])).toEqual([]);\n});\n";
1266        let test_head = "it('keeps items', () => {\n  expect(items([1])).toEqual([1]);\n});\n";
1267        let files = [
1268            file("src/items.ts", source_base, source_head),
1269            file("src/items.test.ts", test_base, test_head),
1270        ];
1271        assert_eq!(
1272            removed_test_findings(&files),
1273            pairs(&[("src/items.test.ts", "test cases: 2 -> 1")])
1274        );
1275    }
1276
1277    #[test]
1278    fn a_deleted_test_file_does_not_explain_its_own_removal() {
1279        let files = [FileTexts {
1280            rel: "src/zero.test.ts".to_owned(),
1281            abs: PathBuf::from("/project/src/zero.test.ts"),
1282            base: Some("import { price } from './zero';\nit('keeps zero', () => {\n  expect(price(0)).toBe(0);\n});\n".to_owned()),
1283            head: None,
1284        }];
1285        assert_eq!(
1286            removed_test_findings(&files),
1287            pairs(&[("src/zero.test.ts", "test cases: 1 -> 0")])
1288        );
1289    }
1290
1291    fn deleted(rel: &str, base: &str) -> FileTexts {
1292        FileTexts {
1293            rel: rel.to_owned(),
1294            abs: PathBuf::from("/project").join(rel),
1295            base: Some(base.to_owned()),
1296            head: None,
1297        }
1298    }
1299
1300    #[test]
1301    fn an_unrelated_deleted_source_file_does_not_explain_a_deleted_test_file() {
1302        let files = [
1303            deleted(
1304                "src/legacy.ts",
1305                "import { a } from './a';\nimport { price } from './price';\nexport const legacy = price(a);\n",
1306            ),
1307            deleted(
1308                "src/price.test.ts",
1309                "import { price } from './price';\nit('keeps zero', () => {\n  expect(price(0)).toBe(0);\n});\n",
1310            ),
1311        ];
1312        assert_eq!(
1313            removed_test_findings(&files),
1314            pairs(&[("src/price.test.ts", "test cases: 1 -> 0")])
1315        );
1316    }
1317
1318    #[test]
1319    fn a_name_that_a_changed_file_still_holds_does_not_explain_a_removal() {
1320        let files = [
1321            deleted("src/legacy.ts", "export const formatPrice = (n) => n;\n"),
1322            file(
1323                "src/format.ts",
1324                "export const format = (n) => n;\n",
1325                "export const formatPrice = (n) => n;\n",
1326            ),
1327            file(
1328                "src/format.test.ts",
1329                "it('formats', () => {\n  expect(formatPrice(1)).toBe(1);\n});\n",
1330                "",
1331            ),
1332        ];
1333        assert_eq!(
1334            removed_test_findings(&files),
1335            pairs(&[("src/format.test.ts", "test cases: 1 -> 0")])
1336        );
1337    }
1338
1339    #[test]
1340    fn a_deleted_directory_name_matches_whole_path_segments_only() {
1341        let root = tempfile::tempdir().expect("tempdir");
1342        let base =
1343            "it('a', () => run());\nit('scores', () => {\n  expect(score(1)).toBe(1);\n});\n";
1344        let head = "it('a', () => run());\n";
1345        let files = [
1346            file("src/score.test.ts", base, head),
1347            deleted("src/core/x.ts", "export const x = 1;\n"),
1348        ];
1349        assert_eq!(
1350            removed_test_findings_in(root.path(), &files),
1351            pairs(&[("src/score.test.ts", "test cases: 2 -> 1")])
1352        );
1353        let base =
1354            "import { a } from '../core/a';\nit('a', () => run(a));\nit('b', () => run(b));\n";
1355        let head = "it('a', () => run(a));\n";
1356        let files = [
1357            file("src/run.test.ts", base, head),
1358            deleted("src/core/x.ts", "export const x = 1;\n"),
1359        ];
1360        assert!(removed_test_findings_in(root.path(), &files).is_empty());
1361    }
1362
1363    #[test]
1364    fn a_directory_that_still_exists_does_not_explain_a_removal() {
1365        let root = tempfile::tempdir().expect("tempdir");
1366        std::fs::create_dir_all(root.path().join("src/components")).expect("components dir");
1367        let files = [
1368            deleted(
1369                "src/components/Legacy.tsx",
1370                "export const Legacy = () => null;\n",
1371            ),
1372            deleted(
1373                "src/__tests__/button.test.tsx",
1374                "import { Button } from '../components/Button';\nit('renders', () => {\n  expect(Button()).toBeTruthy();\n});\n",
1375            ),
1376        ];
1377        assert_eq!(
1378            removed_test_findings_in(root.path(), &files),
1379            pairs(&[("src/__tests__/button.test.tsx", "test cases: 1 -> 0")])
1380        );
1381    }
1382
1383    #[test]
1384    fn edited_story_copy_is_not_a_diverged_clone() {
1385        for rel in [
1386            "apps/storybook/stories/select.stories.tsx",
1387            "src/button.story.tsx",
1388        ] {
1389            assert!(is_example_copy(Path::new("/project"), rel), "{rel}");
1390        }
1391        assert!(!is_example_copy(Path::new("/project"), "src/store.ts"));
1392    }
1393
1394    #[test]
1395    fn tool_config_names_match_config_and_dot_rc_files_only() {
1396        for name in [
1397            "vite.config.ts",
1398            "pkg/karma.conf.js",
1399            ".eslintrc.js",
1400            "pkg/.mocharc.cjs",
1401        ] {
1402            assert!(is_tool_config(name), "{name}");
1403        }
1404        for name in ["src.ts", "src/arc.ts", "lib/orc.js", "src/index.ts"] {
1405            assert!(!is_tool_config(name), "{name}");
1406        }
1407    }
1408
1409    #[test]
1410    fn suppressions_in_fixture_and_generated_files_are_not_reported() {
1411        let head = "// @ts-nocheck\nexport const a = 1;\n";
1412        let mut raw = Vec::new();
1413        let root = Path::new("/project");
1414        let rules = RulesConfig::default();
1415        for rel in [
1416            "src/__tests__/upstream/fixture/generated/schema.ts",
1417            "test/fixtures/app/src/index.ts",
1418            "src/__generated__/graphql.ts",
1419            "src/generated/client.ts",
1420        ] {
1421            detect_file(root, &file(rel, "", head), &rules, &mut raw);
1422        }
1423        assert!(raw.is_empty(), "{:?}", rules_of(&raw));
1424        detect_file(root, &file("src/schema.ts", "", head), &rules, &mut raw);
1425        assert_eq!(
1426            rules_of(&raw),
1427            vec![(DiffRiskRule::AddedSuppression, "@ts-nocheck")]
1428        );
1429    }
1430
1431    #[test]
1432    fn ts_expect_error_in_type_tests_is_an_assertion_not_a_suppression() {
1433        let head = "// @ts-expect-error\nconst x: string = 1;\n";
1434        let mut raw = Vec::new();
1435        let root = Path::new("/project");
1436        let rules = RulesConfig::default();
1437        detect_file(root, &file("test-d/hooks.ts", "", head), &rules, &mut raw);
1438        detect_file(root, &file("src/a.test-d.ts", "", head), &rules, &mut raw);
1439        detect_file(root, &file("src/a.test.ts", "", head), &rules, &mut raw);
1440        assert!(raw.is_empty(), "{:?}", rules_of(&raw));
1441        detect_file(root, &file("src/a.ts", "", head), &rules, &mut raw);
1442        assert_eq!(
1443            rules_of(&raw),
1444            vec![(DiffRiskRule::AddedSuppression, "@ts-expect-error")]
1445        );
1446    }
1447
1448    /// A test file in another language (a Rust integration test under
1449    /// `tests/`) can hold JavaScript test text in a string. The test rules
1450    /// read JavaScript-family test files only.
1451    #[test]
1452    fn test_rules_read_javascript_test_files_only() {
1453        let root = Path::new("/project");
1454        let rules = RulesConfig::default();
1455        let base = "it('a', f);\nit('b', f);\n";
1456        let head = "it.skip('a', f);\n";
1457        let mut raw = Vec::new();
1458        let rust = file("crates/cli/tests/integration/a_tests.rs", base, head);
1459        detect_file(root, &rust, &rules, &mut raw);
1460        detect_removed_tests(root, std::slice::from_ref(&rust), &mut raw);
1461        assert!(raw.is_empty(), "{:?}", rules_of(&raw));
1462
1463        let js = file("src/a.test.ts", base, head);
1464        detect_file(root, &js, &rules, &mut raw);
1465        detect_removed_tests(root, std::slice::from_ref(&js), &mut raw);
1466        assert_eq!(
1467            rules_of(&raw),
1468            vec![
1469                (DiffRiskRule::WeakenedTests, "it.skip"),
1470                (DiffRiskRule::WeakenedTests, "test cases: 2 -> 1"),
1471            ]
1472        );
1473    }
1474
1475    #[test]
1476    fn named_line_suppression_hides_the_finding() {
1477        let list = suppressions("// fallow-ignore-next-line weakened-tests\nit.skip('a', f);\n");
1478        assert!(is_suppressed(&list, DiffRiskRule::WeakenedTests, Some(2)));
1479        assert!(!is_suppressed(&list, DiffRiskRule::TestOnlyBranch, Some(2)));
1480    }
1481
1482    #[test]
1483    fn file_suppression_hides_a_file_level_finding() {
1484        let list = suppressions("// fallow-ignore-file weakened-tests\n");
1485        assert!(is_suppressed(&list, DiffRiskRule::WeakenedTests, None));
1486    }
1487
1488    fn added(evidence: &str, line: u32) -> RawFinding {
1489        RawFinding {
1490            rule: DiffRiskRule::AddedSuppression,
1491            kind: None,
1492            path: "src/a.ts".to_owned(),
1493            line: Some(line),
1494            message: String::new(),
1495            evidence: evidence.to_owned(),
1496            related: Vec::new(),
1497            min_severity: None,
1498        }
1499    }
1500
1501    #[test]
1502    fn added_fallow_ignore_reads_kinds_and_reason() {
1503        let list = suppressions(
1504            "// fallow-ignore-next-line unused-export, security-sink\nexport const a = 1;\n// fallow-ignore-file\n// fallow-ignore-next-line security-client-server-leak -- reviewed\nconst b = 1;\n",
1505        );
1506        let mixed = added_fallow_ignore(&list, &added("fallow-ignore", 1)).expect("parsed");
1507        assert_eq!(mixed.kinds, vec!["unused-export", "security-sink"]);
1508        assert!(mixed.security_without_reason);
1509
1510        let blanket = added_fallow_ignore(&list, &added("fallow-ignore", 3)).expect("parsed");
1511        assert!(blanket.kinds.is_empty());
1512        assert!(!blanket.security_without_reason);
1513
1514        let reasoned = added_fallow_ignore(&list, &added("fallow-ignore", 4)).expect("parsed");
1515        assert_eq!(reasoned.reason.as_deref(), Some("reviewed"));
1516        assert!(!reasoned.security_without_reason);
1517
1518        assert!(added_fallow_ignore(&list, &added("eslint-disable", 1)).is_none());
1519        assert!(added_fallow_ignore(&list, &added("fallow-ignore", 2)).is_none());
1520    }
1521
1522    #[test]
1523    fn blanket_suppression_does_not_hide_an_added_suppression() {
1524        let list = suppressions("// fallow-ignore-file\nconst a = 1;\n");
1525        assert!(!is_suppressed(
1526            &list,
1527            DiffRiskRule::AddedSuppression,
1528            Some(1)
1529        ));
1530        assert!(is_suppressed(&list, DiffRiskRule::TestOnlyBranch, Some(2)));
1531    }
1532
1533    #[test]
1534    fn a_marker_in_a_template_literal_suppresses_nothing() {
1535        let list = suppressions("export const docs = `\n// fallow-ignore-file\n`;\n");
1536        assert!(list.is_empty(), "{list:?}");
1537    }
1538
1539    #[test]
1540    fn json_and_deleted_files_get_a_config_action() {
1541        let actions =
1542            suppression_actions(DiffRiskRule::AddedDependency, "package.json", Some(3), true);
1543        assert_eq!(actions.len(), 1);
1544        assert_eq!(actions[0].kind, DiffRiskActionType::SuppressInConfig);
1545        let actions = suppression_actions(DiffRiskRule::WeakenedTests, "a.test.ts", None, false);
1546        assert_eq!(actions[0].kind, DiffRiskActionType::SuppressInConfig);
1547    }
1548
1549    #[test]
1550    fn source_files_get_line_and_file_comments() {
1551        let actions = suppression_actions(DiffRiskRule::TestOnlyBranch, "src/a.ts", Some(3), true);
1552        let comments: Vec<_> = actions
1553            .iter()
1554            .filter_map(|a| a.comment.as_deref())
1555            .collect();
1556        assert_eq!(
1557            comments,
1558            vec![
1559                "// fallow-ignore-next-line test-only-branch",
1560                "// fallow-ignore-file test-only-branch"
1561            ]
1562        );
1563        let actions =
1564            suppression_actions(DiffRiskRule::AddedSuppression, "src/a.css", Some(3), true);
1565        assert_eq!(
1566            actions[0].comment.as_deref(),
1567            Some("/* fallow-ignore-next-line added-suppression */")
1568        );
1569    }
1570}