fallow-api 3.45.0

Programmatic API contract types for fallow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! Line-level detectors over the base and head text of one changed file.
//!
//! The detectors are syntactic. They compare token counts and added lines,
//! and they do not parse the file. A line counts as added when its trimmed
//! text occurs more often in head than in base, so a moved line is not added.

use rustc_hash::{FxHashMap, FxHashSet};

/// One detector hit on a head line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LineHit {
    /// 1-based head line.
    pub line: u32,
    /// The token or value change that supports the hit.
    pub evidence: String,
}

/// Roots of a test-case call: `it(...)`, `test.skip(...)`.
const TEST_CASE_ROOTS: &[&str] = &["it", "test", "specify", "xit", "xtest", "fit"];
/// Roots of a suite call that can carry a skip or focus marker.
const SUITE_ROOTS: &[&str] = &["describe", "suite", "context"];
/// Roots that skip or focus by name alone.
const PREFIXED_ROOTS: &[&str] = &["xit", "xtest", "xdescribe", "fit", "fdescribe"];
/// Members that keep a call a test case (`it.each`, `test.concurrent`).
const TEST_CASE_MEMBERS: &[&str] = &[
    "skip",
    "only",
    "each",
    "todo",
    "concurrent",
    "sequential",
    "fails",
    "failing",
    "fixme",
    "skipIf",
    "runIf",
    // `@effect/vitest`: `it.effect`, `it.live`, `it.scoped`, `it.scopedLive`
    // and the property test `it.prop`. `it.layer` and `it.flakyTest` do not
    // register a test, so they stay out.
    "effect",
    "live",
    "scoped",
    "scopedLive",
    "prop",
];
/// Members of `expect` that are an assertion (`expect.soft(x)`).
const EXPECT_ASSERTION_MEMBERS: &[&str] = &["soft", "poll"];

/// Comment tokens that turn off a check. `fallow-ignore` has its own rule.
const SUPPRESSION_TOKENS: &[&str] = &[
    "eslint-disable",
    "oxlint-disable",
    "biome-ignore",
    "deno-lint-ignore",
    "@ts-ignore",
    "@ts-expect-error",
    "@ts-nocheck",
    "istanbul ignore",
    "c8 ignore",
    "v8 ignore",
];
pub(crate) const FALLOW_IGNORE_TOKEN: &str = "fallow-ignore";
/// Suppression tokens of the diff-risk rules. A `fallow-ignore` comment that
/// names only these is the suppression the findings ask for, so it is not an
/// added suppression itself.
const DIFF_RISK_TOKENS: &[&str] = &[
    "weakened-tests",
    "added-suppression",
    "test-only-branch",
    "diverged-clone-sibling",
    "added-dependency",
];

/// Threshold keys where a lower value is less strict.
const MIN_THRESHOLD_KEYS: &[&str] = &[
    "branches",
    "functions",
    "lines",
    "statements",
    "minScore",
    "min-score",
    "minCoverage",
    "min-coverage",
];
/// Threshold keys where a higher value is less strict.
const MAX_THRESHOLD_KEYS: &[&str] = &[
    "maxCrap",
    "max-crap",
    "maxCyclomatic",
    "max-cyclomatic",
    "maxCognitive",
    "max-cognitive",
];

/// Lines of `head` that do not occur in `base`, as `(1-based line, text)`.
///
/// Lines compare by trimmed text as a multiset. When head has more copies of
/// a line than base, the last copies count as added. Blank lines never count.
#[must_use]
pub fn added_lines<'a>(base: &str, head: &'a str) -> Vec<(u32, &'a str)> {
    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
    for line in base.lines() {
        *remaining.entry(line.trim()).or_default() += 1;
    }
    let mut head_counts: FxHashMap<&str, usize> = FxHashMap::default();
    for line in head.lines() {
        *head_counts.entry(line.trim()).or_default() += 1;
    }
    // The number of leading copies of each text that base already holds.
    let mut kept: FxHashMap<&str, usize> = head_counts
        .iter()
        .map(|(text, count)| {
            let in_base = remaining.get(text).copied().unwrap_or(0);
            (*text, (*count).min(in_base))
        })
        .collect();
    let mut added = Vec::new();
    for (index, line) in head.lines().enumerate() {
        let text = line.trim();
        if text.is_empty() {
            continue;
        }
        let keep = kept.entry(text).or_default();
        if *keep > 0 {
            *keep -= 1;
            continue;
        }
        added.push((line_number(index), line));
    }
    added
}

