slopguard-core 0.1.15

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
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
use std::collections::HashMap;
use std::fs::{self, read_to_string};
use std::path::{Path, PathBuf};

use ast_grep_config::{
    CombinedScan, GlobalRules, RuleCollection, RuleConfig, RuleConfigError, SerializableRuleConfig,
};
use ast_grep_core::tree_sitter::LanguageExt;
use ast_grep_core::Language as AstLanguage;
use ast_grep_core::{AstGrep, Doc};
use ast_grep_language::SupportLang;
use globset::{Error as GlobError, Glob, GlobSet, GlobSetBuilder};
use ignore::WalkBuilder;
use rayon::prelude::*;
use serde::Serialize;
use serde_yaml::with::singleton_map_recursive;
use serde_yaml::{to_value, Value};
use strum::IntoEnumIterator;
use thiserror::Error;

use crate::cache::{file_content_hash, rules_hash, CacheStore};
use crate::config::Config;
use crate::disable::filter_disabled;
use crate::finding::{CacheStats, Finding, ScanResult, ScanStats};
use crate::metric::{self, Metric};
use crate::rule::{Language, Rule, RuleId, Severity};
use crate::test_filter::CfgTestRanges;

#[derive(Debug, Error)]
pub enum ScanError {
    #[error("failed to compile rule '{id}': {source}")]
    RuleCompile {
        id: RuleId,
        #[source]
        source: RuleConfigError,
    },

    #[error("invalid glob pattern: {0}")]
    Glob(#[from] GlobError),

    #[error("rule '{id}': metric rule is missing a threshold")]
    InvalidMetricRule { id: RuleId },
}

/// The subset of a slopguard rule that ast-grep understands. slopguard-only
/// fields (`category`, `fix` as free text, `tests`) are deliberately left out.
#[derive(Serialize)]
pub struct AstGrepRule<'a> {
    pub id: &'a str,
    pub language: SupportLang,
    pub severity: &'a Severity,
    pub message: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<&'a str>,
    pub rule: &'a Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<&'a [String]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignores: Option<&'a [String]>,
}

/// Rules compiled for scanning, plus a way back to the slopguard rule that
/// produced each ast-grep config.
struct CompiledRules<'a> {
    collection: RuleCollection<SupportLang>,
    by_id: HashMap<(&'a str, Language), &'a Rule>,
    metrics: Vec<MetricRule<'a>>,
}

/// A metric rule prepared for scanning: threshold resolved and `files` /
/// `ignores` globs compiled once. ast-grep applies those globs for AST rules;
/// metric rules are evaluated outside ast-grep so they apply them here.
struct MetricRule<'a> {
    rule: &'a Rule,
    metric: Metric,
    threshold: f64,
    files: Option<GlobSet>,
    ignores: Option<GlobSet>,
}

impl MetricRule<'_> {
    fn applies_to(&self, path: &Path, lang: &Language) -> bool {
        self.rule.language == *lang
            && self.files.as_ref().is_none_or(|g| g.is_match(path))
            && !self.ignores.as_ref().is_some_and(|g| g.is_match(path))
    }
}

fn extension_to_lang(path: &Path) -> Option<SupportLang> {
    SupportLang::from_path(path)
        .filter(|lang| Language::iter().any(|l| l.ast_grep_langs().contains(lang)))
}

fn support_lang_to_language(lang: SupportLang) -> Language {
    match lang {
        SupportLang::Rust => Language::Rust,
        _ => Language::TypeScript,
    }
}

pub(crate) fn compile_ast_grep_rule(
    rule: &AstGrepRule,
) -> Result<RuleConfig<SupportLang>, RuleConfigError> {
    let inner: SerializableRuleConfig<SupportLang> = to_value(rule)
        .and_then(singleton_map_recursive::deserialize)
        .map_err(RuleConfigError::from)?;
    RuleConfig::try_from(inner, &GlobalRules::default())
}

fn compile_rule(rule: &Rule, lang: SupportLang) -> Result<RuleConfig<SupportLang>, ScanError> {
    let ast_grep_rule = AstGrepRule {
        id: rule.id.as_str(),
        language: lang,
        severity: &rule.severity,
        message: &rule.message,
        note: rule.note.as_deref(),
        rule: &rule.rule,
        files: rule.files.as_deref(),
        ignores: rule.ignores.as_deref(),
    };
    compile_ast_grep_rule(&ast_grep_rule).map_err(|source| ScanError::RuleCompile {
        id: rule.id.clone(),
        source,
    })
}

