slopguard-core 0.1.36

Core analysis engine for slopguard
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
use std::collections::HashSet;
use std::fs::{create_dir, read_dir, write};
use std::path::{Path, PathBuf};

use tempfile::tempdir;

use super::test_support::*;
use super::*;
use crate::cache::{CacheEntry, CacheKey};
use crate::config::Config;
use crate::finding::{Finding, ScanResult};
use crate::rule::{load_builtin_rules, Rule, RuleId};

fn test_cache_key() -> CacheKey {
    CacheKey::from_bytes([7; 32])
}

// Shadow the public entry points so the tests sign with a fixed key instead of
// creating one in the user's cache directory.
fn scan_cached(
    paths: &[PathBuf],
    rules: &[Rule],
    config: &Config,
    cache_dir: &Path,
) -> Result<ScanResult, ScanError> {
    scan_cached_with_key(paths, rules, config, cache_dir, test_cache_key())
}

fn scan_files_cached(
    files: &[PathBuf],
    rules: &[Rule],
    config: &Config,
    cache_dir: &Path,
) -> Result<ScanResult, ScanError> {
    scan_files_cached_with_key(files, rules, config, cache_dir, test_cache_key())
}

#[test]
fn scan_cache_ignores_forged_empty_entry() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    write(
        src_dir.path().join("main.rs"),
        "fn main() {\n    foo().unwrap();\n}\n",
    )
    .unwrap();
    let rules = [unwrap_rule()];
    let config = Config::default();
    let paths = [src_dir.path().to_path_buf()];

    let first = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    assert_eq!(first.findings.len(), 1);

    // Replace every entry with an unsigned one claiming the file is clean, as a
    // repository shipping its own cache could.
    let forged = rmp_serde::to_vec_named(&CacheEntry::default()).unwrap();
    let mut replaced = 0;
    for entry in read_dir(&cache_path).unwrap() {
        let path = entry.unwrap().path();
        if path.extension().is_some_and(|ext| ext == "bin") {
            write(&path, &forged).unwrap();
            replaced += 1;
        }
    }
    assert_eq!(replaced, 1);

    let second = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    assert_eq!(second.findings.len(), 1, "the forged entry must be ignored");
    let stats = second.cache_stats.as_ref().unwrap();
    assert_eq!(stats.cached, 0);
    assert_eq!(stats.changed, 1);
}

#[test]
fn scan_files_cached_keeps_other_entries() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    let a = src_dir.path().join("a.rs");
    let b = src_dir.path().join("b.rs");
    write(&a, "fn a() {\n    foo().unwrap();\n}\n").unwrap();
    write(&b, "fn b() {\n    bar().unwrap();\n}\n").unwrap();

    let rules = [unwrap_rule()];
    let config = Config::default();
    let paths = [src_dir.path().to_path_buf()];

    scan_cached(&paths, &rules, &config, &cache_path).unwrap();

    // A partial scan must not evict the entry of the file it skipped.
    scan_files_cached(&[a], &rules, &config, &cache_path).unwrap();

    let result = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    let stats = result.cache_stats.as_ref().unwrap();
    assert_eq!(stats.cached, 2, "a partial scan must not prune");
    assert_eq!(stats.changed, 0);
}

#[test]
fn file_target_walk_keeps_other_entries() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    let a = src_dir.path().join("a.rs");
    write(&a, "fn a() {\n    foo().unwrap();\n}\n").unwrap();
    write(
        src_dir.path().join("b.rs"),
        "fn b() {\n    bar().unwrap();\n}\n",
    )
    .unwrap();

    let rules = [unwrap_rule()];
    let config = Config::default();
    let paths = [src_dir.path().to_path_buf()];

    scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    // The pre-commit hook passes files as scan paths, not through `--diff`.
    scan_cached(&[a], &rules, &config, &cache_path).unwrap();

    let result = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    let stats = result.cache_stats.as_ref().unwrap();
    assert_eq!(stats.cached, 2, "a file target must not prune");
    assert_eq!(stats.changed, 0);
}

