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