/// Resolve a metric rule's threshold and compile its path globs.
fn build_metric_rule(rule: &Rule) -> Result<MetricRule<'_>, ScanError> {
    let Some((metric, threshold)) = rule.metric_spec() else {
        return Err(ScanError::InvalidMetricRule {
            id: rule.id.clone(),
        });
    };
    Ok(MetricRule {
        rule,
        metric,
        threshold,
        files: rule.files.as_deref().map(build_glob_set).transpose()?,
        ignores: rule.ignores.as_deref().map(build_glob_set).transpose()?,
    })
}

fn compile_rules(rules: &[Rule]) -> Result<CompiledRules<'_>, ScanError> {
    // Metric rules must never reach ast-grep: their `rule` field is null and
    // would fail to compile.
    let (metric_rules, ast_rules): (Vec<&Rule>, Vec<&Rule>) =
        rules.iter().partition(|r| r.is_metric());

    let configs = ast_rules
        .iter()
        .copied()
        .flat_map(|rule| {
            rule.language
                .ast_grep_langs()
                .iter()
                .map(move |lang| compile_rule(rule, *lang))
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(CompiledRules {
        collection: RuleCollection::try_new(configs)?,
        by_id: ast_rules
            .iter()
            .copied()
            .map(|rule| ((rule.id.as_str(), rule.language.clone()), rule))
            .collect::<HashMap<_, _>>(),
        metrics: metric_rules
            .into_iter()
            .map(build_metric_rule)
            .collect::<Result<Vec<_>, _>>()?,
    })
}

fn build_glob_set(patterns: &[String]) -> Result<GlobSet, GlobError> {
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        builder.add(Glob::new(pattern)?);
    }
    builder.build()
}

/// Whether `path` lives in a conventional test, bench, or example tree.
///
/// Rust integration tests, benchmarks, and examples are not `#[cfg(test)]`
/// modules, so `CfgTestRanges` cannot see them. Rules with `skip_test_code`
/// should treat these whole files as test code.
///
/// Matches exact directory names (`tests`, `benches`, `examples`) and also
/// crate-level test directories whose name ends with `_test` or `_tests`
/// (e.g. `integrations_tests`, `e2e_tests`).
fn is_test_path(path: &Path) -> bool {
    let in_test_dir = path.components().any(|c| {
        let Some(name) = c.as_os_str().to_str() else {
            return false;
        };
        matches!(name, "tests" | "benches" | "examples")
            || name.ends_with("_tests")
            || name.ends_with("_test")
            || name.starts_with("test_")
    });
    let test_file_name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .is_some_and(|s| s.ends_with("_test") || s.ends_with("_tests"));
    in_test_dir || test_file_name
}

/// One finding per metric rule whose measured value exceeds its threshold.
///
/// File-level findings have no source position, so they are anchored at 1:1.
/// `skip_test_code` drops the whole file: a line-1 finding can never be inside
/// a `#[cfg(test)]` block.
fn metric_findings<D: Doc>(
    metrics: &[&MetricRule],
    path: &Path,
    root: &AstGrep<D>,
    source: &str,
    lang: &Language,
) -> Vec<Finding> {
    metrics
        .iter()
        .filter(|m| !(m.rule.skip_test_code && is_test_path(path)))
        .filter_map(|m| {
            let value = metric::compute(m.metric, lang, root, source);
            if !metric::exceeds(value, m.threshold) {
                return None;
            }
            let rendered = m.metric.format_value(value);
            Some(Finding {
                rule_id: m.rule.id.clone(),
                severity: m.rule.severity.clone(),
                category: m.rule.category.clone().unwrap_or_default(),
                message: m.rule.message.replace("$value", &rendered),
                note: m.rule.note.clone(),
                fix: m.rule.fix.clone(),
                file: path.to_path_buf(),
                line: 1,
                column: 1,
                end_line: 1,
                end_column: 1,
                matched_text: m.metric.describe(value),
                confidence: None,
                escalated: false,
            })
        })
        .collect()
}