#[test]
fn scan_finds_file_lines_violation() {
    let dir = tempdir().unwrap();
    write(dir.path().join("big.rs"), rust_lines(12)).unwrap();
    let result = scan_dir(dir.path(), &[file_lines_rule()]);
    assert_eq!(result.findings.len(), 1);
    let f = &result.findings[0];
    assert_eq!(f.rule_id, RuleId::from("test-file-lines"));
    assert_eq!(f.line, 1);
    assert_eq!(f.column, 1);
    assert_eq!(f.end_line, 1);
    assert_eq!(f.end_column, 1);
    assert_eq!(f.matched_text, "12 lines");
}

#[test]
fn metric_message_interpolates_value() {
    let dir = tempdir().unwrap();
    write(dir.path().join("big.rs"), rust_lines(12)).unwrap();
    let rule = metric_rule(
        r#"
id: test-interpolate
language: rust
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "File exceeds 10 lines ($value lines)"
"#,
    );
    let result = scan_dir(dir.path(), &[rule]);
    assert_eq!(result.findings.len(), 1);
    let message = &result.findings[0].message;
    assert!(message.contains("(12 lines)"), "got: {message}");
    assert!(!message.contains("$value"), "got: {message}");
}

#[test]
fn metric_rule_below_threshold_no_finding() {
    let dir = tempdir().unwrap();
    write(dir.path().join("exact.rs"), rust_lines(10)).unwrap();
    let result = scan_dir(dir.path(), &[file_lines_rule()]);
    assert_eq!(
        result.findings.len(),
        0,
        "a file of exactly the threshold length must not fire"
    );
}

#[test]
fn metric_comment_ratio_finding() {
    let dir = tempdir().unwrap();
    write(
        dir.path().join("commented.rs"),
        "// a\n// b\n// c\n// d\nfn f() {}\nfn g() {}\nfn h() {}\n",
    )
    .unwrap();
    let rule = metric_rule(
        r#"
id: test-comment-ratio
language: rust
severity: warning
category: slop
metric: comment_ratio
threshold: 0.4
message: "Too many comments ($value)"
"#,
    );
    let result = scan_dir(dir.path(), &[rule]);
    assert_eq!(result.findings.len(), 1);
    assert!(
        result.findings[0].matched_text.ends_with("comment ratio"),
        "got: {}",
        result.findings[0].matched_text
    );
}

#[test]
fn metric_rule_respects_ignores_glob() {
    let dir = tempdir().unwrap();
    let gen = dir.path().join("generated");
    create_dir(&gen).unwrap();
    write(gen.join("out.rs"), rust_lines(12)).unwrap();
    write(dir.path().join("main.rs"), rust_lines(12)).unwrap();
    let rule = metric_rule(
        r#"
id: test-metric-ignores
language: rust
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "too long"
ignores:
  - "**/generated/**"
"#,
    );
    let result = scan_dir(dir.path(), &[rule]);
    assert_eq!(result.findings.len(), 1);
    assert!(result.findings[0]
        .file
        .to_string_lossy()
        .contains("main.rs"));
}

#[test]
fn metric_rule_respects_files_glob() {
    let dir = tempdir().unwrap();
    let src = dir.path().join("src");
    create_dir(&src).unwrap();
    write(src.join("lib.rs"), rust_lines(12)).unwrap();
    write(dir.path().join("build.rs"), rust_lines(12)).unwrap();
    let rule = metric_rule(
        r#"
id: test-metric-files
language: rust
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "too long"
files:
  - "**/src/**/*.rs"
"#,
    );
    let result = scan_dir(dir.path(), &[rule]);
    assert_eq!(result.findings.len(), 1);
    assert!(result.findings[0].file.to_string_lossy().contains("lib.rs"));
}

#[test]
fn metric_rule_skip_test_code_skips_test_files() {
    let dir = tempdir().unwrap();
    let tests_dir = dir.path().join("tests");
    create_dir(&tests_dir).unwrap();
    write(tests_dir.join("it.rs"), rust_lines(12)).unwrap();

    let skipping = metric_rule(
        r#"
id: test-metric-skip
language: rust
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "too long"
skip_test_code: true
"#,
    );
    let skipped = scan_dir(dir.path(), &[skipping]);
    assert_eq!(skipped.findings.len(), 0);
    let reported = scan_dir(dir.path(), &[file_lines_rule()]);
    assert_eq!(reported.findings.len(), 1);
}