/// The identifier tokens in the code of `src`. Comments and the content of
/// string literals do not count, so a word in a test title or a comment is
/// not an identifier. A token that starts with a digit is a number.
#[must_use]
pub fn code_identifiers(src: &str) -> FxHashSet<String> {
    let mut found = FxHashSet::default();
    for line in src.lines() {
        let code = blank_string_literals(code_part(line));
        found.extend(
            code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
                .filter(|token| {
                    token
                        .bytes()
                        .next()
                        .is_some_and(|byte| !byte.is_ascii_digit())
                })
                .map(str::to_owned),
        );
    }
    found
}

/// Added lines of a test file that add a skip or focus marker.
///
/// A marker is the first skip or focus chain on a line, with the first string
/// literal of that line as its title. Markers compare as a multiset, not as
/// line text. So a base marker on a line that the change edits in another
/// place (a callback that becomes `async`, a new title, a reformat) is not
/// added. An added marker first matches a base marker with the same chain
/// and title, then a base marker with the same chain only. The chain-only
/// match covers a renamed test. It does not apply to a base marker whose
/// title is a plain test or suite call in the head: that skip moved to
/// another test, so the added marker skips a test that ran before.
#[must_use]
pub fn skip_only_hits(base: &str, head: &str) -> Vec<LineHit> {
    let mut pool: FxHashMap<SkipMarker<'_>, usize> = FxHashMap::default();
    for marker in base.lines().filter_map(skip_marker) {
        *pool.entry(marker).or_default() += 1;
    }
    let added = added_lines(base, head);
    let added_numbers: FxHashSet<u32> = added.iter().map(|(line, _)| *line).collect();
    // A head line that the change kept holds a base marker already.
    for (index, line) in head.lines().enumerate() {
        if added_numbers.contains(&line_number(index)) {
            continue;
        }
        if let Some(marker) = skip_marker(line) {
            take_marker(&mut pool, &marker);
        }
    }
    let mut candidates: Vec<(u32, SkipMarker<'_>)> = added
        .into_iter()
        .filter_map(|(line, text)| skip_marker(text).map(|marker| (line, marker)))
        .collect();
    candidates.retain(|(_, marker)| !take_marker(&mut pool, marker));
    let plain_titles: FxHashSet<&str> = head.lines().filter_map(plain_title).collect();
    pool.retain(|marker, _| {
        marker
            .title
            .is_none_or(|title| !plain_titles.contains(title))
    });
    candidates.retain(|(_, marker)| !take_chain(&mut pool, &marker.chain));
    candidates
        .into_iter()
        .map(|(line, marker)| LineHit {
            line,
            evidence: marker.chain,
        })
        .collect()
}

/// A skip or focus marker on one line: the chain text (`it.skip`) and the
/// first string literal of the line, when the line has one.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct SkipMarker<'a> {
    chain: String,
    title: Option<&'a str>,
}

fn skip_marker(line: &str) -> Option<SkipMarker<'_>> {
    let code = code_part(line);
    let chain = call_chains(code)
        .into_iter()
        .find(|chain| is_skip_or_focus(chain))?;
    Some(SkipMarker {
        chain: chain.join("."),
        title: first_string_literal(code),
    })
}

/// The title of a test or suite call without a skip or focus marker.
fn plain_title(line: &str) -> Option<&str> {
    if skip_marker(line).is_some() {
        return None;
    }
    let code = code_part(line);
    call_chains(code).into_iter().find(|chain| {
        chain
            .first()
            .is_some_and(|root| TEST_CASE_ROOTS.contains(root) || SUITE_ROOTS.contains(root))
    })?;
    first_string_literal(code)
}