fn scan_file(path: &Path, lang: SupportLang, rules: &CompiledRules) -> Vec<Finding> {
    let rule_lang = support_lang_to_language(lang);
    let applicable = rules.collection.get_rule_from_lang(path, lang);
    let metrics: Vec<&MetricRule> = rules
        .metrics
        .iter()
        .filter(|m| m.applies_to(path, &rule_lang))
        .collect();
    if applicable.is_empty() && metrics.is_empty() {
        return Vec::new();
    }
    let Ok(source) = read_to_string(path) else {
        return Vec::new();
    };

    let root = lang.ast_grep(&source);

    let mut findings: Vec<Finding> = if applicable.is_empty() {
        Vec::new()
    } else {
        let combined = CombinedScan::new(applicable);
        let result = combined.scan(&root, false);

        let cfg_test = (lang == SupportLang::Rust && !result.matches.is_empty())
            .then(|| CfgTestRanges::from_root(&root));
        let cfg_test = cfg_test.as_ref();
        let is_test_file = is_test_path(path);

        result
            .matches
            .into_iter()
            .filter_map(|(config, matches)| {
                let rule = rules.by_id.get(&(config.id.as_str(), rule_lang.clone()))?;
                Some((*rule, matches))
            })
            .flat_map(|(rule, matches)| {
                let skip_test_code = rule.skip_test_code;
                matches
                    .into_iter()
                    .map(move |node_match| {
                        let start = node_match.start_pos();
                        let end = node_match.end_pos();
                        Finding {
                            rule_id: rule.id.clone(),
                            severity: rule.severity.clone(),
                            category: rule.category.clone().unwrap_or_default(),
                            message: rule.message.clone(),
                            note: rule.note.clone(),
                            fix: rule.fix.clone(),
                            file: path.to_path_buf(),
                            line: start.line() + 1,
                            column: start.byte_point().1 + 1,
                            end_line: end.line() + 1,
                            end_column: end.byte_point().1 + 1,
                            matched_text: node_match.text().to_string(),
                            confidence: None,
                            escalated: false,
                        }
                    })
                    .filter(move |f| {
                        if !skip_test_code {
                            return true;
                        }
                        let in_test_code =
                            is_test_file || cfg_test.is_some_and(|r| r.contains_line(f.line));
                        !in_test_code
                    })
            })
            .collect()
    };

    findings.extend(metric_findings(&metrics, path, &root, &source, &rule_lang));
    filter_disabled(findings, &source)
}

/// Walk `paths` (gitignore-aware) and keep the source files slopguard can parse.
fn walk_files(paths: &[PathBuf], ignores: &GlobSet) -> Vec<(PathBuf, SupportLang)> {
    paths
        .iter()
        .flat_map(|path| WalkBuilder::new(path).build().flatten())
        .filter(|entry| entry.file_type().is_some_and(|t| t.is_file()))
        .map(|entry| entry.into_path())
        .filter(|path| !ignores.is_match(path))
        .filter_map(|path| extension_to_lang(&path).map(|lang| (path, lang)))
        .collect()
}

/// Keep the given files as-is (no directory walk), dropping the ones that are
/// ignored by config or written in an unsupported language.
///
/// Deliberately not gitignore-aware: a file git reports as changed must be
/// scanned even when it lives under a hidden or ignored directory.
fn explicit_files(files: &[PathBuf], ignores: &GlobSet) -> Vec<(PathBuf, SupportLang)> {
    files
        .iter()
        .filter(|path| path.is_file())
        .filter(|path| !ignores.is_match(path))
        .filter_map(|path| extension_to_lang(path).map(|lang| (path.clone(), lang)))
        .collect()
}

/// Count errors and warnings in one pass.
pub fn count_severities(findings: &[Finding]) -> (usize, usize) {
    let mut errors = 0;
    let mut warnings = 0;
    for finding in findings {
        match finding.severity {
            Severity::Error => errors += 1,
            Severity::Warning => warnings += 1,
        }
    }
    (errors, warnings)
}

/// Sort findings by location and drop duplicates from overlapping rules.
fn normalize_findings(findings: &mut Vec<Finding>) {
    findings.sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
    findings.dedup_by(|a, b| {
        a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
    });
}

/// Scan an already-collected file list without touching the cache.
fn scan_collected(files: Vec<(PathBuf, SupportLang)>, compiled: &CompiledRules) -> ScanResult {
    let mut findings: Vec<Finding> = files
        .par_iter()
        .flat_map_iter(|(path, lang)| scan_file(path, *lang, compiled))
        .collect();
    normalize_findings(&mut findings);

    let (errors, warnings) = count_severities(&findings);

    ScanResult {
        findings,
        stats: ScanStats {
            errors,
            warnings,
            total: errors + warnings,
            files_scanned: files.len(),
            baseline_filtered: 0,
            diff_base: None,
            files_changed: None,
        },
        cache_stats: None,
    }
}

