1use std::collections::HashMap;
2use std::fs::{self, read_to_string};
3use std::path::{Path, PathBuf};
4
5use ast_grep_config::{
6 CombinedScan, GlobalRules, RuleCollection, RuleConfig, RuleConfigError, SerializableRuleConfig,
7};
8use ast_grep_core::tree_sitter::LanguageExt;
9use ast_grep_core::Language as AstLanguage;
10use ast_grep_language::SupportLang;
11use globset::{Error as GlobError, Glob, GlobSet, GlobSetBuilder};
12use ignore::WalkBuilder;
13use rayon::prelude::*;
14use serde::Serialize;
15use serde_yaml::with::singleton_map_recursive;
16use serde_yaml::{to_value, Value};
17use strum::IntoEnumIterator;
18use thiserror::Error;
19
20use crate::cache::{file_content_hash, rules_hash, CacheStore};
21use crate::config::Config;
22use crate::disable::filter_disabled;
23use crate::finding::{CacheStats, Finding, ScanResult, ScanStats};
24use crate::rule::{Language, Rule, RuleId, Severity};
25use crate::test_filter::CfgTestRanges;
26
27#[derive(Debug, Error)]
28pub enum ScanError {
29 #[error("failed to compile rule '{id}': {source}")]
30 RuleCompile {
31 id: RuleId,
32 #[source]
33 source: RuleConfigError,
34 },
35
36 #[error("invalid glob pattern: {0}")]
37 Glob(#[from] GlobError),
38}
39
40#[derive(Serialize)]
43pub struct AstGrepRule<'a> {
44 pub id: &'a str,
45 pub language: SupportLang,
46 pub severity: &'a Severity,
47 pub message: &'a str,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub note: Option<&'a str>,
50 pub rule: &'a Value,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub files: Option<&'a [String]>,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub ignores: Option<&'a [String]>,
55}
56
57struct CompiledRules<'a> {
60 collection: RuleCollection<SupportLang>,
61 by_id: HashMap<(&'a str, Language), &'a Rule>,
62}
63
64fn extension_to_lang(path: &Path) -> Option<SupportLang> {
65 SupportLang::from_path(path)
66 .filter(|lang| Language::iter().any(|l| l.ast_grep_langs().contains(lang)))
67}
68
69fn support_lang_to_language(lang: SupportLang) -> Language {
70 match lang {
71 SupportLang::Rust => Language::Rust,
72 _ => Language::TypeScript,
73 }
74}
75
76pub(crate) fn compile_ast_grep_rule(
77 rule: &AstGrepRule,
78) -> Result<RuleConfig<SupportLang>, RuleConfigError> {
79 let inner: SerializableRuleConfig<SupportLang> = to_value(rule)
80 .and_then(singleton_map_recursive::deserialize)
81 .map_err(RuleConfigError::from)?;
82 RuleConfig::try_from(inner, &GlobalRules::default())
83}
84
85fn compile_rule(rule: &Rule, lang: SupportLang) -> Result<RuleConfig<SupportLang>, ScanError> {
86 let ast_grep_rule = AstGrepRule {
87 id: rule.id.as_str(),
88 language: lang,
89 severity: &rule.severity,
90 message: &rule.message,
91 note: rule.note.as_deref(),
92 rule: &rule.rule,
93 files: rule.files.as_deref(),
94 ignores: rule.ignores.as_deref(),
95 };
96 compile_ast_grep_rule(&ast_grep_rule).map_err(|source| ScanError::RuleCompile {
97 id: rule.id.clone(),
98 source,
99 })
100}
101
102fn compile_rules(rules: &[Rule]) -> Result<CompiledRules<'_>, ScanError> {
103 let configs = rules
104 .iter()
105 .flat_map(|rule| {
106 rule.language
107 .ast_grep_langs()
108 .iter()
109 .map(move |lang| compile_rule(rule, *lang))
110 })
111 .collect::<Result<Vec<_>, _>>()?;
112 Ok(CompiledRules {
113 collection: RuleCollection::try_new(configs)?,
114 by_id: rules
115 .iter()
116 .map(|rule| ((rule.id.as_str(), rule.language.clone()), rule))
117 .collect::<HashMap<_, _>>(),
118 })
119}
120
121fn build_glob_set(patterns: &[String]) -> Result<GlobSet, GlobError> {
122 let mut builder = GlobSetBuilder::new();
123 for pattern in patterns {
124 builder.add(Glob::new(pattern)?);
125 }
126 builder.build()
127}
128
129fn is_test_path(path: &Path) -> bool {
139 let in_test_dir = path.components().any(|c| {
140 let Some(name) = c.as_os_str().to_str() else {
141 return false;
142 };
143 matches!(name, "tests" | "benches" | "examples")
144 || name.ends_with("_tests")
145 || name.ends_with("_test")
146 || name.starts_with("test_")
147 });
148 let test_file_name = path
149 .file_stem()
150 .and_then(|s| s.to_str())
151 .is_some_and(|s| s.ends_with("_test") || s.ends_with("_tests"));
152 in_test_dir || test_file_name
153}
154
155fn scan_file(path: &Path, lang: SupportLang, rules: &CompiledRules) -> Vec<Finding> {
156 let applicable = rules.collection.get_rule_from_lang(path, lang);
157 if applicable.is_empty() {
158 return Vec::new();
159 }
160 let Ok(source) = read_to_string(path) else {
161 return Vec::new();
162 };
163
164 let root = lang.ast_grep(&source);
165 let combined = CombinedScan::new(applicable);
166 let result = combined.scan(&root, false);
167
168 let cfg_test = (lang == SupportLang::Rust && !result.matches.is_empty())
169 .then(|| CfgTestRanges::from_root(&root));
170 let cfg_test = cfg_test.as_ref();
171 let is_test_file = is_test_path(path);
172
173 let findings = result
174 .matches
175 .into_iter()
176 .filter_map(|(config, matches)| {
177 let rule_lang = support_lang_to_language(lang);
178 let rule = rules.by_id.get(&(config.id.as_str(), rule_lang))?;
179 Some((*rule, matches))
180 })
181 .flat_map(|(rule, matches)| {
182 let skip_test_code = rule.skip_test_code;
183 matches
184 .into_iter()
185 .map(move |node_match| {
186 let start = node_match.start_pos();
187 let end = node_match.end_pos();
188 Finding {
189 rule_id: rule.id.clone(),
190 severity: rule.severity.clone(),
191 category: rule.category.clone().unwrap_or_default(),
192 message: rule.message.clone(),
193 note: rule.note.clone(),
194 fix: rule.fix.clone(),
195 file: path.to_path_buf(),
196 line: start.line() + 1,
197 column: start.byte_point().1 + 1,
198 end_line: end.line() + 1,
199 end_column: end.byte_point().1 + 1,
200 matched_text: node_match.text().to_string(),
201 confidence: None,
202 }
203 })
204 .filter(move |f| {
205 if !skip_test_code {
206 return true;
207 }
208 let in_test_code =
209 is_test_file || cfg_test.is_some_and(|r| r.contains_line(f.line));
210 !in_test_code
211 })
212 })
213 .collect();
214
215 filter_disabled(findings, &source)
216}
217
218pub fn scan(paths: &[PathBuf], rules: &[Rule], config: &Config) -> Result<ScanResult, ScanError> {
220 let compiled = compile_rules(rules)?;
221 let ignores = build_glob_set(&config.scan.ignores)?;
222
223 let files: Vec<(PathBuf, SupportLang)> = paths
224 .iter()
225 .flat_map(|path| WalkBuilder::new(path).build().flatten())
226 .filter(|entry| entry.file_type().is_some_and(|t| t.is_file()))
227 .map(|entry| entry.into_path())
228 .filter(|path| !ignores.is_match(path))
229 .filter_map(|path| extension_to_lang(&path).map(|lang| (path, lang)))
230 .collect();
231
232 let mut findings: Vec<Finding> = files
233 .par_iter()
234 .flat_map_iter(|(path, lang)| scan_file(path, *lang, &compiled))
235 .collect();
236 findings.sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
237 findings.dedup_by(|a, b| {
238 a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
239 });
240
241 let (errors, warnings) =
242 findings
243 .iter()
244 .fold((0, 0), |(errors, warnings), f| match f.severity {
245 Severity::Error => (errors + 1, warnings),
246 Severity::Warning => (errors, warnings + 1),
247 });
248
249 Ok(ScanResult {
250 findings,
251 stats: ScanStats {
252 errors,
253 warnings,
254 total: errors + warnings,
255 files_scanned: files.len(),
256 },
257 cache_stats: None,
258 })
259}
260
261pub fn scan_cached(
270 paths: &[PathBuf],
271 rules: &[Rule],
272 config: &Config,
273 cache_dir: &Path,
274) -> Result<ScanResult, ScanError> {
275 let compiled = compile_rules(rules)?;
276 let ignores = build_glob_set(&config.scan.ignores)?;
277
278 let files: Vec<(PathBuf, SupportLang)> = paths
279 .iter()
280 .flat_map(|path| WalkBuilder::new(path).build().flatten())
281 .filter(|entry| entry.file_type().is_some_and(|t| t.is_file()))
282 .map(|entry| entry.into_path())
283 .filter(|path| !ignores.is_match(path))
284 .filter_map(|path| extension_to_lang(&path).map(|lang| (path, lang)))
285 .collect();
286
287 let store = CacheStore::with_dir(cache_dir.to_path_buf());
288 let current_rules_hash = rules_hash(rules);
289 let rules_changed = store
290 .check_rules_changed(¤t_rules_hash)
291 .unwrap_or(true);
292
293 let file_contents: Vec<(PathBuf, SupportLang, Vec<u8>, String)> = files
294 .into_iter()
295 .filter_map(|(path, lang)| {
296 let content = fs::read(&path).ok()?;
297 let hash = file_content_hash(&content);
298 Some((path, lang, content, hash))
299 })
300 .collect();
301
302 let mut cached_count = 0usize;
303 let mut changed_count = 0usize;
304 let mut all_findings: Vec<Finding> = Vec::new();
305
306 struct FileWork {
307 path: PathBuf,
308 lang: SupportLang,
309 hash: String,
310 }
311
312 let mut to_scan: Vec<FileWork> = Vec::new();
313
314 for (path, lang, _content, hash) in file_contents.iter() {
315 if !rules_changed {
316 if let Some(cached_findings) = store.get(hash) {
317 cached_count += 1;
318 all_findings.extend(cached_findings);
319 continue;
320 }
321 }
322 changed_count += 1;
323 to_scan.push(FileWork {
324 path: path.clone(),
325 lang: *lang,
326 hash: hash.clone(),
327 });
328 }
329
330 let scanned_findings: Vec<(String, Vec<Finding>)> = to_scan
331 .par_iter()
332 .map(|work| {
333 let findings = scan_file(&work.path, work.lang, &compiled);
334 (work.hash.clone(), findings)
335 })
336 .collect();
337
338 for (hash, findings) in scanned_findings {
339 store.put(&hash, &findings).ok();
340 all_findings.extend(findings);
341 }
342
343 let current_hashes: Vec<String> = file_contents.iter().map(|(_, _, _, h)| h.clone()).collect();
344 store.cleanup(¤t_hashes).ok();
345
346 all_findings.sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
347 all_findings.dedup_by(|a, b| {
348 a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
349 });
350
351 let (errors, warnings) =
352 all_findings
353 .iter()
354 .fold((0, 0), |(errors, warnings), f| match f.severity {
355 Severity::Error => (errors + 1, warnings),
356 Severity::Warning => (errors, warnings + 1),
357 });
358
359 let files_scanned = cached_count + changed_count;
360
361 Ok(ScanResult {
362 findings: all_findings,
363 stats: ScanStats {
364 errors,
365 warnings,
366 total: errors + warnings,
367 files_scanned,
368 },
369 cache_stats: Some(CacheStats {
370 cached: cached_count,
371 changed: changed_count,
372 }),
373 })
374}
375
376#[cfg(test)]
377mod tests {
378 use std::fs::{create_dir, write};
379
380 use tempfile::tempdir;
381
382 use super::*;
383 use crate::rule::{load_builtin_rules, parse_rule, RuleId};
384
385 fn unwrap_rule() -> Rule {
386 parse_rule(
387 r#"
388id: test-unwrap
389language: rust
390severity: error
391category: correctness
392message: ".unwrap() forbidden"
393rule:
394 kind: call_expression
395 regex: '\.unwrap\(\)\s*$'
396"#,
397 )
398 .unwrap()
399 }
400
401 fn scan_dir(dir: &Path, rules: &[Rule]) -> ScanResult {
402 scan(&[dir.to_path_buf()], rules, &Config::default()).unwrap()
403 }
404
405 #[test]
406 fn scan_finds_unwrap_violation() {
407 let dir = tempdir().unwrap();
408 write(
409 dir.path().join("main.rs"),
410 "fn main() {\n foo().unwrap();\n}\n",
411 )
412 .unwrap();
413 let result = scan_dir(dir.path(), &[unwrap_rule()]);
414 assert_eq!(result.findings.len(), 1);
415 let f = &result.findings[0];
416 assert_eq!(f.rule_id, RuleId::from("test-unwrap"));
417 assert_eq!(f.severity, Severity::Error);
418 assert_eq!(f.line, 2);
419 assert!(f.matched_text.contains("unwrap()"));
420 }
421
422 #[test]
423 fn scan_clean_file_no_findings() {
424 let dir = tempdir().unwrap();
425 write(dir.path().join("main.rs"), "fn main() { let x = foo(); }\n").unwrap();
426 let result = scan_dir(dir.path(), &[unwrap_rule()]);
427 assert_eq!(result.findings.len(), 0);
428 assert_eq!(result.stats.files_scanned, 1);
429 }
430
431 #[test]
432 fn scan_unsupported_language_ignored() {
433 let dir = tempdir().unwrap();
434 write(dir.path().join("script.py"), "x.unwrap()\n").unwrap();
435 write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();
436 let result = scan_dir(dir.path(), &[unwrap_rule()]);
437 assert_eq!(result.findings.len(), 0);
438 assert_eq!(result.stats.files_scanned, 1);
439 }
440
441 #[test]
442 fn scan_explicit_file_path() {
443 let dir = tempdir().unwrap();
444 let file = dir.path().join("main.rs");
445 write(&file, "fn main() { foo().unwrap(); }\n").unwrap();
446 let result = scan(&[file], &[unwrap_rule()], &Config::default()).unwrap();
447 assert_eq!(result.findings.len(), 1);
448 assert_eq!(result.stats.files_scanned, 1);
449 }
450
451 #[test]
452 fn rule_ignores_glob_respected() {
453 let dir = tempdir().unwrap();
454 let tests_dir = dir.path().join("tests");
455 create_dir(&tests_dir).unwrap();
456 write(
457 tests_dir.join("test_main.rs"),
458 "fn t() { foo().unwrap(); }\n",
459 )
460 .unwrap();
461 write(
462 dir.path().join("main.rs"),
463 "fn main() { foo().unwrap(); }\n",
464 )
465 .unwrap();
466 let rule = parse_rule(
467 r#"
468id: ign
469language: rust
470severity: error
471category: correctness
472message: x
473rule:
474 kind: call_expression
475 regex: '\.unwrap\(\)\s*$'
476ignores:
477 - "**/tests/**"
478"#,
479 )
480 .unwrap();
481 let result = scan_dir(dir.path(), &[rule]);
482 assert_eq!(result.findings.len(), 1);
483 assert!(result.findings[0]
484 .file
485 .to_string_lossy()
486 .contains("main.rs"));
487 }
488
489 #[test]
490 fn config_ignores_respected() {
491 let dir = tempdir().unwrap();
492 let gen = dir.path().join("generated");
493 create_dir(&gen).unwrap();
494 write(gen.join("out.rs"), "fn g() { foo().unwrap(); }\n").unwrap();
495 write(
496 dir.path().join("main.rs"),
497 "fn main() { foo().unwrap(); }\n",
498 )
499 .unwrap();
500 let mut cfg = Config::default();
501 cfg.scan.ignores = vec!["**/generated/**".to_string()];
502 let result = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap();
503 assert_eq!(result.stats.files_scanned, 1);
504 assert_eq!(result.findings.len(), 1);
505 }
506
507 #[test]
508 fn config_invalid_glob_is_an_error() {
509 let dir = tempdir().unwrap();
510 let mut cfg = Config::default();
511 cfg.scan.ignores = vec!["[".to_string()];
512 let err = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap_err();
513 assert!(matches!(err, ScanError::Glob(_)), "{err:?}");
514 }
515
516 #[test]
517 fn rule_without_kind_fails_to_compile() {
518 let dir = tempdir().unwrap();
519 let rule = parse_rule(
520 r#"
521id: no-kind
522language: rust
523severity: error
524category: correctness
525message: x
526rule:
527 regex: 'unwrap'
528"#,
529 )
530 .unwrap();
531 let err = scan(&[dir.path().to_path_buf()], &[rule], &Config::default()).unwrap_err();
532 assert!(
533 matches!(&err, ScanError::RuleCompile { id, .. } if *id == RuleId::from("no-kind")),
534 "{err:?}"
535 );
536 }
537
538 #[test]
539 fn stats_counting_accurate() {
540 let dir = tempdir().unwrap();
541 write(
542 dir.path().join("a.rs"),
543 "fn f() { foo().unwrap(); bar().unwrap(); }\n",
544 )
545 .unwrap();
546 let result = scan_dir(dir.path(), &[unwrap_rule()]);
547 assert_eq!(result.stats.errors, 2);
548 assert_eq!(result.stats.warnings, 0);
549 assert_eq!(result.stats.total, 2);
550 assert_eq!(result.stats.files_scanned, 1);
551 }
552
553 #[test]
554 fn scan_empty_file() {
555 let dir = tempdir().unwrap();
556 write(dir.path().join("empty.rs"), "").unwrap();
557 let result = scan_dir(dir.path(), &[unwrap_rule()]);
558 assert_eq!(result.findings.len(), 0);
559 assert_eq!(result.stats.files_scanned, 1);
560 }
561
562 #[test]
563 fn scan_complex_rule() {
564 let rule = parse_rule(
565 r#"
566id: dbg
567language: rust
568severity: error
569category: security
570message: debug on secret
571rule:
572 kind: attribute_item
573 all:
574 - regex: 'derive\([^)]*Debug'
575 - precedes:
576 kind: struct_item
577 has:
578 kind: field_identifier
579 regex: '^(api_key|password|secret)$'
580 stopBy: end
581"#,
582 )
583 .unwrap();
584 let dir = tempdir().unwrap();
585 write(
586 dir.path().join("t.rs"),
587 "#[derive(Debug)]\nstruct Config {\n api_key: String,\n}\n",
588 )
589 .unwrap();
590 let result = scan_dir(dir.path(), &[rule]);
591 assert_eq!(result.findings.len(), 1);
592 assert_eq!(result.findings[0].rule_id, RuleId::from("dbg"));
593 }
594
595 #[test]
596 fn typescript_rule_applies_to_tsx_files() {
597 let rule = parse_rule(
598 r#"
599id: ts-any
600language: typescript
601severity: warning
602category: slop
603message: no any
604rule:
605 kind: predefined_type
606 regex: '^any$'
607"#,
608 )
609 .unwrap();
610 let dir = tempdir().unwrap();
611 write(dir.path().join("a.ts"), "let x: any = 1;\n").unwrap();
612 write(dir.path().join("b.tsx"), "let y: any = 2;\n").unwrap();
613 let result = scan_dir(dir.path(), &[rule]);
614 assert_eq!(result.stats.files_scanned, 2);
615 assert_eq!(result.stats.warnings, 2);
616 }
617
618 #[test]
619 fn scan_with_disable_comment_filters_findings() {
620 let dir = tempdir().unwrap();
621 write(
622 dir.path().join("main.rs"),
623 "fn main() {\n // slopguard-disable-next-line\n foo().unwrap();\n bar().unwrap();\n}\n",
624 )
625 .unwrap();
626 let result = scan_dir(dir.path(), &[unwrap_rule()]);
627 assert_eq!(
628 result.findings.len(),
629 1,
630 "only the non-disabled unwrap should remain"
631 );
632 assert_eq!(result.findings[0].line, 4);
633 }
634
635 #[test]
636 fn scan_with_disable_rule_id_filters_only_that_rule() {
637 let dir = tempdir().unwrap();
638 write(
639 dir.path().join("main.rs"),
640 "fn main() {\n // slopguard-disable-next-line test-unwrap\n foo().unwrap();\n}\n",
641 )
642 .unwrap();
643 let result = scan_dir(dir.path(), &[unwrap_rule()]);
644 assert_eq!(result.findings.len(), 0);
645 }
646
647 fn unwrap_rule_skipping_test_code() -> Rule {
648 parse_rule(
649 r#"
650id: test-unwrap
651language: rust
652severity: error
653category: correctness
654message: ".unwrap() forbidden"
655rule:
656 kind: call_expression
657 regex: '\.unwrap\(\)\s*$'
658skip_test_code: true
659"#,
660 )
661 .unwrap()
662 }
663
664 #[test]
665 fn cfg_test_block_excluded_by_post_filter() {
666 let dir = tempdir().unwrap();
667 write(
668 dir.path().join("main.rs"),
669 "fn prod() {\n foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n fn test_it() {\n bar().unwrap();\n }\n}\n",
670 )
671 .unwrap();
672 let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
673 assert_eq!(
674 result.findings.len(),
675 1,
676 "should only find the prod unwrap, not the one inside #[cfg(test)]"
677 );
678 assert_eq!(result.findings[0].line, 2);
679 }
680
681 #[test]
682 fn cfg_test_kept_without_skip_test_code() {
683 let dir = tempdir().unwrap();
684 write(
685 dir.path().join("main.rs"),
686 "fn prod() {\n foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n fn test_it() {\n bar().unwrap();\n }\n}\n",
687 )
688 .unwrap();
689 let result = scan_dir(dir.path(), &[unwrap_rule()]);
690 assert_eq!(
691 result.findings.len(),
692 2,
693 "rule without skip_test_code should find both"
694 );
695 }
696
697 #[test]
698 fn integration_test_file_excluded_by_skip_test_code() {
699 let dir = tempdir().unwrap();
700 let tests_dir = dir.path().join("tests");
701 std::fs::create_dir(&tests_dir).unwrap();
702 write(
703 tests_dir.join("it.rs"),
704 "fn check() {\n foo().unwrap();\n}\n",
705 )
706 .unwrap();
707 let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
708 assert_eq!(
709 result.findings.len(),
710 0,
711 "unwrap inside a tests/ integration file should be skipped"
712 );
713 }
714
715 #[test]
716 fn integration_test_file_kept_without_skip_test_code() {
717 let dir = tempdir().unwrap();
718 let tests_dir = dir.path().join("tests");
719 std::fs::create_dir(&tests_dir).unwrap();
720 write(
721 tests_dir.join("it.rs"),
722 "fn check() {\n foo().unwrap();\n}\n",
723 )
724 .unwrap();
725 let result = scan_dir(dir.path(), &[unwrap_rule()]);
726 assert_eq!(
727 result.findings.len(),
728 1,
729 "rule without skip_test_code should still flag tests/ files"
730 );
731 }
732
733 #[test]
734 fn test_crate_directory_excluded_by_skip_test_code() {
735 let dir = tempdir().unwrap();
736 let test_crate = dir
737 .path()
738 .join("crates")
739 .join("integrations_tests")
740 .join("src");
741 std::fs::create_dir_all(&test_crate).unwrap();
742 write(
743 test_crate.join("api.rs"),
744 "fn check() {\n foo().unwrap();\n}\n",
745 )
746 .unwrap();
747 let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
748 assert_eq!(
749 result.findings.len(),
750 0,
751 "unwrap inside a *_tests crate should be skipped"
752 );
753 }
754
755 #[test]
756 fn test_crate_directory_kept_without_skip_test_code() {
757 let dir = tempdir().unwrap();
758 let test_crate = dir
759 .path()
760 .join("crates")
761 .join("integrations_tests")
762 .join("src");
763 std::fs::create_dir_all(&test_crate).unwrap();
764 write(
765 test_crate.join("api.rs"),
766 "fn check() {\n foo().unwrap();\n}\n",
767 )
768 .unwrap();
769 let result = scan_dir(dir.path(), &[unwrap_rule()]);
770 assert_eq!(
771 result.findings.len(),
772 1,
773 "rule without skip_test_code should still flag *_tests crate files"
774 );
775 }
776
777 #[test]
778 fn all_builtin_rules_compile() {
779 let rules = load_builtin_rules().unwrap();
780 assert!(
781 rules.len() >= 55,
782 "expected at least 55 rules, got {}",
783 rules.len()
784 );
785 let compiled = compile_rules(&rules).expect("all builtin rules should compile");
786 assert_eq!(compiled.by_id.len(), rules.len());
787 }
788
789 #[test]
790 fn scan_with_cache() {
791 let src_dir = tempdir().unwrap();
792 let cache_dir = tempdir().unwrap();
793 let cache_path = cache_dir.path().join("cache");
794 write(
795 src_dir.path().join("main.rs"),
796 "fn main() {\n foo().unwrap();\n}\n",
797 )
798 .unwrap();
799
800 let rules = [unwrap_rule()];
801 let config = Config::default();
802
803 let result1 = scan_cached(
804 &[src_dir.path().to_path_buf()],
805 &rules,
806 &config,
807 &cache_path,
808 )
809 .unwrap();
810
811 assert_eq!(result1.findings.len(), 1);
812 let cache_stats1 = result1.cache_stats.as_ref().unwrap();
813 assert_eq!(cache_stats1.cached, 0, "first scan: nothing cached");
814 assert_eq!(cache_stats1.changed, 1, "first scan: one file scanned");
815
816 let result2 = scan_cached(
817 &[src_dir.path().to_path_buf()],
818 &rules,
819 &config,
820 &cache_path,
821 )
822 .unwrap();
823
824 assert_eq!(result2.findings.len(), 1);
825 let cache_stats2 = result2.cache_stats.as_ref().unwrap();
826 assert_eq!(cache_stats2.cached, 1, "second scan: one file from cache");
827 assert_eq!(cache_stats2.changed, 0, "second scan: nothing changed");
828 }
829}