/// Removes one copy of `marker` from `pool`. Returns whether a copy was there.
fn take_marker<'a>(pool: &mut FxHashMap<SkipMarker<'a>, usize>, marker: &SkipMarker<'a>) -> bool {
    match pool.get_mut(marker) {
        Some(count) if *count > 0 => {
            *count -= 1;
            true
        }
        _ => false,
    }
}

/// Removes one copy of any marker with `chain` from `pool`. Returns whether a
/// copy was there. The lowest title goes first, so the result is stable.
fn take_chain(pool: &mut FxHashMap<SkipMarker<'_>, usize>, chain: &str) -> bool {
    let key = pool
        .iter()
        .filter(|(marker, count)| marker.chain == chain && **count > 0)
        .map(|(marker, _)| marker.clone())
        .min_by(|a, b| a.title.cmp(&b.title));
    key.is_some_and(|key| take_marker(pool, &key))
}

/// The content of the first single-line string literal in `code`.
fn first_string_literal(code: &str) -> Option<&str> {
    let (start, quote) = code
        .char_indices()
        .find(|(_, c)| matches!(c, '\'' | '"' | '`'))?;
    let body = start + quote.len_utf8();
    let mut escaped = false;
    for (offset, c) in code[body..].char_indices() {
        if c == quote && !escaped {
            return Some(&code[body..body + offset]);
        }
        escaped = !escaped && c == '\\';
    }
    None
}

/// The number of test-case calls in a test file, comments excluded.
#[must_use]
pub fn test_case_count(src: &str) -> usize {
    src.lines()
        .flat_map(|line| call_chains(code_part(line)))
        .filter(|chain| is_test_case(chain))
        .count()
}

/// The number of assertion calls (`expect(`, `assert`, `should`) in a test
/// file, comments excluded.
#[must_use]
pub fn assertion_count(src: &str) -> usize {
    src.lines()
        .map(|line| {
            let code = code_part(line);
            let chains = call_chains(code)
                .into_iter()
                .filter(|chain| is_assertion(chain))
                .count();
            chains + member_should_count(code)
        })
        .sum()
}

/// The code lines that the change removed from a file, as `(assertion lines,
/// code lines)`. Comment and blank lines do not count.
#[must_use]
pub fn removed_assertion_lines(base: &str, head: &str) -> (usize, usize) {
    added_lines(head, base)
        .into_iter()
        .filter(|(_, line)| !code_part(line).trim().is_empty())
        .fold((0, 0), |(asserts, code), (_, line)| {
            (asserts + usize::from(assertion_count(line) > 0), code + 1)
        })
}

/// Added comment lines that add a suppression.
#[must_use]
pub fn added_suppression_hits(base: &str, head: &str) -> Vec<LineHit> {
    added_lines(base, head)
        .into_iter()
        .filter_map(|(line, text)| {
            let comment = comment_part(text)?;
            suppression_token(comment).map(|token| LineHit {
                line,
                evidence: token.to_owned(),
            })
        })
        .collect()
}

/// Added lines of a non-test source file that branch on the test
/// environment.
#[must_use]
pub fn test_only_branch_hits(base: &str, head: &str) -> Vec<LineHit> {
    let head_lines: Vec<&str> = head.lines().collect();
    added_lines(base, head)
        .into_iter()
        .filter_map(|(line, text)| {
            let code = code_part(text);
            let token = test_environment_token(code)?;
            if picks_env_file(code) || only_quiets_logs(&head_lines, line) {
                return None;
            }
            Some(LineHit {
                line,
                evidence: token.to_owned(),
            })
        })
        .collect()
}

/// Whether a test-environment check picks an env file, such as
/// `config({ path: NODE_ENV === 'test' ? '.env.test' : '.env' })`. That is
/// configuration, not a code path.
fn picks_env_file(code: &str) -> bool {
    ["'.env", "\".env", "`.env"]
        .iter()
        .any(|literal| code.contains(literal))
}

/// The most lines that [`only_quiets_logs`] reads after a check.
const MAX_GUARDED_LINES: usize = 12;

