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