/// Scan an already-collected file list, reusing cached findings for files
/// whose content hash is unchanged.
///
/// `prune` drops cache entries that no longer correspond to a scanned file. A
/// partial scan must pass `false`: it never saw the other files, so their
/// entries are still valid.
fn scan_collected_cached(
    files: Vec<(PathBuf, SupportLang)>,
    compiled: &CompiledRules,
    rules: &[Rule],
    cache_dir: &Path,
    prune: bool,
) -> ScanResult {
    let current_rules_hash = rules_hash(rules);
    let store = CacheStore::with_dir(cache_dir.to_path_buf()).scoped_to_rules(&current_rules_hash);
    let rules_changed = store
        .check_rules_changed(&current_rules_hash)
        .unwrap_or(true);

    let file_contents: Vec<(PathBuf, SupportLang, Vec<u8>, String)> = files
        .into_iter()
        .filter_map(|(path, lang)| {
            let content = fs::read(&path).ok()?;
            let hash = file_content_hash(&content);
            Some((path, lang, content, hash))
        })
        .collect();

    let mut cached_count = 0usize;
    let mut changed_count = 0usize;
    let mut all_findings: Vec<Finding> = Vec::new();

    struct FileWork {
        path: PathBuf,
        lang: SupportLang,
        hash: String,
    }

    let mut to_scan: Vec<FileWork> = Vec::new();

    for (path, lang, _content, hash) in file_contents.iter() {
        if !rules_changed {
            if let Some(cached_findings) = store.get(hash) {
                cached_count += 1;
                all_findings.extend(cached_findings);
                continue;
            }
        }
        changed_count += 1;
        to_scan.push(FileWork {
            path: path.clone(),
            lang: *lang,
            hash: hash.clone(),
        });
    }

    let scanned_findings: Vec<(String, Vec<Finding>)> = to_scan
        .par_iter()
        .map(|work| {
            let findings = scan_file(&work.path, work.lang, compiled);
            (work.hash.clone(), findings)
        })
        .collect();

    for (hash, findings) in scanned_findings {
        store.put(&hash, &findings).ok();
        all_findings.extend(findings);
    }

    if prune {
        let current_hashes: Vec<String> =
            file_contents.iter().map(|(_, _, _, h)| h.clone()).collect();
        store.cleanup(&current_hashes).ok();
    }

    normalize_findings(&mut all_findings);

    let (errors, warnings) = count_severities(&all_findings);

    let files_scanned = cached_count + changed_count;

    ScanResult {
        findings: all_findings,
        stats: ScanStats {
            errors,
            warnings,
            total: errors + warnings,
            files_scanned,
            baseline_filtered: 0,
            diff_base: None,
            files_changed: None,
        },
        cache_stats: Some(CacheStats {
            cached: cached_count,
            changed: changed_count,
        }),
    }
}

/// Scan the given paths for rule violations.
pub fn scan(paths: &[PathBuf], rules: &[Rule], config: &Config) -> Result<ScanResult, ScanError> {
    let compiled = compile_rules(rules)?;
    let ignores = build_glob_set(&config.scan.ignores)?;
    Ok(scan_collected(walk_files(paths, &ignores), &compiled))
}

/// Scan with file-level caching. Files whose content hash matches a cached
/// entry (and whose rules have not changed) return cached findings without
/// reparsing.
///
/// `cache_dir` is the directory where cache files are stored. When a custom
/// cache directory is specified (via `--cache-dir`, `SLOPGUARD_CACHE_DIR`,
/// or `scan.cache_dir` in config), pass it directly. Otherwise pass the
/// project root and use `CacheStore::new` which appends `.slopguard-cache`.
pub fn scan_cached(
    paths: &[PathBuf],
    rules: &[Rule],
    config: &Config,
    cache_dir: &Path,
) -> Result<ScanResult, ScanError> {
    let compiled = compile_rules(rules)?;
    let ignores = build_glob_set(&config.scan.ignores)?;
    Ok(scan_collected_cached(
        walk_files(paths, &ignores),
        &compiled,
        rules,
        cache_dir,
        true,
    ))
}

