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