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