#[test]
fn metric_only_ruleset_still_scans() {
    let dir = tempdir().unwrap();
    write(dir.path().join("big.rs"), rust_lines(12)).unwrap();
    let result = scan_dir(dir.path(), &[file_lines_rule()]);
    assert_eq!(
        result.findings.len(),
        1,
        "a rule set with only metric rules must still scan files"
    );
}

#[test]
fn metric_and_ast_rules_together() {
    let dir = tempdir().unwrap();
    let mut source = String::from("fn main() {\n    foo().unwrap();\n}\n");
    source.push_str(&rust_lines(12));
    write(dir.path().join("main.rs"), source).unwrap();

    let result = scan_dir(dir.path(), &[unwrap_rule(), file_lines_rule()]);
    assert_eq!(result.findings.len(), 2);
    let first = &result.findings[0];
    assert_eq!(first.rule_id, RuleId::from("test-file-lines"));
    assert_eq!(first.line, 1);
    let second = &result.findings[1];
    assert_eq!(second.rule_id, RuleId::from("test-unwrap"));
}

#[test]
fn metric_rule_wrong_language_not_applied() {
    let dir = tempdir().unwrap();
    write(dir.path().join("big.rs"), rust_lines(12)).unwrap();
    let rule = metric_rule(
        r#"
id: test-metric-ts
language: typescript
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "too long"
"#,
    );
    let result = scan_dir(dir.path(), &[rule]);
    assert_eq!(result.findings.len(), 0);
}

#[test]
fn metric_findings_are_cached() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    write(src_dir.path().join("big.rs"), rust_lines(12)).unwrap();

    let rules = [file_lines_rule()];
    let config = Config::default();
    let paths = [src_dir.path().to_path_buf()];

    let first = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    assert_eq!(first.findings.len(), 1);
    assert_eq!(first.cache_stats.as_ref().unwrap().changed, 1);

    let second = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    assert_eq!(second.cache_stats.as_ref().unwrap().cached, 1);
    assert_eq!(second.findings.len(), 1);
    assert_eq!(second.findings[0].matched_text, "12 lines");
}

#[test]
fn scan_with_cache() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    write(
        src_dir.path().join("main.rs"),
        "fn main() {\n    foo().unwrap();\n}\n",
    )
    .unwrap();

    let rules = [unwrap_rule()];
    let config = Config::default();

    let result1 = scan_cached(
        &[src_dir.path().to_path_buf()],
        &rules,
        &config,
        &cache_path,
    )
    .unwrap();

    assert_eq!(result1.findings.len(), 1);
    let cache_stats1 = result1.cache_stats.as_ref().unwrap();
    assert_eq!(cache_stats1.cached, 0, "first scan: nothing cached");
    assert_eq!(cache_stats1.changed, 1, "first scan: one file scanned");

    let result2 = scan_cached(
        &[src_dir.path().to_path_buf()],
        &rules,
        &config,
        &cache_path,
    )
    .unwrap();

    assert_eq!(result2.findings.len(), 1);
    let cache_stats2 = result2.cache_stats.as_ref().unwrap();
    assert_eq!(cache_stats2.cached, 1, "second scan: one file from cache");
    assert_eq!(cache_stats2.changed, 0, "second scan: nothing changed");
}

#[test]
fn cross_file_single_impl_trait_reported() {
    let dir = tempdir().unwrap();
    write(
        dir.path().join("repo.rs"),
        "pub trait Repository {\n    fn get(&self);\n}\n",
    )
    .unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\n\nimpl Repository for Pg {\n    fn get(&self) {}\n}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 1);
    let f = &result.findings[0];
    assert_eq!(f.rule_id, RuleId::from("no-single-impl-trait"));
    assert!(f.file.to_string_lossy().ends_with("repo.rs"));
    assert_eq!(f.line, 1);
    assert_eq!(f.matched_text, "pub trait Repository");
}