/// Whether a negated test check (`!== 'test'`) guards only `console` calls.
/// Then the tests only stay quiet, and production takes the same code path.
fn only_quiets_logs(lines: &[&str], line: u32) -> bool {
    let index = usize::try_from(line).unwrap_or(0).saturating_sub(1);
    let Some(check) = lines.get(index) else {
        return false;
    };
    let check = blank_string_literals(code_part(check));
    if !check.contains("!=") {
        return false;
    }
    if check.contains("console.") {
        return true;
    }
    let mut body = lines
        .iter()
        .skip(index + 1)
        .take(MAX_GUARDED_LINES)
        .map(|line| code_part(line).trim())
        .filter(|code| !code.is_empty() && !matches!(*code, "{" | ") {" | ")"));
    if !body
        .next()
        .is_some_and(|first| first.starts_with("console."))
    {
        return false;
    }
    // The rest of the block holds only more `console` calls or the
    // arguments of one: quoted text, closing parentheses or commas.
    for code in body {
        if code.starts_with('}') {
            return true;
        }
        let continues = code.starts_with("console.")
            || code.starts_with(['\'', '"', '`', ')', ','])
            || code.ends_with(',');
        if !continues {
            return false;
        }
    }
    false
}

/// Threshold values in a coverage or quality config that the change made
/// less strict. Occurrences of one key pair up in file order.
#[must_use]
pub fn weakened_threshold_hits(base: &str, head: &str) -> Vec<LineHit> {
    let mut hits = Vec::new();
    for (keys, lower_is_weaker) in [(MIN_THRESHOLD_KEYS, true), (MAX_THRESHOLD_KEYS, false)] {
        for key in keys {
            let base_values = numeric_values_for_key(base, key);
            let head_values = numeric_values_for_key(head, key);
            for ((base_value, _), (head_value, head_line)) in
                base_values.iter().zip(head_values.iter())
            {
                let weaker = if lower_is_weaker {
                    head_value < base_value
                } else {
                    head_value > base_value
                };
                if weaker {
                    hits.push(LineHit {
                        line: *head_line,
                        evidence: format!("{key}: {base_value} -> {head_value}"),
                    });
                }
            }
        }
    }
    hits.sort_by_key(|hit| hit.line);
    hits
}

/// Whether `rel_path` names a test-runner, coverage or Fallow config file.
#[must_use]
pub fn is_coverage_config_path(rel_path: &str) -> bool {
    let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
    if rel_path.contains("node_modules/") {
        return false;
    }
    const EXACT: &[&str] = &[
        "package.json",
        ".nycrc",
        ".nycrc.json",
        ".nycrc.yml",
        ".nycrc.yaml",
        ".c8rc",
        ".c8rc.json",
        ".fallowrc.json",
        ".fallowrc.jsonc",
        "fallow.toml",
        ".fallow.toml",
    ];
    const PREFIXES: &[&str] = &[
        "vitest.config.",
        "vitest.workspace.",
        "vite.config.",
        "jest.config.",
        "karma.conf.",
        "playwright.config.",
    ];
    EXACT.contains(&name) || PREFIXES.iter().any(|prefix| name.starts_with(prefix))
}

fn line_number(index: usize) -> u32 {
    u32::try_from(index + 1).unwrap_or(u32::MAX)
}

/// The code of a line before any comment. A line that starts inside a
/// comment has no code.
fn code_part(line: &str) -> &str {
    let trimmed = line.trim_start();
    if trimmed.starts_with("//")
        || trimmed.starts_with("/*")
        || trimmed.starts_with('*')
        || trimmed.starts_with("<!--")
    {
        return "";
    }
    match comment_start(line) {
        Some(start) => &line[..start],
        None => line,
    }
}

/// The comment of a line, from its first comment marker.
fn comment_part(line: &str) -> Option<&str> {
    let trimmed = line.trim_start();
    if trimmed.starts_with('*') || trimmed.starts_with('#') {
        return Some(trimmed);
    }
    comment_start(line).map(|start| &line[start..])
}