/// Scan an explicit list of files instead of walking directories.
///
/// Used by `--diff`, where git already produced the exact file set. Paths that
/// no longer exist or that slopguard cannot parse are silently skipped.
pub fn scan_files(
    files: &[PathBuf],
    rules: &[Rule],
    config: &Config,
) -> Result<ScanResult, ScanError> {
    let compiled = compile_rules(rules)?;
    let ignores = build_glob_set(&config.scan.ignores)?;
    Ok(scan_collected(explicit_files(files, &ignores), &compiled))
}

/// Cached variant of [`scan_files`]. Cache pruning is skipped: a partial scan
/// must not evict the entries of files it did not look at.
pub fn scan_files_cached(
    files: &[PathBuf],
    rules: &[Rule],
    config: &Config,
    cache_dir: &Path,
) -> Result<ScanResult, ScanError> {
    let compiled = compile_rules(rules)?;
    let ignores = build_glob_set(&config.scan.ignores)?;
    Ok(scan_collected_cached(
        explicit_files(files, &ignores),
        &compiled,
        rules,
        cache_dir,
        false,
    ))
}

#[cfg(test)]
mod tests {
    use std::fs::{create_dir, write};

    use tempfile::tempdir;

    use super::*;
    use crate::rule::{load_builtin_rules, parse_rule, RuleId};

    fn unwrap_rule() -> Rule {
        parse_rule(
            r#"
id: test-unwrap
language: rust
severity: error
category: correctness
message: ".unwrap() forbidden"
rule:
  kind: call_expression
  regex: '\.unwrap\(\)\s*$'
"#,
        )
        .unwrap()
    }

    fn scan_dir(dir: &Path, rules: &[Rule]) -> ScanResult {
        scan(&[dir.to_path_buf()], rules, &Config::default()).unwrap()
    }

