Skip to main content

fallow_api/diff_risk/
text.rs

1//! Line-level detectors over the base and head text of one changed file.
2//!
3//! The detectors are syntactic. They compare token counts and added lines,
4//! and they do not parse the file. A line counts as added when its trimmed
5//! text occurs more often in head than in base, so a moved line is not added.
6
7use rustc_hash::{FxHashMap, FxHashSet};
8
9/// One detector hit on a head line.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct LineHit {
12    /// 1-based head line.
13    pub line: u32,
14    /// The token or value change that supports the hit.
15    pub evidence: String,
16}
17
18/// Roots of a test-case call: `it(...)`, `test.skip(...)`.
19const TEST_CASE_ROOTS: &[&str] = &["it", "test", "specify", "xit", "xtest", "fit"];
20/// Roots of a suite call that can carry a skip or focus marker.
21const SUITE_ROOTS: &[&str] = &["describe", "suite", "context"];
22/// Roots that skip or focus by name alone.
23const PREFIXED_ROOTS: &[&str] = &["xit", "xtest", "xdescribe", "fit", "fdescribe"];
24/// Members that keep a call a test case (`it.each`, `test.concurrent`).
25const TEST_CASE_MEMBERS: &[&str] = &[
26    "skip",
27    "only",
28    "each",
29    "todo",
30    "concurrent",
31    "sequential",
32    "fails",
33    "failing",
34    "fixme",
35    "skipIf",
36    "runIf",
37    // `@effect/vitest`: `it.effect`, `it.live`, `it.scoped`, `it.scopedLive`
38    // and the property test `it.prop`. `it.layer` and `it.flakyTest` do not
39    // register a test, so they stay out.
40    "effect",
41    "live",
42    "scoped",
43    "scopedLive",
44    "prop",
45];
46/// Members of `expect` that are an assertion (`expect.soft(x)`).
47const EXPECT_ASSERTION_MEMBERS: &[&str] = &["soft", "poll"];
48
49/// Comment tokens that turn off a check. `fallow-ignore` has its own rule.
50const SUPPRESSION_TOKENS: &[&str] = &[
51    "eslint-disable",
52    "oxlint-disable",
53    "biome-ignore",
54    "deno-lint-ignore",
55    "@ts-ignore",
56    "@ts-expect-error",
57    "@ts-nocheck",
58    "istanbul ignore",
59    "c8 ignore",
60    "v8 ignore",
61    fallow_types::inline_threshold::INLINE_THRESHOLD_MARKER,
62];
63pub(crate) const FALLOW_IGNORE_TOKEN: &str = "fallow-ignore";
64/// Suppression tokens of the diff-risk rules. A `fallow-ignore` comment that
65/// names only these is the suppression the findings ask for, so it is not an
66/// added suppression itself.
67const DIFF_RISK_TOKENS: &[&str] = &[
68    "weakened-tests",
69    "added-suppression",
70    "test-only-branch",
71    "diverged-clone-sibling",
72    "added-dependency",
73];
74
75/// Threshold keys where a lower value is less strict.
76const MIN_THRESHOLD_KEYS: &[&str] = &[
77    "branches",
78    "functions",
79    "lines",
80    "statements",
81    "minScore",
82    "min-score",
83    "minCoverage",
84    "min-coverage",
85];
86/// Threshold keys where a higher value is less strict.
87const MAX_THRESHOLD_KEYS: &[&str] = &[
88    "maxCrap",
89    "max-crap",
90    "maxCyclomatic",
91    "max-cyclomatic",
92    "maxCognitive",
93    "max-cognitive",
94];
95
96/// Lines of `head` that do not occur in `base`, as `(1-based line, text)`.
97///
98/// Lines compare by trimmed text as a multiset. When head has more copies of
99/// a line than base, the last copies count as added. Blank lines never count.
100#[must_use]
101pub fn added_lines<'a>(base: &str, head: &'a str) -> Vec<(u32, &'a str)> {
102    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
103    for line in base.lines() {
104        *remaining.entry(line.trim()).or_default() += 1;
105    }
106    let mut head_counts: FxHashMap<&str, usize> = FxHashMap::default();
107    for line in head.lines() {
108        *head_counts.entry(line.trim()).or_default() += 1;
109    }
110    // The number of leading copies of each text that base already holds.
111    let mut kept: FxHashMap<&str, usize> = head_counts
112        .iter()
113        .map(|(text, count)| {
114            let in_base = remaining.get(text).copied().unwrap_or(0);
115            (*text, (*count).min(in_base))
116        })
117        .collect();
118    let mut added = Vec::new();
119    for (index, line) in head.lines().enumerate() {
120        let text = line.trim();
121        if text.is_empty() {
122            continue;
123        }
124        let keep = kept.entry(text).or_default();
125        if *keep > 0 {
126            *keep -= 1;
127            continue;
128        }
129        added.push((line_number(index), line));
130    }
131    added
132}
133
134/// The identifier tokens in the code of `src`. Comments and the content of
135/// string literals do not count, so a word in a test title or a comment is
136/// not an identifier. A token that starts with a digit is a number.
137#[must_use]
138pub fn code_identifiers(src: &str) -> FxHashSet<String> {
139    let mut found = FxHashSet::default();
140    for line in src.lines() {
141        let code = blank_string_literals(code_part(line));
142        found.extend(
143            code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
144                .filter(|token| {
145                    token
146                        .bytes()
147                        .next()
148                        .is_some_and(|byte| !byte.is_ascii_digit())
149                })
150                .map(str::to_owned),
151        );
152    }
153    found
154}
155
156/// Added lines of a test file that add a skip or focus marker.
157///
158/// A marker is the first skip or focus chain on a line, with the first string
159/// literal of that line as its title. Markers compare as a multiset, not as
160/// line text. So a base marker on a line that the change edits in another
161/// place (a callback that becomes `async`, a new title, a reformat) is not
162/// added. An added marker first matches a base marker with the same chain
163/// and title, then a base marker with the same chain only. The chain-only
164/// match covers a renamed test. It does not apply to a base marker whose
165/// title is a plain test or suite call in the head: that skip moved to
166/// another test, so the added marker skips a test that ran before.
167#[must_use]
168pub fn skip_only_hits(base: &str, head: &str) -> Vec<LineHit> {
169    let mut pool: FxHashMap<SkipMarker<'_>, usize> = FxHashMap::default();
170    for marker in base.lines().filter_map(skip_marker) {
171        *pool.entry(marker).or_default() += 1;
172    }
173    let added = added_lines(base, head);
174    let added_numbers: FxHashSet<u32> = added.iter().map(|(line, _)| *line).collect();
175    // A head line that the change kept holds a base marker already.
176    for (index, line) in head.lines().enumerate() {
177        if added_numbers.contains(&line_number(index)) {
178            continue;
179        }
180        if let Some(marker) = skip_marker(line) {
181            take_marker(&mut pool, &marker);
182        }
183    }
184    let mut candidates: Vec<(u32, SkipMarker<'_>)> = added
185        .into_iter()
186        .filter_map(|(line, text)| skip_marker(text).map(|marker| (line, marker)))
187        .collect();
188    candidates.retain(|(_, marker)| !take_marker(&mut pool, marker));
189    let plain_titles: FxHashSet<&str> = head.lines().filter_map(plain_title).collect();
190    pool.retain(|marker, _| {
191        marker
192            .title
193            .is_none_or(|title| !plain_titles.contains(title))
194    });
195    candidates.retain(|(_, marker)| !take_chain(&mut pool, &marker.chain));
196    candidates
197        .into_iter()
198        .map(|(line, marker)| LineHit {
199            line,
200            evidence: marker.chain,
201        })
202        .collect()
203}
204
205/// A skip or focus marker on one line: the chain text (`it.skip`) and the
206/// first string literal of the line, when the line has one.
207#[derive(Debug, Clone, PartialEq, Eq, Hash)]
208struct SkipMarker<'a> {
209    chain: String,
210    title: Option<&'a str>,
211}
212
213fn skip_marker(line: &str) -> Option<SkipMarker<'_>> {
214    let code = code_part(line);
215    let chain = call_chains(code)
216        .into_iter()
217        .find(|chain| is_skip_or_focus(chain))?;
218    Some(SkipMarker {
219        chain: chain.join("."),
220        title: first_string_literal(code),
221    })
222}
223
224/// The title of a test or suite call without a skip or focus marker.
225fn plain_title(line: &str) -> Option<&str> {
226    if skip_marker(line).is_some() {
227        return None;
228    }
229    let code = code_part(line);
230    call_chains(code).into_iter().find(|chain| {
231        chain
232            .first()
233            .is_some_and(|root| TEST_CASE_ROOTS.contains(root) || SUITE_ROOTS.contains(root))
234    })?;
235    first_string_literal(code)
236}
237
238/// Removes one copy of `marker` from `pool`. Returns whether a copy was there.
239fn take_marker<'a>(pool: &mut FxHashMap<SkipMarker<'a>, usize>, marker: &SkipMarker<'a>) -> bool {
240    match pool.get_mut(marker) {
241        Some(count) if *count > 0 => {
242            *count -= 1;
243            true
244        }
245        _ => false,
246    }
247}
248
249/// Removes one copy of any marker with `chain` from `pool`. Returns whether a
250/// copy was there. The lowest title goes first, so the result is stable.
251fn take_chain(pool: &mut FxHashMap<SkipMarker<'_>, usize>, chain: &str) -> bool {
252    let key = pool
253        .iter()
254        .filter(|(marker, count)| marker.chain == chain && **count > 0)
255        .map(|(marker, _)| marker.clone())
256        .min_by(|a, b| a.title.cmp(&b.title));
257    key.is_some_and(|key| take_marker(pool, &key))
258}
259
260/// The content of the first single-line string literal in `code`.
261fn first_string_literal(code: &str) -> Option<&str> {
262    let (start, quote) = code
263        .char_indices()
264        .find(|(_, c)| matches!(c, '\'' | '"' | '`'))?;
265    let body = start + quote.len_utf8();
266    let mut escaped = false;
267    for (offset, c) in code[body..].char_indices() {
268        if c == quote && !escaped {
269            return Some(&code[body..body + offset]);
270        }
271        escaped = !escaped && c == '\\';
272    }
273    None
274}
275
276/// The number of test-case calls in a test file, comments excluded.
277#[must_use]
278pub fn test_case_count(src: &str) -> usize {
279    src.lines()
280        .flat_map(|line| call_chains(code_part(line)))
281        .filter(|chain| is_test_case(chain))
282        .count()
283}
284
285/// The number of assertion calls (`expect(`, `assert`, `should`) in a test
286/// file, comments excluded.
287#[must_use]
288pub fn assertion_count(src: &str) -> usize {
289    src.lines()
290        .map(|line| {
291            let code = code_part(line);
292            let chains = call_chains(code)
293                .into_iter()
294                .filter(|chain| is_assertion(chain))
295                .count();
296            chains + member_should_count(code)
297        })
298        .sum()
299}
300
301/// The code lines that the change removed from a file, as `(assertion lines,
302/// code lines)`. Comment and blank lines do not count.
303#[must_use]
304pub fn removed_assertion_lines(base: &str, head: &str) -> (usize, usize) {
305    added_lines(head, base)
306        .into_iter()
307        .filter(|(_, line)| !code_part(line).trim().is_empty())
308        .fold((0, 0), |(asserts, code), (_, line)| {
309            (asserts + usize::from(assertion_count(line) > 0), code + 1)
310        })
311}
312
313/// Added comment lines that add a suppression.
314#[must_use]
315pub fn added_suppression_hits(base: &str, head: &str) -> Vec<LineHit> {
316    added_lines(base, head)
317        .into_iter()
318        .filter_map(|(line, text)| {
319            let comment = comment_part(text)?;
320            suppression_token(comment).map(|token| LineHit {
321                line,
322                evidence: token.to_owned(),
323            })
324        })
325        .collect()
326}
327
328/// Added lines of a non-test source file that branch on the test
329/// environment.
330#[must_use]
331pub fn test_only_branch_hits(base: &str, head: &str) -> Vec<LineHit> {
332    let head_lines: Vec<&str> = head.lines().collect();
333    added_lines(base, head)
334        .into_iter()
335        .filter_map(|(line, text)| {
336            let code = code_part(text);
337            let token = test_environment_token(code)?;
338            if picks_env_file(code) || only_quiets_logs(&head_lines, line) {
339                return None;
340            }
341            Some(LineHit {
342                line,
343                evidence: token.to_owned(),
344            })
345        })
346        .collect()
347}
348
349/// Whether a test-environment check picks an env file, such as
350/// `config({ path: NODE_ENV === 'test' ? '.env.test' : '.env' })`. That is
351/// configuration, not a code path.
352fn picks_env_file(code: &str) -> bool {
353    ["'.env", "\".env", "`.env"]
354        .iter()
355        .any(|literal| code.contains(literal))
356}
357
358/// The most lines that [`only_quiets_logs`] reads after a check.
359const MAX_GUARDED_LINES: usize = 12;
360
361/// Whether a negated test check (`!== 'test'`) guards only `console` calls.
362/// Then the tests only stay quiet, and production takes the same code path.
363fn only_quiets_logs(lines: &[&str], line: u32) -> bool {
364    let index = usize::try_from(line).unwrap_or(0).saturating_sub(1);
365    let Some(check) = lines.get(index) else {
366        return false;
367    };
368    let check = blank_string_literals(code_part(check));
369    if !check.contains("!=") {
370        return false;
371    }
372    if check.contains("console.") {
373        return true;
374    }
375    let mut body = lines
376        .iter()
377        .skip(index + 1)
378        .take(MAX_GUARDED_LINES)
379        .map(|line| code_part(line).trim())
380        .filter(|code| !code.is_empty() && !matches!(*code, "{" | ") {" | ")"));
381    if !body
382        .next()
383        .is_some_and(|first| first.starts_with("console."))
384    {
385        return false;
386    }
387    // The rest of the block holds only more `console` calls or the
388    // arguments of one: quoted text, closing parentheses or commas.
389    for code in body {
390        if code.starts_with('}') {
391            return true;
392        }
393        let continues = code.starts_with("console.")
394            || code.starts_with(['\'', '"', '`', ')', ','])
395            || code.ends_with(',');
396        if !continues {
397            return false;
398        }
399    }
400    false
401}
402
403/// Threshold values in a coverage or quality config that the change made
404/// less strict. Occurrences of one key pair up in file order.
405#[must_use]
406pub fn weakened_threshold_hits(base: &str, head: &str) -> Vec<LineHit> {
407    let mut hits = Vec::new();
408    for (keys, lower_is_weaker) in [(MIN_THRESHOLD_KEYS, true), (MAX_THRESHOLD_KEYS, false)] {
409        for key in keys {
410            let base_values = numeric_values_for_key(base, key);
411            let head_values = numeric_values_for_key(head, key);
412            for ((base_value, _), (head_value, head_line)) in
413                base_values.iter().zip(head_values.iter())
414            {
415                let weaker = if lower_is_weaker {
416                    head_value < base_value
417                } else {
418                    head_value > base_value
419                };
420                if weaker {
421                    hits.push(LineHit {
422                        line: *head_line,
423                        evidence: format!("{key}: {base_value} -> {head_value}"),
424                    });
425                }
426            }
427        }
428    }
429    hits.sort_by_key(|hit| hit.line);
430    hits
431}
432
433/// Whether `rel_path` names a test-runner, coverage or Fallow config file.
434#[must_use]
435pub fn is_coverage_config_path(rel_path: &str) -> bool {
436    let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
437    if rel_path.contains("node_modules/") {
438        return false;
439    }
440    const EXACT: &[&str] = &[
441        "package.json",
442        ".nycrc",
443        ".nycrc.json",
444        ".nycrc.yml",
445        ".nycrc.yaml",
446        ".c8rc",
447        ".c8rc.json",
448        ".fallowrc.json",
449        ".fallowrc.jsonc",
450        "fallow.toml",
451        ".fallow.toml",
452    ];
453    const PREFIXES: &[&str] = &[
454        "vitest.config.",
455        "vitest.workspace.",
456        "vite.config.",
457        "jest.config.",
458        "karma.conf.",
459        "playwright.config.",
460    ];
461    EXACT.contains(&name) || PREFIXES.iter().any(|prefix| name.starts_with(prefix))
462}
463
464fn line_number(index: usize) -> u32 {
465    u32::try_from(index + 1).unwrap_or(u32::MAX)
466}
467
468/// The code of a line before any comment. A line that starts inside a
469/// comment has no code.
470fn code_part(line: &str) -> &str {
471    let trimmed = line.trim_start();
472    if trimmed.starts_with("//")
473        || trimmed.starts_with("/*")
474        || trimmed.starts_with('*')
475        || trimmed.starts_with("<!--")
476    {
477        return "";
478    }
479    match comment_start(line) {
480        Some(start) => &line[..start],
481        None => line,
482    }
483}
484
485/// The comment of a line, from its first comment marker.
486fn comment_part(line: &str) -> Option<&str> {
487    let trimmed = line.trim_start();
488    if trimmed.starts_with('*') || trimmed.starts_with('#') {
489        return Some(trimmed);
490    }
491    comment_start(line).map(|start| &line[start..])
492}
493
494/// The byte offset of the first `//`, `/*` or `<!--` marker. A `//` right
495/// after `:` is a URL scheme, not a comment. A `//` or `/*` inside a
496/// single-line string literal is text, not a comment. The `<!--` search reads
497/// the raw line, because an apostrophe in markup text is not a quote.
498fn comment_start(line: &str) -> Option<usize> {
499    let code = blank_string_literals(line);
500    let bytes = code.as_bytes();
501    let mut index = 0;
502    let mut script = None;
503    while index + 1 < bytes.len() {
504        let pair = (bytes[index], bytes[index + 1]);
505        let is_line_comment = pair == (b'/', b'/') && (index == 0 || bytes[index - 1] != b':');
506        if is_line_comment || pair == (b'/', b'*') {
507            script = Some(index);
508            break;
509        }
510        index += 1;
511    }
512    let markup = line.find("<!--");
513    match (script, markup) {
514        (Some(a), Some(b)) => Some(a.min(b)),
515        (a, b) => a.or(b),
516    }
517}
518
519const fn is_ident_byte(byte: u8) -> bool {
520    byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
521}
522
523/// Every member chain in `code` that is called: `it.skip(` gives
524/// `["it", "skip"]`. A chain that follows a `.` is a member of another
525/// expression, so it is not a chain root.
526fn call_chains(code: &str) -> Vec<Vec<&str>> {
527    let bytes = code.as_bytes();
528    let mut chains = Vec::new();
529    let mut index = 0;
530    while index < bytes.len() {
531        let starts_ident = is_ident_byte(bytes[index])
532            && !bytes[index].is_ascii_digit()
533            && (index == 0 || (!is_ident_byte(bytes[index - 1]) && bytes[index - 1] != b'.'));
534        if !starts_ident {
535            index += 1;
536            continue;
537        }
538        let mut chain = Vec::new();
539        let mut cursor = index;
540        loop {
541            let start = cursor;
542            while cursor < bytes.len() && is_ident_byte(bytes[cursor]) {
543                cursor += 1;
544            }
545            chain.push(&code[start..cursor]);
546            if cursor + 1 < bytes.len() && bytes[cursor] == b'.' && is_ident_byte(bytes[cursor + 1])
547            {
548                cursor += 1;
549                continue;
550            }
551            break;
552        }
553        let next = code[cursor..].trim_start().bytes().next();
554        if matches!(next, Some(b'(' | b'`')) {
555            chains.push(chain);
556        }
557        index = cursor.max(index + 1);
558    }
559    chains
560}
561
562fn is_skip_or_focus(chain: &[&str]) -> bool {
563    let Some(root) = chain.first() else {
564        return false;
565    };
566    if PREFIXED_ROOTS.contains(root) {
567        return true;
568    }
569    (TEST_CASE_ROOTS.contains(root) || SUITE_ROOTS.contains(root))
570        && chain[1..]
571            .iter()
572            .any(|member| matches!(*member, "skip" | "only"))
573}
574
575fn is_test_case(chain: &[&str]) -> bool {
576    chain
577        .first()
578        .is_some_and(|root| TEST_CASE_ROOTS.contains(root))
579        && chain[1..]
580            .iter()
581            .all(|member| TEST_CASE_MEMBERS.contains(member))
582}
583
584fn is_assertion(chain: &[&str]) -> bool {
585    match chain {
586        ["expect"] | ["should" | "assert", ..] => true,
587        ["expect", member] => EXPECT_ASSERTION_MEMBERS.contains(member),
588        _ => false,
589    }
590}
591
592/// `x.should.equal(1)` style assertions: `.should` followed by `.` or `(`.
593fn member_should_count(code: &str) -> usize {
594    code.match_indices(".should")
595        .filter(|(start, token)| {
596            let after = code.as_bytes().get(start + token.len()).copied();
597            matches!(after, Some(b'.' | b'('))
598        })
599        .count()
600}
601
602/// The first suppression token in a comment, or `None`. A `fallow-ignore`
603/// marker that names only diff-risk rules is not a suppression here.
604fn suppression_token(comment: &str) -> Option<&'static str> {
605    let generic = SUPPRESSION_TOKENS
606        .iter()
607        .filter_map(|token| comment.find(token).map(|at| (at, *token)))
608        .min_by_key(|(at, _)| *at);
609    let fallow = comment
610        .find(FALLOW_IGNORE_TOKEN)
611        .filter(|at| !names_only_diff_risk_rules(&comment[*at..]))
612        .map(|at| (at, FALLOW_IGNORE_TOKEN));
613    [generic, fallow]
614        .into_iter()
615        .flatten()
616        .min_by_key(|(at, _)| *at)
617        .map(|(_, token)| token)
618}
619
620/// Whether a `fallow-ignore-*` directive lists only diff-risk tokens. A
621/// directive without tokens suppresses every rule, so it does not qualify.
622fn names_only_diff_risk_rules(directive: &str) -> bool {
623    let body = directive
624        .split_once("--")
625        .map_or(directive, |(tokens, _reason)| tokens);
626    let body = body
627        .trim_end()
628        .trim_end_matches("*/")
629        .trim_end_matches("-->");
630    let mut words = body.split_whitespace();
631    // The first word is the directive itself (`fallow-ignore-next-line`).
632    words.next();
633    let tokens: Vec<&str> = words
634        .flat_map(|word| word.split(','))
635        .filter(|token| !token.is_empty())
636        .collect();
637    !tokens.is_empty() && tokens.iter().all(|token| DIFF_RISK_TOKENS.contains(token))
638}
639
640/// The test-environment token in a line of code, or `None`.
641fn test_environment_token(code: &str) -> Option<&'static str> {
642    // The tokens count only outside string literals: a parser that compares
643    // source text with `'process.env.VITEST'` is not a test-only branch.
644    // `import.meta.vitest` is not a token: Vitest uses it to mark an in-source
645    // test block, which is test code and not a production branch.
646    let outside = blank_string_literals(code);
647    for token in ["process.env.VITEST", "process.env.JEST_WORKER_ID"] {
648        if outside.contains(token) {
649            return Some(token);
650        }
651    }
652    let compares_test = ["'test'", "\"test\"", "`test`"]
653        .iter()
654        .any(|literal| code.contains(literal))
655        && (outside.contains("==") || outside.contains("!="));
656    (outside.contains("process.env.NODE_ENV") && compares_test).then_some("process.env.NODE_ENV")
657}
658
659/// `code` with the content of each string literal on the line replaced by
660/// spaces. The quotes stay. A backslash escapes the next character. Each
661/// character becomes as many spaces as it has bytes, so byte offsets in the
662/// result are byte offsets in `code`.
663fn blank_string_literals(code: &str) -> String {
664    let mut out = String::with_capacity(code.len());
665    let mut quote: Option<char> = None;
666    let mut escaped = false;
667    for c in code.chars() {
668        let Some(open) = quote else {
669            if matches!(c, '\'' | '"' | '`') {
670                quote = Some(c);
671            }
672            out.push(c);
673            continue;
674        };
675        if c == open && !escaped {
676            quote = None;
677            out.push(c);
678            continue;
679        }
680        escaped = !escaped && c == '\\';
681        out.extend(std::iter::repeat_n(' ', c.len_utf8()));
682    }
683    out
684}
685
686/// Every numeric value that follows `key` as an object key, with its 1-based
687/// line. The key must stand alone: `lines` does not match `maxLines`.
688fn numeric_values_for_key(src: &str, key: &str) -> Vec<(f64, u32)> {
689    let mut values = Vec::new();
690    let mut line = 1u32;
691    let mut scanned = 0;
692    let mut search_from = 0;
693    while let Some(relative) = src[search_from..].find(key) {
694        let start = search_from + relative;
695        let end = start + key.len();
696        search_from = end;
697        let before = src[..start].bytes().next_back();
698        let after = src.as_bytes().get(end).copied();
699        let stands_alone = !before.is_some_and(|byte| is_ident_byte(byte) || byte == b'-')
700            && !after.is_some_and(|byte| is_ident_byte(byte) || byte == b'-');
701        if !stands_alone {
702            continue;
703        }
704        let rest = src[end..]
705            .trim_start_matches(['"', '\''])
706            .trim_start_matches([' ', '\t']);
707        let Some(rest) = rest.strip_prefix([':', '=']) else {
708            continue;
709        };
710        let rest = rest.trim_start_matches([' ', '\t', '"', '\'']);
711        let number: String = rest
712            .chars()
713            .take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
714            .collect();
715        let Ok(value) = number.parse::<f64>() else {
716            continue;
717        };
718        line += u32::try_from(src[scanned..start].matches('\n').count()).unwrap_or(0);
719        scanned = start;
720        values.push((value, line));
721    }
722    values
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728
729    #[test]
730    fn explain_text_names_every_detected_suppression_token() {
731        let full = crate::explain::AUDIT_RULES
732            .iter()
733            .find(|rule| rule.id == "fallow/added-suppression")
734            .map(|rule| rule.full)
735            .unwrap_or_default();
736        for token in SUPPRESSION_TOKENS.iter().chain([&FALLOW_IGNORE_TOKEN]) {
737            assert!(
738                full.contains(&format!("`{token}`")),
739                "the added-suppression explain text must name `{token}`"
740            );
741        }
742    }
743
744    #[test]
745    fn added_lines_ignore_moved_lines() {
746        let base = "a\nb\nc\n";
747        let head = "c\na\nb\nd\n";
748        assert_eq!(added_lines(base, head), vec![(4, "d")]);
749    }
750
751    #[test]
752    fn added_skip_and_only_markers_are_hits_at_their_line() {
753        let base = "it('a', () => {});\ntest('b', () => {});\n";
754        let head = "it.skip('a', () => {});\ntest.only('b', () => {});\nxit('c', f);\n";
755        let hits = skip_only_hits(base, head);
756        let evidence: Vec<(u32, &str)> = hits
757            .iter()
758            .map(|hit| (hit.line, hit.evidence.as_str()))
759            .collect();
760        assert_eq!(evidence, vec![(1, "it.skip"), (2, "test.only"), (3, "xit")]);
761    }
762
763    #[test]
764    fn existing_or_commented_skip_markers_are_not_hits() {
765        let base = "it.skip('a', () => {});\n";
766        let head = "// it.only('x')\nit.skip('a', () => {});\nconst profit = fit2(1);\n";
767        assert!(skip_only_hits(base, head).is_empty());
768    }
769
770    #[test]
771    fn existing_skip_on_a_changed_line_is_not_a_hit() {
772        let base = "it.skip('pending', () => {\n  expect(1).toBe(1);\n});\n";
773        let head = "it.skip('pending', async () => {\n  expect(1).toBe(1);\n});\n";
774        assert!(skip_only_hits(base, head).is_empty());
775    }
776
777    #[test]
778    fn existing_skip_with_a_new_title_is_not_a_hit() {
779        let base = "it('a', f);\ntest.only('old title', () => {});\n";
780        let head = "it('a', f);\ntest.only('new title', () => {});\n";
781        assert!(skip_only_hits(base, head).is_empty());
782    }
783
784    #[test]
785    fn moved_and_changed_skip_is_not_a_hit() {
786        let base = "it.skip('a', () => {});\nit('b', f);\n";
787        let head = "it('b', f);\nit.skip('a', async () => {});\n";
788        assert!(skip_only_hits(base, head).is_empty());
789    }
790
791    #[test]
792    fn new_skip_next_to_a_changed_existing_skip_is_one_hit() {
793        let base = "it.skip('a', () => {});\nit('b', () => {});\n";
794        let head = "it.skip('a', async () => {});\nit.skip('b', () => {});\n";
795        let hits = skip_only_hits(base, head);
796        let evidence: Vec<(u32, &str)> = hits
797            .iter()
798            .map(|hit| (hit.line, hit.evidence.as_str()))
799            .collect();
800        assert_eq!(evidence, vec![(2, "it.skip")]);
801    }
802
803    #[test]
804    fn skip_that_moves_to_another_test_is_a_hit() {
805        // The base skips 'doubles'. The head runs 'doubles' again and skips
806        // 'keeps zero'. So 'keeps zero' no longer runs.
807        let base = "it.skip('doubles', () => {});\nit('keeps zero', () => {});\n";
808        let head = "it('doubles', () => {});\nit.skip('keeps zero', () => {});\n";
809        let hits = skip_only_hits(base, head);
810        let evidence: Vec<(u32, &str)> = hits
811            .iter()
812            .map(|hit| (hit.line, hit.evidence.as_str()))
813            .collect();
814        assert_eq!(evidence, vec![(2, "it.skip")]);
815    }
816
817    #[test]
818    fn suite_skip_that_moves_to_another_suite_is_a_hit() {
819        let base = "describe.skip('a', () => {});\ndescribe('b', () => {});\n";
820        let head = "describe('a', () => {});\ndescribe.skip('b', () => {});\n";
821        let hits = skip_only_hits(base, head);
822        assert_eq!(hits.len(), 1);
823        assert_eq!(hits[0].line, 2);
824    }
825
826    #[test]
827    fn exact_title_match_wins_over_a_chain_match() {
828        // Base has one `it.skip('a')`. Head changes that line and adds a new
829        // `it.skip('c')` before it. The finding must go to the new title.
830        let base = "it.skip('a', () => {});\n";
831        let head = "it.skip('c', () => {});\nit.skip('a', async () => {});\n";
832        let hits = skip_only_hits(base, head);
833        let evidence: Vec<(u32, &str)> = hits
834            .iter()
835            .map(|hit| (hit.line, hit.evidence.as_str()))
836            .collect();
837        assert_eq!(evidence, vec![(1, "it.skip")]);
838    }
839
840    #[test]
841    fn test_case_count_counts_cases_with_modifiers_only() {
842        let src = "describe('s', () => {\n  it('a', f);\n  it.skip('b', f);\n  test.each([1])('c', f);\n  test.describe('d', f);\n  submit(1);\n  // it('commented', f);\n});\n";
843        assert_eq!(test_case_count(src), 3);
844    }
845
846    #[test]
847    fn test_case_count_counts_effect_vitest_members() {
848        let src = "it.effect('a', f);\nit.live('b', f);\nit.scoped('c', f);\nit.scopedLive('d', f);\nit.prop('e', arbs, f);\nit.effect.skip('f', f);\nit.effect.each([1])('g', f);\nit.effect.prop('h', arbs, f);\nit.layer(Live)('i', f);\nit.flakyTest(eff);\n";
849        assert_eq!(test_case_count(src), 8);
850    }
851
852    #[test]
853    fn test_case_count_needs_a_test_root_for_effect_vitest_members() {
854        let src = "foo.live('a', f);\ndescribe.scoped('b', f);\nlayer.effect('c', f);\n";
855        assert_eq!(test_case_count(src), 0);
856    }
857
858    #[test]
859    fn assertion_count_counts_expect_assert_and_should() {
860        let src = "expect(a).toBe(1);\nexpect.soft(b).toBe(2);\nassert.equal(c, 3);\nassert(d);\nx.should.equal(4);\nexpect.assertions(2);\n// expect(e)\n";
861        assert_eq!(assertion_count(src), 5);
862    }
863
864    #[test]
865    fn added_suppression_comments_are_hits() {
866        let base = "const a = 1;\n// eslint-disable-next-line no-console\nconsole.log(a);\n";
867        let head = "// @ts-ignore\nconst a = 1;\n// eslint-disable-next-line no-console\nconsole.log(a);\n/* istanbul ignore next */\nconst s = 'eslint-disable';\n";
868        let hits = added_suppression_hits(base, head);
869        let evidence: Vec<(u32, &str)> = hits
870            .iter()
871            .map(|hit| (hit.line, hit.evidence.as_str()))
872            .collect();
873        assert_eq!(evidence, vec![(1, "@ts-ignore"), (5, "istanbul ignore")]);
874    }
875
876    #[test]
877    fn added_threshold_override_comment_is_a_hit() {
878        let head = "// fallow-override-threshold-next-line maxCognitive=40 -- legacy
879export function f() {}
880";
881        let hits = added_suppression_hits("", head);
882        let evidence: Vec<(u32, &str)> = hits
883            .iter()
884            .map(|hit| (hit.line, hit.evidence.as_str()))
885            .collect();
886        assert_eq!(evidence, vec![(1, "fallow-override-threshold-next-line")]);
887    }
888
889    #[test]
890    fn fallow_ignore_that_names_only_diff_risk_rules_is_not_an_added_suppression() {
891        let head = "// fallow-ignore-next-line weakened-tests\nit.skip('a', f);\n// fallow-ignore-next-line unused-export\nexport const b = 1;\n// fallow-ignore-file\n";
892        let hits = added_suppression_hits("", head);
893        let lines: Vec<u32> = hits.iter().map(|hit| hit.line).collect();
894        assert_eq!(lines, vec![3, 5]);
895    }
896
897    #[test]
898    fn comment_markers_inside_string_literals_are_not_suppressions() {
899        let head = "out.push('/* eslint-disable */');\nout.push(\"// @ts-nocheck\");\nconst u = 'it\\'s'; // @ts-ignore\n<!-- eslint-disable -->\n";
900        let hits = added_suppression_hits("", head);
901        let evidence: Vec<(u32, &str)> = hits
902            .iter()
903            .map(|hit| (hit.line, hit.evidence.as_str()))
904            .collect();
905        assert_eq!(evidence, vec![(3, "@ts-ignore"), (4, "eslint-disable")]);
906    }
907
908    #[test]
909    fn multibyte_characters_before_a_comment_do_not_panic() {
910        let head = "const name = 'café'; // @ts-ignore\nconst ünï = 1;\n";
911        let hits = added_suppression_hits("", head);
912        assert_eq!(hits.len(), 1);
913        assert_eq!(hits[0].line, 1);
914    }
915
916    #[test]
917    fn quiet_logs_in_tests_are_not_hits() {
918        let head = "if (process.env.NODE_ENV !== 'test') {\n  console.error(message);\n}\nif (\n  status !== 'ok' &&\n  process.env.NODE_ENV !== 'test'\n) {\n  console.warn(\n    `not scheduled`,\n  );\n}\nif (process.env.NODE_ENV !== 'test') {\n  sendMetrics();\n}\n";
919        let lines: Vec<u32> = test_only_branch_hits("", head)
920            .iter()
921            .map(|hit| hit.line)
922            .collect();
923        assert_eq!(lines, vec![12]);
924    }
925
926    #[test]
927    fn test_env_file_selection_is_not_a_hit() {
928        let head = "config({ path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env' });\nconst key = process.env.NODE_ENV === 'test' ? 'test:' : '';\n";
929        let lines: Vec<u32> = test_only_branch_hits("", head)
930            .iter()
931            .map(|hit| hit.line)
932            .collect();
933        assert_eq!(lines, vec![2]);
934    }
935
936    #[test]
937    fn added_test_environment_branches_are_hits() {
938        let head = "if (process.env.NODE_ENV === 'test') return;\nif (process.env.NODE_ENV === 'production') x();\nconst w = process.env.JEST_WORKER_ID;\nif (process.env.VITEST) y();\n// process.env.VITEST\n";
939        let lines: Vec<u32> = test_only_branch_hits("", head)
940            .iter()
941            .map(|hit| hit.line)
942            .collect();
943        assert_eq!(lines, vec![1, 3, 4]);
944    }
945
946    #[test]
947    fn vitest_in_source_test_block_is_not_a_hit() {
948        let head = "export const add = (a, b) => a + b;\nif (import.meta.vitest) {\n  const { it, expect } = import.meta.vitest;\n  it('adds', () => expect(add(1, 2)).toBe(3));\n}\n";
949        assert!(test_only_branch_hits("", head).is_empty());
950    }
951
952    #[test]
953    fn test_environment_tokens_inside_strings_are_not_hits() {
954        let head = "return code.slice(a, b) === 'import.meta.vitest'\nconst m = `inside the \\`if (import.meta.vitest)\\` block`;\nconst s = \"process.env.VITEST\";\n";
955        assert!(test_only_branch_hits("", head).is_empty());
956    }
957
958    #[test]
959    fn lowered_min_threshold_and_raised_max_threshold_are_hits() {
960        let base = "thresholds: {\n  lines: 90,\n  branches: 80,\n},\nmaxCrap: 30,\n";
961        let head = "thresholds: {\n  lines: 70,\n  branches: 85,\n},\nmaxCrap: 45,\n";
962        let hits = weakened_threshold_hits(base, head);
963        let evidence: Vec<(u32, &str)> = hits
964            .iter()
965            .map(|hit| (hit.line, hit.evidence.as_str()))
966            .collect();
967        assert_eq!(
968            evidence,
969            vec![(2, "lines: 90 -> 70"), (5, "maxCrap: 30 -> 45")]
970        );
971    }
972
973    #[test]
974    fn json_thresholds_are_compared_by_key() {
975        let base = r#"{"jest": {"coverageThreshold": {"global": {"statements": 95}}}}"#;
976        let head = r#"{"jest": {"coverageThreshold": {"global": {"statements": 50}}}}"#;
977        let hits = weakened_threshold_hits(base, head);
978        assert_eq!(hits.len(), 1);
979        assert_eq!(hits[0].evidence, "statements: 95 -> 50");
980    }
981
982    #[test]
983    fn coverage_config_paths() {
984        assert!(is_coverage_config_path("vitest.config.ts"));
985        assert!(is_coverage_config_path("packages/a/jest.config.js"));
986        assert!(is_coverage_config_path("package.json"));
987        assert!(is_coverage_config_path(".nycrc.json"));
988        assert!(is_coverage_config_path(".fallowrc.json"));
989        assert!(!is_coverage_config_path("src/lines.ts"));
990    }
991}