/// The byte offset of the first `//`, `/*` or `<!--` marker. A `//` right
/// after `:` is a URL scheme, not a comment. A `//` or `/*` inside a
/// single-line string literal is text, not a comment. The `<!--` search reads
/// the raw line, because an apostrophe in markup text is not a quote.
fn comment_start(line: &str) -> Option<usize> {
    let code = blank_string_literals(line);
    let bytes = code.as_bytes();
    let mut index = 0;
    let mut script = None;
    while index + 1 < bytes.len() {
        let pair = (bytes[index], bytes[index + 1]);
        let is_line_comment = pair == (b'/', b'/') && (index == 0 || bytes[index - 1] != b':');
        if is_line_comment || pair == (b'/', b'*') {
            script = Some(index);
            break;
        }
        index += 1;
    }
    let markup = line.find("<!--");
    match (script, markup) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    }
}

const fn is_ident_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}

/// Every member chain in `code` that is called: `it.skip(` gives
/// `["it", "skip"]`. A chain that follows a `.` is a member of another
/// expression, so it is not a chain root.
fn call_chains(code: &str) -> Vec<Vec<&str>> {
    let bytes = code.as_bytes();
    let mut chains = Vec::new();
    let mut index = 0;
    while index < bytes.len() {
        let starts_ident = is_ident_byte(bytes[index])
            && !bytes[index].is_ascii_digit()
            && (index == 0 || (!is_ident_byte(bytes[index - 1]) && bytes[index - 1] != b'.'));
        if !starts_ident {
            index += 1;
            continue;
        }
        let mut chain = Vec::new();
        let mut cursor = index;
        loop {
            let start = cursor;
            while cursor < bytes.len() && is_ident_byte(bytes[cursor]) {
                cursor += 1;
            }
            chain.push(&code[start..cursor]);
            if cursor + 1 < bytes.len() && bytes[cursor] == b'.' && is_ident_byte(bytes[cursor + 1])
            {
                cursor += 1;
                continue;
            }
            break;
        }
        let next = code[cursor..].trim_start().bytes().next();
        if matches!(next, Some(b'(' | b'`')) {
            chains.push(chain);
        }
        index = cursor.max(index + 1);
    }
    chains
}

fn is_skip_or_focus(chain: &[&str]) -> bool {
    let Some(root) = chain.first() else {
        return false;
    };
    if PREFIXED_ROOTS.contains(root) {
        return true;
    }
    (TEST_CASE_ROOTS.contains(root) || SUITE_ROOTS.contains(root))
        && chain[1..]
            .iter()
            .any(|member| matches!(*member, "skip" | "only"))
}

fn is_test_case(chain: &[&str]) -> bool {
    chain
        .first()
        .is_some_and(|root| TEST_CASE_ROOTS.contains(root))
        && chain[1..]
            .iter()
            .all(|member| TEST_CASE_MEMBERS.contains(member))
}

fn is_assertion(chain: &[&str]) -> bool {
    match chain {
        ["expect"] | ["should" | "assert", ..] => true,
        ["expect", member] => EXPECT_ASSERTION_MEMBERS.contains(member),
        _ => false,
    }
}

/// `x.should.equal(1)` style assertions: `.should` followed by `.` or `(`.
fn member_should_count(code: &str) -> usize {
    code.match_indices(".should")
        .filter(|(start, token)| {
            let after = code.as_bytes().get(start + token.len()).copied();
            matches!(after, Some(b'.' | b'('))
        })
        .count()
}

/// The first suppression token in a comment, or `None`. A `fallow-ignore`
/// marker that names only diff-risk rules is not a suppression here.
fn suppression_token(comment: &str) -> Option<&'static str> {
    let generic = SUPPRESSION_TOKENS
        .iter()
        .filter_map(|token| comment.find(token).map(|at| (at, *token)))
        .min_by_key(|(at, _)| *at);
    let fallow = comment
        .find(FALLOW_IGNORE_TOKEN)
        .filter(|at| !names_only_diff_risk_rules(&comment[*at..]))
        .map(|at| (at, FALLOW_IGNORE_TOKEN));
    [generic, fallow]
        .into_iter()
        .flatten()
        .min_by_key(|(at, _)| *at)
        .map(|(_, token)| token)
}