    #[test]
    fn scan_finds_unwrap_violation() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("main.rs"),
            "fn main() {\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.findings.len(), 1);
        let f = &result.findings[0];
        assert_eq!(f.rule_id, RuleId::from("test-unwrap"));
        assert_eq!(f.severity, Severity::Error);
        assert_eq!(f.line, 2);
        assert!(f.matched_text.contains("unwrap()"));
    }

    #[test]
    fn scan_clean_file_no_findings() {
        let dir = tempdir().unwrap();
        write(dir.path().join("main.rs"), "fn main() { let x = foo(); }\n").unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 1);
    }

    #[test]
    fn scan_unsupported_language_ignored() {
        let dir = tempdir().unwrap();
        write(dir.path().join("script.py"), "x.unwrap()\n").unwrap();
        write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 1);
    }

    #[test]
    fn scan_explicit_file_path() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("main.rs");
        write(&file, "fn main() { foo().unwrap(); }\n").unwrap();
        let result = scan(&[file], &[unwrap_rule()], &Config::default()).unwrap();
        assert_eq!(result.findings.len(), 1);
        assert_eq!(result.stats.files_scanned, 1);
    }

    #[test]
    fn rule_ignores_glob_respected() {
        let dir = tempdir().unwrap();
        let tests_dir = dir.path().join("tests");
        create_dir(&tests_dir).unwrap();
        write(
            tests_dir.join("test_main.rs"),
            "fn t() { foo().unwrap(); }\n",
        )
        .unwrap();
        write(
            dir.path().join("main.rs"),
            "fn main() { foo().unwrap(); }\n",
        )
        .unwrap();
        let rule = parse_rule(
            r#"
id: ign
language: rust
severity: error
category: correctness
message: x
rule:
  kind: call_expression
  regex: '\.unwrap\(\)\s*$'
ignores:
  - "**/tests/**"
"#,
        )
        .unwrap();
        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 config_ignores_respected() {
        let dir = tempdir().unwrap();
        let gen = dir.path().join("generated");
        create_dir(&gen).unwrap();
        write(gen.join("out.rs"), "fn g() { foo().unwrap(); }\n").unwrap();
        write(
            dir.path().join("main.rs"),
            "fn main() { foo().unwrap(); }\n",
        )
        .unwrap();
        let mut cfg = Config::default();
        cfg.scan.ignores = vec!["**/generated/**".to_string()];
        let result = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap();
        assert_eq!(result.stats.files_scanned, 1);
        assert_eq!(result.findings.len(), 1);
    }

    #[test]
    fn config_invalid_glob_is_an_error() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::default();
        cfg.scan.ignores = vec!["[".to_string()];
        let err = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap_err();
        assert!(matches!(err, ScanError::Glob(_)), "{err:?}");
    }

    #[test]
    fn rule_without_kind_fails_to_compile() {
        let dir = tempdir().unwrap();
        let rule = parse_rule(
            r#"
id: no-kind
language: rust
severity: error
category: correctness
message: x
rule:
  regex: 'unwrap'
"#,
        )
        .unwrap();
        let err = scan(&[dir.path().to_path_buf()], &[rule], &Config::default()).unwrap_err();
        assert!(
            matches!(&err, ScanError::RuleCompile { id, .. } if *id == RuleId::from("no-kind")),
            "{err:?}"
        );
    }

    #[test]
    fn stats_counting_accurate() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("a.rs"),
            "fn f() { foo().unwrap(); bar().unwrap(); }\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.stats.errors, 2);
        assert_eq!(result.stats.warnings, 0);
        assert_eq!(result.stats.total, 2);
        assert_eq!(result.stats.files_scanned, 1);
    }

    #[test]
    fn scan_empty_file() {
        let dir = tempdir().unwrap();
        write(dir.path().join("empty.rs"), "").unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 1);
    }

    #[test]
    fn scan_complex_rule() {
        let rule = parse_rule(
            r#"
id: dbg
language: rust
severity: error
category: security
message: debug on secret
rule:
  kind: attribute_item
  all:
    - regex: 'derive\([^)]*Debug'
    - precedes:
        kind: struct_item
        has:
          kind: field_identifier
          regex: '^(api_key|password|secret)$'
          stopBy: end
"#,
        )
        .unwrap();
        let dir = tempdir().unwrap();
        write(
            dir.path().join("t.rs"),
            "#[derive(Debug)]\nstruct Config {\n    api_key: String,\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[rule]);
        assert_eq!(result.findings.len(), 1);
        assert_eq!(result.findings[0].rule_id, RuleId::from("dbg"));
    }

    #[test]
    fn typescript_rule_applies_to_tsx_files() {
        let rule = parse_rule(
            r#"
id: ts-any
language: typescript
severity: warning
category: slop
message: no any
rule:
  kind: predefined_type
  regex: '^any$'
"#,
        )
        .unwrap();
        let dir = tempdir().unwrap();
        write(dir.path().join("a.ts"), "let x: any = 1;\n").unwrap();
        write(dir.path().join("b.tsx"), "let y: any = 2;\n").unwrap();
        let result = scan_dir(dir.path(), &[rule]);
        assert_eq!(result.stats.files_scanned, 2);
        assert_eq!(result.stats.warnings, 2);
    }

    #[test]
    fn scan_with_disable_comment_filters_findings() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("main.rs"),
            "fn main() {\n    // slopguard-disable-next-line\n    foo().unwrap();\n    bar().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(
            result.findings.len(),
            1,
            "only the non-disabled unwrap should remain"
        );
        assert_eq!(result.findings[0].line, 4);
    }

    #[test]
    fn scan_with_disable_rule_id_filters_only_that_rule() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("main.rs"),
            "fn main() {\n    // slopguard-disable-next-line test-unwrap\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(result.findings.len(), 0);
    }

    fn unwrap_rule_skipping_test_code() -> Rule {
        parse_rule(
            r#"
id: test-unwrap
language: rust
severity: error
category: correctness
message: ".unwrap() forbidden"
rule:
  kind: call_expression
  regex: '\.unwrap\(\)\s*$'
skip_test_code: true
"#,
        )
        .unwrap()
    }

    #[test]
    fn cfg_test_block_excluded_by_post_filter() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("main.rs"),
            "fn prod() {\n    foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n    fn test_it() {\n        bar().unwrap();\n    }\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
        assert_eq!(
            result.findings.len(),
            1,
            "should only find the prod unwrap, not the one inside #[cfg(test)]"
        );
        assert_eq!(result.findings[0].line, 2);
    }

    #[test]
    fn cfg_test_kept_without_skip_test_code() {
        let dir = tempdir().unwrap();
        write(
            dir.path().join("main.rs"),
            "fn prod() {\n    foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n    fn test_it() {\n        bar().unwrap();\n    }\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(
            result.findings.len(),
            2,
            "rule without skip_test_code should find both"
        );
    }

    #[test]
    fn integration_test_file_excluded_by_skip_test_code() {
        let dir = tempdir().unwrap();
        let tests_dir = dir.path().join("tests");
        std::fs::create_dir(&tests_dir).unwrap();
        write(
            tests_dir.join("it.rs"),
            "fn check() {\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
        assert_eq!(
            result.findings.len(),
            0,
            "unwrap inside a tests/ integration file should be skipped"
        );
    }

    #[test]
    fn integration_test_file_kept_without_skip_test_code() {
        let dir = tempdir().unwrap();
        let tests_dir = dir.path().join("tests");
        std::fs::create_dir(&tests_dir).unwrap();
        write(
            tests_dir.join("it.rs"),
            "fn check() {\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(
            result.findings.len(),
            1,
            "rule without skip_test_code should still flag tests/ files"
        );
    }

    #[test]
    fn test_crate_directory_excluded_by_skip_test_code() {
        let dir = tempdir().unwrap();
        let test_crate = dir
            .path()
            .join("crates")
            .join("integrations_tests")
            .join("src");
        std::fs::create_dir_all(&test_crate).unwrap();
        write(
            test_crate.join("api.rs"),
            "fn check() {\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
        assert_eq!(
            result.findings.len(),
            0,
            "unwrap inside a *_tests crate should be skipped"
        );
    }

    #[test]
    fn test_crate_directory_kept_without_skip_test_code() {
        let dir = tempdir().unwrap();
        let test_crate = dir
            .path()
            .join("crates")
            .join("integrations_tests")
            .join("src");
        std::fs::create_dir_all(&test_crate).unwrap();
        write(
            test_crate.join("api.rs"),
            "fn check() {\n    foo().unwrap();\n}\n",
        )
        .unwrap();
        let result = scan_dir(dir.path(), &[unwrap_rule()]);
        assert_eq!(
            result.findings.len(),
            1,
            "rule without skip_test_code should still flag *_tests crate files"
        );
    }

    #[test]
    fn all_builtin_rules_compile() {
        let rules = load_builtin_rules().unwrap();
        assert!(
            rules.len() >= 55,
            "expected at least 55 rules, got {}",
            rules.len()
        );
        let compiled = compile_rules(&rules).expect("all builtin rules should compile");
        let ast_rule_count = rules.iter().filter(|r| !r.is_metric()).count();
        assert_eq!(compiled.by_id.len(), ast_rule_count);
        assert!(
            !compiled.metrics.is_empty(),
            "builtin rules should include metric rules"
        );
    }

    #[test]
    fn scan_files_only_scans_given_files() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a.rs");
        let b = 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 result = scan_files(&[a], &[unwrap_rule()], &Config::default()).unwrap();
        assert_eq!(result.findings.len(), 1);
        assert_eq!(result.stats.files_scanned, 1);
        assert!(result.findings[0].file.to_string_lossy().contains("a.rs"));
    }

    #[test]
    fn scan_files_skips_unsupported_language() {
        let dir = tempdir().unwrap();
        let py = dir.path().join("script.py");
        write(&py, "x.unwrap()\n").unwrap();

        let result = scan_files(&[py], &[unwrap_rule()], &Config::default()).unwrap();
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 0);
    }

    #[test]
    fn scan_files_skips_missing_file() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("gone.rs");

        let result = scan_files(&[missing], &[unwrap_rule()], &Config::default()).unwrap();
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 0);
    }

    #[test]
    fn scan_files_respects_config_ignores() {
        let dir = tempdir().unwrap();
        let gen = dir.path().join("generated");
        create_dir(&gen).unwrap();
        let out = gen.join("out.rs");
        write(&out, "fn g() { foo().unwrap(); }\n").unwrap();

        let mut cfg = Config::default();
        cfg.scan.ignores = vec!["**/generated/**".to_string()];
        let result = scan_files(&[out], &[unwrap_rule()], &cfg).unwrap();
        assert_eq!(result.findings.len(), 0);
        assert_eq!(result.stats.files_scanned, 0);
    }

    #[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);
    }

    fn metric_rule(body: &str) -> Rule {
        parse_rule(body).unwrap()
    }

    fn file_lines_rule() -> Rule {
        metric_rule(
            r#"
id: test-file-lines
language: rust
severity: warning
category: slop
metric: file_lines
threshold: 10
message: "File is too long"
"#,
        )
    }

    /// `n` lines of trivial Rust, one statement per line.
    fn rust_lines(n: usize) -> String {
        (0..n).map(|i| format!("// line {i}\n")).collect()
    }

    #[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");
    }
}