#[test]
fn cross_file_two_impls_not_reported() {
    let dir = tempdir().unwrap();
    write(dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();
    write(
        dir.path().join("mem.rs"),
        "pub struct Mem;\nimpl Repository for Mem {}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 0);
}

#[test]
fn cross_file_no_impl_not_reported() {
    let dir = tempdir().unwrap();
    write(dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 0);
}

#[test]
fn cross_file_blanket_impl_not_reported() {
    let dir = tempdir().unwrap();
    write(dir.path().join("desc.rs"), "pub trait Describe {}\n").unwrap();
    write(dir.path().join("all.rs"), "impl<T> Describe for T {}\n").unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 0);
}

#[test]
fn cross_file_duplicate_trait_name_not_reported() {
    let dir = tempdir().unwrap();
    write(dir.path().join("a.rs"), "pub trait Repository {}\n").unwrap();
    write(dir.path().join("b.rs"), "pub trait Repository {}\n").unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 0);
}

#[test]
fn cross_file_disable_comment_on_declaration() {
    let dir = tempdir().unwrap();
    write(
        dir.path().join("repo.rs"),
        "// slopguard-disable-next-line no-single-impl-trait\npub trait Repository {}\n",
    )
    .unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(
        result.findings.len(),
        0,
        "a disable comment above the declaration must suppress the finding"
    );
}