/// Whether a `fallow-ignore-*` directive lists only diff-risk tokens. A
/// directive without tokens suppresses every rule, so it does not qualify.
fn names_only_diff_risk_rules(directive: &str) -> bool {
    let body = directive
        .split_once("--")
        .map_or(directive, |(tokens, _reason)| tokens);
    let body = body
        .trim_end()
        .trim_end_matches("*/")
        .trim_end_matches("-->");
    let mut words = body.split_whitespace();
    // The first word is the directive itself (`fallow-ignore-next-line`).
    words.next();
    let tokens: Vec<&str> = words
        .flat_map(|word| word.split(','))
        .filter(|token| !token.is_empty())
        .collect();
    !tokens.is_empty() && tokens.iter().all(|token| DIFF_RISK_TOKENS.contains(token))
}

/// The test-environment token in a line of code, or `None`.
fn test_environment_token(code: &str) -> Option<&'static str> {
    // The tokens count only outside string literals: a parser that compares
    // source text with `'process.env.VITEST'` is not a test-only branch.
    // `import.meta.vitest` is not a token: Vitest uses it to mark an in-source
    // test block, which is test code and not a production branch.
    let outside = blank_string_literals(code);
    for token in ["process.env.VITEST", "process.env.JEST_WORKER_ID"] {
        if outside.contains(token) {
            return Some(token);
        }
    }
    let compares_test = ["'test'", "\"test\"", "`test`"]
        .iter()
        .any(|literal| code.contains(literal))
        && (outside.contains("==") || outside.contains("!="));
    (outside.contains("process.env.NODE_ENV") && compares_test).then_some("process.env.NODE_ENV")
}

/// `code` with the content of each string literal on the line replaced by
/// spaces. The quotes stay. A backslash escapes the next character. Each
/// character becomes as many spaces as it has bytes, so byte offsets in the
/// result are byte offsets in `code`.
fn blank_string_literals(code: &str) -> String {
    let mut out = String::with_capacity(code.len());
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for c in code.chars() {
        let Some(open) = quote else {
            if matches!(c, '\'' | '"' | '`') {
                quote = Some(c);
            }
            out.push(c);
            continue;
        };
        if c == open && !escaped {
            quote = None;
            out.push(c);
            continue;
        }
        escaped = !escaped && c == '\\';
        out.extend(std::iter::repeat_n(' ', c.len_utf8()));
    }
    out
}