#[test]
fn cross_file_cfg_test_mock_counts_as_second_impl() {
    let dir = tempdir().unwrap();
    write(dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();
    write(
        dir.path().join("mock.rs"),
        "#[cfg(test)]\nmod tests {\n    struct MockRepo;\n    impl Repository for MockRepo {}\n}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(
        result.findings.len(),
        0,
        "a test mock counts as a second implementation"
    );
}

#[test]
fn cross_file_declaration_in_test_path_not_reported() {
    let dir = tempdir().unwrap();
    let tests_dir = dir.path().join("tests");
    create_dir(&tests_dir).unwrap();
    write(tests_dir.join("support.rs"), "pub trait Repository {}\n").unwrap();
    write(
        tests_dir.join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(result.findings.len(), 0);
}

/// A project (marked by `slopguard.toml`) whose trait has one impl per file in
/// `impls`.
fn repository_project(impls: &[&str]) -> tempfile::TempDir {
    let dir = tempdir().unwrap();
    write(dir.path().join("slopguard.toml"), "").unwrap();
    write(dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();
    for name in impls {
        write(
            dir.path().join(format!("{}.rs", name.to_lowercase())),
            format!("pub struct {name};\nimpl Repository for {name} {{}}\n"),
        )
        .unwrap();
    }
    dir
}

#[test]
fn scan_files_indexes_the_whole_project() {
    // The second impl lives in a file outside the scanned list: a partial
    // index would see one impl and report the trait.
    let dir = repository_project(&["Pg", "Mem"]);
    let rules = [single_impl_trait_rule()];
    let partial = scan_files(&[dir.path().join("repo.rs")], &rules, &Config::default()).unwrap();
    assert!(partial.findings.is_empty(), "got: {:?}", partial.findings);
}

#[test]
fn scan_files_reports_only_findings_in_the_given_files() {
    let dir = repository_project(&["Pg"]);
    let rules = [single_impl_trait_rule()];
    let config = Config::default();

    let on_decl = scan_files(&[dir.path().join("repo.rs")], &rules, &config).unwrap();
    assert_eq!(on_decl.findings.len(), 1);
    assert!(on_decl.findings[0].file.ends_with("repo.rs"));

    let on_impl = scan_files(&[dir.path().join("pg.rs")], &rules, &config).unwrap();
    assert!(
        on_impl.findings.is_empty(),
        "the finding sits in repo.rs, which was not scanned: {:?}",
        on_impl.findings
    );
}

#[test]
fn file_target_of_a_walk_indexes_the_whole_project() {
    // The pre-commit hook passes files as scan paths, not through `--diff`.
    let dir = repository_project(&["Pg", "Mem"]);
    let rules = [single_impl_trait_rule()];
    let result = scan(&[dir.path().join("repo.rs")], &rules, &Config::default()).unwrap();
    assert!(result.findings.is_empty(), "got: {:?}", result.findings);
    assert_eq!(result.stats.files_scanned, 1);
}

#[test]
fn cached_partial_scan_keeps_the_project_cache() {
    let dir = repository_project(&["Pg", "Mem"]);
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    let rules = [single_impl_trait_rule()];
    let config = Config::default();
    let file_target = [dir.path().join("repo.rs")];

    let first = scan_cached(&file_target, &rules, &config, &cache_path).unwrap();
    assert!(first.findings.is_empty(), "got: {:?}", first.findings);
    let second = scan_cached(&file_target, &rules, &config, &cache_path).unwrap();
    assert!(second.findings.is_empty(), "got: {:?}", second.findings);
    assert_eq!(
        second.cache_stats.map(|s| (s.cached, s.changed)),
        Some((1, 0))
    );

    // The index-only files were scanned and stored by the partial runs, so a
    // full scan finds every entry already cached.
    let full = scan_cached(&[dir.path().to_path_buf()], &rules, &config, &cache_path).unwrap();
    assert_eq!(
        full.cache_stats.map(|s| (s.cached, s.changed)),
        Some((3, 0))
    );
}

#[test]
fn cross_file_survives_cache_round_trip() {
    let src_dir = tempdir().unwrap();
    let cache_dir = tempdir().unwrap();
    let cache_path = cache_dir.path().join("cache");
    write(src_dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();
    write(
        src_dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();

    let rules = [single_impl_trait_rule()];
    let config = Config::default();
    let paths = [src_dir.path().to_path_buf()];

    let first = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    assert_eq!(first.findings.len(), 1);
    assert_eq!(first.cache_stats.as_ref().unwrap().changed, 2);

    let second = scan_cached(&paths, &rules, &config, &cache_path).unwrap();
    let stats = second.cache_stats.as_ref().unwrap();
    assert_eq!(stats.cached, 2, "both files should come from the cache");
    assert_eq!(stats.changed, 0);
    assert_eq!(
        second.findings.len(),
        1,
        "symbols must survive the cache round trip"
    );
}

#[test]
fn cross_file_rule_with_no_ast_rules_still_parses_files() {
    let dir = tempdir().unwrap();
    write(dir.path().join("repo.rs"), "pub trait Repository {}\n").unwrap();
    write(
        dir.path().join("pg.rs"),
        "pub struct Pg;\nimpl Repository for Pg {}\n",
    )
    .unwrap();

    let result = scan_dir(dir.path(), &[single_impl_trait_rule()]);
    assert_eq!(
        result.findings.len(),
        1,
        "a cross-file-only ruleset must still parse every file"
    );
}

#[test]
fn all_engine_kinds_run_and_aggregate() {
    // One scan with an AST rule (per-file), a metric rule (per-file) and a
    // cross-file rule (project-level) must return the union of their findings:
    // the orchestrator iterates every registered engine across both scopes.
    let dir = tempdir().unwrap();
    let mut service = String::from(
        "fn main() {\n    foo().unwrap();\n}\npub trait Repo {\n    fn get(&self);\n}\n",
    );
    // Push the file past the file_lines threshold of 10.
    service.push_str(&rust_lines(10));
    write(dir.path().join("service.rs"), service).unwrap();
    write(
        dir.path().join("postgres.rs"),
        "struct Pg;\nimpl Repo for Pg {\n    fn get(&self) {}\n}\n",
    )
    .unwrap();

    let result = scan_dir(
        dir.path(),
        &[unwrap_rule(), file_lines_rule(), single_impl_trait_rule()],
    );

    let ids: HashSet<RuleId> = result.findings.iter().map(|f| f.rule_id.clone()).collect();
    assert!(
        ids.contains(&RuleId::from("test-unwrap")),
        "AST engine finding missing: {ids:?}"
    );
    assert!(
        ids.contains(&RuleId::from("test-file-lines")),
        "metric engine finding missing: {ids:?}"
    );
    assert!(
        ids.contains(&RuleId::from("no-single-impl-trait")),
        "cross-file engine finding missing: {ids:?}"
    );
}

/// Findings of the builtin rule `rule_id` on `source`, written as `lib.rs`.
fn builtin_findings(rule_id: &str, source: &str) -> Vec<Finding> {
    // A rule id may exist once per language (`no-trivial-function` has a
    // TypeScript twin), so keep every variant and let the scan pick by file.
    let rules: Vec<Rule> = load_builtin_rules()
        .unwrap()
        .into_iter()
        .filter(|r| r.id.as_str() == rule_id)
        .collect();
    assert!(!rules.is_empty(), "builtin rule '{rule_id}' should exist");
    let dir = tempdir().unwrap();
    write(dir.path().join("lib.rs"), source).unwrap();
    scan_dir(dir.path(), &rules)
        .findings
        .into_iter()
        .filter(|f| f.rule_id.as_str() == rule_id)
        .collect()
}

#[test]
fn expect_inside_enclosing_call_reported_once() {
    let found = builtin_findings(
        "no-expect-in-prod",
        "fn f(h: &mut H, v: Option<u8>) { headers.insert(h, v.expect(\"set\")); }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
    assert!(
        found[0].matched_text.starts_with("v.expect("),
        "got: {}",
        found[0].matched_text
    );
}

#[test]
fn expect_inside_lazy_lock_closure_reported_once() {
    let found = builtin_findings(
        "no-expect-in-prod",
        "static X: LazyLock<u8> = LazyLock::new(|| x.expect(\"boom\"));\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
}

#[test]
fn expect_in_format_macro_reported_once() {
    let found = builtin_findings(
        "no-expect-in-prod",
        "fn f() { let s = format!(\"{}\", name.as_deref().expect(\"set\")); }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
}

#[test]
fn lock_expect_not_reported() {
    let found = builtin_findings(
        "no-expect-in-prod",
        "fn f() { let g = map.lock().expect(\"poisoned\"); }\n",
    );
    assert!(found.is_empty(), "got: {found:?}");
}

#[test]
fn swallowed_map_err_with_try_in_some_not_reported() {
    let found = builtin_findings(
        "no-swallowed-error",
        "fn f() { let v = Some(x.parse().map_err(|_| Error::Bad)?); }\n",
    );
    assert!(found.is_empty(), "got: {found:?}");
}

#[test]
fn swallowed_map_err_inside_call_reported_once() {
    let found = builtin_findings(
        "no-swallowed-error",
        "fn f() { foo(x.parse().map_err(|_| Error::Bad)); }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
    assert!(
        found[0].matched_text.starts_with("x.parse().map_err("),
        "got: {}",
        found[0].matched_text
    );
}

#[test]
fn getter_named_like_field_not_reported() {
    let found = builtin_findings(
        "no-trivial-function",
        "impl A { fn name(&self) -> String { self.name } }\n",
    );
    assert!(found.is_empty(), "got: {found:?}");
}

#[test]
fn call_adding_constant_argument_not_reported() {
    let found = builtin_findings(
        "no-trivial-function",
        "fn from_fn(f: F) -> L { from_fn_with_state((), f) }\n",
    );
    assert!(found.is_empty(), "got: {found:?}");
}

#[test]
fn pure_forward_still_reported() {
    let found = builtin_findings(
        "no-trivial-function",
        "fn run(mut x: i32, y: &str) -> i32 { compute(x, &y) }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
}

#[test]
fn field_read_under_other_name_still_reported() {
    let found = builtin_findings(
        "no-trivial-function",
        "impl A { fn label(&self) -> String { self.name } }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
}

#[test]
fn self_pass_through_still_reported() {
    let found = builtin_findings(
        "no-trivial-function",
        "impl A { fn describe(&self) -> String { render(self) } }\n",
    );
    assert_eq!(found.len(), 1, "got: {found:?}");
}