/// Every numeric value that follows `key` as an object key, with its 1-based
/// line. The key must stand alone: `lines` does not match `maxLines`.
fn numeric_values_for_key(src: &str, key: &str) -> Vec<(f64, u32)> {
    let mut values = Vec::new();
    let mut line = 1u32;
    let mut scanned = 0;
    let mut search_from = 0;
    while let Some(relative) = src[search_from..].find(key) {
        let start = search_from + relative;
        let end = start + key.len();
        search_from = end;
        let before = src[..start].bytes().next_back();
        let after = src.as_bytes().get(end).copied();
        let stands_alone = !before.is_some_and(|byte| is_ident_byte(byte) || byte == b'-')
            && !after.is_some_and(|byte| is_ident_byte(byte) || byte == b'-');
        if !stands_alone {
            continue;
        }
        let rest = src[end..]
            .trim_start_matches(['"', '\''])
            .trim_start_matches([' ', '\t']);
        let Some(rest) = rest.strip_prefix([':', '=']) else {
            continue;
        };
        let rest = rest.trim_start_matches([' ', '\t', '"', '\'']);
        let number: String = rest
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
            .collect();
        let Ok(value) = number.parse::<f64>() else {
            continue;
        };
        line += u32::try_from(src[scanned..start].matches('\n').count()).unwrap_or(0);
        scanned = start;
        values.push((value, line));
    }
    values
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn explain_text_names_every_detected_suppression_token() {
        let full = crate::explain::AUDIT_RULES
            .iter()
            .find(|rule| rule.id == "fallow/added-suppression")
            .map(|rule| rule.full)
            .unwrap_or_default();
        for token in SUPPRESSION_TOKENS.iter().chain([&FALLOW_IGNORE_TOKEN]) {
            assert!(
                full.contains(&format!("`{token}`")),
                "the added-suppression explain text must name `{token}`"
            );
        }
    }

    #[test]
    fn added_lines_ignore_moved_lines() {
        let base = "a\nb\nc\n";
        let head = "c\na\nb\nd\n";
        assert_eq!(added_lines(base, head), vec![(4, "d")]);
    }

    #[test]
    fn added_skip_and_only_markers_are_hits_at_their_line() {
        let base = "it('a', () => {});\ntest('b', () => {});\n";
        let head = "it.skip('a', () => {});\ntest.only('b', () => {});\nxit('c', f);\n";
        let hits = skip_only_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(1, "it.skip"), (2, "test.only"), (3, "xit")]);
    }

    #[test]
    fn existing_or_commented_skip_markers_are_not_hits() {
        let base = "it.skip('a', () => {});\n";
        let head = "// it.only('x')\nit.skip('a', () => {});\nconst profit = fit2(1);\n";
        assert!(skip_only_hits(base, head).is_empty());
    }

    #[test]
    fn existing_skip_on_a_changed_line_is_not_a_hit() {
        let base = "it.skip('pending', () => {\n  expect(1).toBe(1);\n});\n";
        let head = "it.skip('pending', async () => {\n  expect(1).toBe(1);\n});\n";
        assert!(skip_only_hits(base, head).is_empty());
    }

    #[test]
    fn existing_skip_with_a_new_title_is_not_a_hit() {
        let base = "it('a', f);\ntest.only('old title', () => {});\n";
        let head = "it('a', f);\ntest.only('new title', () => {});\n";
        assert!(skip_only_hits(base, head).is_empty());
    }

    #[test]
    fn moved_and_changed_skip_is_not_a_hit() {
        let base = "it.skip('a', () => {});\nit('b', f);\n";
        let head = "it('b', f);\nit.skip('a', async () => {});\n";
        assert!(skip_only_hits(base, head).is_empty());
    }

    #[test]
    fn new_skip_next_to_a_changed_existing_skip_is_one_hit() {
        let base = "it.skip('a', () => {});\nit('b', () => {});\n";
        let head = "it.skip('a', async () => {});\nit.skip('b', () => {});\n";
        let hits = skip_only_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(2, "it.skip")]);
    }

    #[test]
    fn skip_that_moves_to_another_test_is_a_hit() {
        // The base skips 'doubles'. The head runs 'doubles' again and skips
        // 'keeps zero'. So 'keeps zero' no longer runs.
        let base = "it.skip('doubles', () => {});\nit('keeps zero', () => {});\n";
        let head = "it('doubles', () => {});\nit.skip('keeps zero', () => {});\n";
        let hits = skip_only_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(2, "it.skip")]);
    }

    #[test]
    fn suite_skip_that_moves_to_another_suite_is_a_hit() {
        let base = "describe.skip('a', () => {});\ndescribe('b', () => {});\n";
        let head = "describe('a', () => {});\ndescribe.skip('b', () => {});\n";
        let hits = skip_only_hits(base, head);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].line, 2);
    }

    #[test]
    fn exact_title_match_wins_over_a_chain_match() {
        // Base has one `it.skip('a')`. Head changes that line and adds a new
        // `it.skip('c')` before it. The finding must go to the new title.
        let base = "it.skip('a', () => {});\n";
        let head = "it.skip('c', () => {});\nit.skip('a', async () => {});\n";
        let hits = skip_only_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(1, "it.skip")]);
    }

    #[test]
    fn test_case_count_counts_cases_with_modifiers_only() {
        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";
        assert_eq!(test_case_count(src), 3);
    }

    #[test]
    fn test_case_count_counts_effect_vitest_members() {
        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";
        assert_eq!(test_case_count(src), 8);
    }

    #[test]
    fn test_case_count_needs_a_test_root_for_effect_vitest_members() {
        let src = "foo.live('a', f);\ndescribe.scoped('b', f);\nlayer.effect('c', f);\n";
        assert_eq!(test_case_count(src), 0);
    }

    #[test]
    fn assertion_count_counts_expect_assert_and_should() {
        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";
        assert_eq!(assertion_count(src), 5);
    }

    #[test]
    fn added_suppression_comments_are_hits() {
        let base = "const a = 1;\n// eslint-disable-next-line no-console\nconsole.log(a);\n";
        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";
        let hits = added_suppression_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(1, "@ts-ignore"), (5, "istanbul ignore")]);
    }

    #[test]
    fn fallow_ignore_that_names_only_diff_risk_rules_is_not_an_added_suppression() {
        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";
        let hits = added_suppression_hits("", head);
        let lines: Vec<u32> = hits.iter().map(|hit| hit.line).collect();
        assert_eq!(lines, vec![3, 5]);
    }

    #[test]
    fn comment_markers_inside_string_literals_are_not_suppressions() {
        let head = "out.push('/* eslint-disable */');\nout.push(\"// @ts-nocheck\");\nconst u = 'it\\'s'; // @ts-ignore\n<!-- eslint-disable -->\n";
        let hits = added_suppression_hits("", head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(evidence, vec![(3, "@ts-ignore"), (4, "eslint-disable")]);
    }

    #[test]
    fn multibyte_characters_before_a_comment_do_not_panic() {
        let head = "const name = 'café'; // @ts-ignore\nconst ünï = 1;\n";
        let hits = added_suppression_hits("", head);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].line, 1);
    }

    #[test]
    fn quiet_logs_in_tests_are_not_hits() {
        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";
        let lines: Vec<u32> = test_only_branch_hits("", head)
            .iter()
            .map(|hit| hit.line)
            .collect();
        assert_eq!(lines, vec![12]);
    }

    #[test]
    fn test_env_file_selection_is_not_a_hit() {
        let head = "config({ path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env' });\nconst key = process.env.NODE_ENV === 'test' ? 'test:' : '';\n";
        let lines: Vec<u32> = test_only_branch_hits("", head)
            .iter()
            .map(|hit| hit.line)
            .collect();
        assert_eq!(lines, vec![2]);
    }

    #[test]
    fn added_test_environment_branches_are_hits() {
        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";
        let lines: Vec<u32> = test_only_branch_hits("", head)
            .iter()
            .map(|hit| hit.line)
            .collect();
        assert_eq!(lines, vec![1, 3, 4]);
    }

    #[test]
    fn vitest_in_source_test_block_is_not_a_hit() {
        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";
        assert!(test_only_branch_hits("", head).is_empty());
    }

    #[test]
    fn test_environment_tokens_inside_strings_are_not_hits() {
        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";
        assert!(test_only_branch_hits("", head).is_empty());
    }

    #[test]
    fn lowered_min_threshold_and_raised_max_threshold_are_hits() {
        let base = "thresholds: {\n  lines: 90,\n  branches: 80,\n},\nmaxCrap: 30,\n";
        let head = "thresholds: {\n  lines: 70,\n  branches: 85,\n},\nmaxCrap: 45,\n";
        let hits = weakened_threshold_hits(base, head);
        let evidence: Vec<(u32, &str)> = hits
            .iter()
            .map(|hit| (hit.line, hit.evidence.as_str()))
            .collect();
        assert_eq!(
            evidence,
            vec![(2, "lines: 90 -> 70"), (5, "maxCrap: 30 -> 45")]
        );
    }

    #[test]
    fn json_thresholds_are_compared_by_key() {
        let base = r#"{"jest": {"coverageThreshold": {"global": {"statements": 95}}}}"#;
        let head = r#"{"jest": {"coverageThreshold": {"global": {"statements": 50}}}}"#;
        let hits = weakened_threshold_hits(base, head);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].evidence, "statements: 95 -> 50");
    }

    #[test]
    fn coverage_config_paths() {
        assert!(is_coverage_config_path("vitest.config.ts"));
        assert!(is_coverage_config_path("packages/a/jest.config.js"));
        assert!(is_coverage_config_path("package.json"));
        assert!(is_coverage_config_path(".nycrc.json"));
        assert!(is_coverage_config_path(".fallowrc.json"));
        assert!(!is_coverage_config_path("src/lines.ts"));
    }
}