garbage-code-hunter 0.2.2

A humorous Rust code quality detector that roasts your garbage code
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
use regex::Regex;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

use crate::context::ProjectConfig;
use crate::finding::StyleFinding;
use crate::language::{Language, SUPPORTED_EXTENSIONS};
use crate::signals::{aggregate_detector_scores, SignalDetector, StyleSignal};
use crate::style_ir::{StyleIr, StyleIrSummary};
use crate::treesitter::duplication::{CrossFileDupDetector, IntraFileDupDetector};
use crate::treesitter::engine::{ParsedFile, TreeSitterEngine};

pub struct StyleIrFileInfo {
    pub file_path: String,
    pub summary: StyleIrSummary,
    pub is_test: bool,
}

pub struct FullAnalysisResult {
    pub findings: Vec<StyleFinding>,
    pub file_count: usize,
    pub total_lines: usize,
    pub style_ir_files: Vec<StyleIrFileInfo>,
}

#[derive(Debug, Clone)]
pub struct CodeIssue {
    pub file_path: PathBuf,
    pub line: usize,
    pub column: usize,
    pub rule_name: String,
    pub message: String,
    pub severity: Severity,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
    Mild,    // Minor issues
    Spicy,   // Medium issues
    Nuclear, // Serious issues
}

pub struct CodeAnalyzer {
    ts_engine: TreeSitterEngine,
    exclude_patterns: Vec<Regex>,
    project_config: ProjectConfig,
    cross_detector: RefCell<CrossFileDupDetector>,
    detectors: Vec<Box<dyn SignalDetector>>,
    direct_scores: RefCell<HashMap<StyleSignal, f64>>,
}

impl CodeAnalyzer {
    pub fn new(exclude_patterns: &[String], lang: &str) -> Self {
        Self::with_config(exclude_patterns, lang, ProjectConfig::default())
    }

    pub fn infection_spread(&self) -> HashMap<String, Vec<(String, usize, Vec<String>)>> {
        self.cross_detector.borrow().infection_spread()
    }

    pub fn with_config(exclude_patterns: &[String], _lang: &str, config: ProjectConfig) -> Self {
        // Default exclude patterns for common build/dependency directories
        let default_excludes = [
            "target",
            "node_modules",
            ".git",
            ".svn",
            ".hg",
            "build",
            "dist",
            "out",
            "__pycache__",
            ".DS_Store",
            ".venv",
            "venv",
            "vendor",
        ];

        let mut all_patterns: Vec<String> =
            default_excludes.iter().map(|s| s.to_string()).collect();
        all_patterns.extend(exclude_patterns.iter().cloned());

        // Also add exclude patterns from project config
        all_patterns.extend(config.whitelists.exclude_patterns.clone());

        let patterns = all_patterns
            .iter()
            .filter_map(|pattern| {
                // Convert glob patterns to regular expressions with path-boundary anchoring.
                // Without anchors, "build" would match "mybuild/foo.o" — a substring false positive.
                let glob_pattern = pattern
                    .replace(".", r"\.")
                    .replace("*", ".*")
                    .replace("?", ".");
                let regex_pattern = format!(r"(?:^|/){}(?:/|$)", glob_pattern);
                Regex::new(&regex_pattern).ok()
            })
            .collect();

        Self {
            ts_engine: TreeSitterEngine::new(),
            exclude_patterns: patterns,
            project_config: config,
            cross_detector: RefCell::new(CrossFileDupDetector::new()),
            detectors: Vec::new(),
            direct_scores: RefCell::new(HashMap::new()),
        }
    }

    pub fn with_detectors(mut self, detectors: Vec<Box<dyn SignalDetector>>) -> Self {
        self.detectors = detectors;
        self
    }

    pub fn direct_signal_scores(&self) -> HashMap<StyleSignal, f64> {
        self.direct_scores.borrow().clone()
    }

    fn should_exclude(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        self.exclude_patterns
            .iter()
            .any(|pattern| pattern.is_match(&path_str))
    }

    /// Collect source files from a path (file or directory). Excludes
    /// unsupported extensions and should_exclude paths. Includes generated files.
    fn collect_source_files(&self, path: &Path) -> Vec<PathBuf> {
        if path.is_file() {
            if !self.should_exclude(path) {
                let lang = Language::from_path(path);
                if lang != Language::Unknown {
                    return vec![path.to_path_buf()];
                }
            }
            return Vec::new();
        }
        if !path.is_dir() {
            return Vec::new();
        }
        WalkDir::new(path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| !self.should_exclude(e.path()))
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .is_some_and(|ext| SUPPORTED_EXTENSIONS.contains(&ext))
            })
            .map(|e| e.path().to_path_buf())
            .collect()
    }

    /// Compatibility wrapper — runs the full pipeline and converts back to `CodeIssue`s.
    pub fn analyze_path(&self, path: &Path) -> Vec<CodeIssue> {
        self.analyze_to_findings(path)
            .into_iter()
            .map(|f| f.to_code_issue())
            .collect()
    }

    /// Full analysis pipeline returning `StyleFinding`s.
    ///
    /// - Phase 1: Parse all files and cache `ParsedFile`s
    /// - Phase 2: Cross-file duplication detection
    /// - Phase 3: Intra-file duplication detection
    /// - Phase 4: Direct signal detection (scores + findings)
    ///
    /// Also populates `self.direct_scores` for downstream consumers.
    pub fn analyze_to_findings(&self, path: &Path) -> Vec<StyleFinding> {
        let files = self.collect_source_files(path);
        if files.is_empty() {
            return Vec::new();
        }

        // Phase 1: Parse all files and cache for downstream phases
        let mut parsed_files: Vec<(ParsedFile, PathBuf, bool)> = Vec::new();

        for file_path in &files {
            if Self::is_generated_file(file_path) {
                continue;
            }
            let content = match fs::read_to_string(file_path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            let lang = Language::from_path(file_path);
            if lang == Language::Unknown {
                continue;
            }
            let is_test_file = Self::is_test_file(file_path);

            if let Some(parsed) = self.ts_engine.parse_file(file_path, &content) {
                parsed_files.push((parsed, file_path.clone(), is_test_file));
            }
        }

        // Phase 2: Cross-file duplication detection
        let mut issues: Vec<CodeIssue> = Vec::new();
        *self.cross_detector.borrow_mut() = CrossFileDupDetector::new();
        for (parsed, _, is_test) in &parsed_files {
            if *is_test && self.project_config.signals.skip_tests {
                continue;
            }
            self.cross_detector.borrow_mut().process_file(parsed);
        }
        issues.extend(self.cross_detector.borrow().find_duplicates());
        issues.extend(self.cross_detector.borrow().find_near_duplicates());

        // Phase 3: Intra-file code duplication
        for (parsed, _, is_test) in &parsed_files {
            if *is_test && self.project_config.signals.skip_tests {
                continue;
            }
            issues.extend(IntraFileDupDetector::check(parsed));
        }

        // Phase 4: Direct signal detection (scores + findings)
        let mut findings: Vec<StyleFinding> = issues.iter().map(From::from).collect();
        if !self.detectors.is_empty() && !parsed_files.is_empty() {
            let parsed_for_scores: Vec<ParsedFile> =
                parsed_files.iter().map(|(p, _, _)| p.clone()).collect();
            let test_flags: Vec<bool> = parsed_files
                .iter()
                .map(|(_, _, is_test)| *is_test)
                .collect();
            let skip_tests_config = self.project_config.signals.skip_tests;
            *self.direct_scores.borrow_mut() = aggregate_detector_scores(
                &self.detectors,
                &parsed_for_scores,
                &test_flags,
                skip_tests_config,
            );

            for (parsed, file_path, is_test_file) in &parsed_files {
                let lang = parsed.language;
                let ir = StyleIr::from_parsed(parsed);
                for detector in &self.detectors {
                    if !detector.supported_languages().contains(&lang) {
                        continue;
                    }
                    let findings_iter = if let Some(ref ir) = ir {
                        detector.detect_findings_with_ir(
                            ir,
                            parsed,
                            *is_test_file,
                            skip_tests_config,
                        )
                    } else {
                        detector.detect_findings(parsed, *is_test_file, skip_tests_config)
                    };
                    for (signal, count) in findings_iter {
                        let count = if *is_test_file {
                            (count as f64 * 0.2).round() as usize
                        } else {
                            count
                        };
                        if count > 0 {
                            findings.push(StyleFinding::for_signal(
                                signal,
                                count,
                                file_path.clone(),
                            ));
                        }
                    }
                }
            }
        }

        findings
    }

    pub fn analyze_full(&self, path: &Path) -> FullAnalysisResult {
        let files = self.collect_source_files(path);
        if files.is_empty() {
            return FullAnalysisResult {
                findings: Vec::new(),
                file_count: 0,
                total_lines: 0,
                style_ir_files: Vec::new(),
            };
        }

        let mut parsed_files: Vec<(ParsedFile, PathBuf, bool)> = Vec::new();
        let mut style_ir_files: Vec<StyleIrFileInfo> = Vec::new();
        let mut file_count: usize = 0;
        let mut total_lines: usize = 0;

        for file_path in &files {
            if Self::is_generated_file(file_path) {
                continue;
            }
            let content = match fs::read_to_string(file_path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            let lang = Language::from_path(file_path);
            if lang == Language::Unknown {
                continue;
            }
            file_count += 1;
            total_lines += content.lines().count();
            let is_test_file = Self::is_test_file(file_path);

            if let Some(parsed) = self.ts_engine.parse_file(file_path, &content) {
                if let Some(ir) = StyleIr::from_parsed(&parsed) {
                    style_ir_files.push(StyleIrFileInfo {
                        file_path: file_path.to_string_lossy().to_string(),
                        summary: ir.summary(),
                        is_test: is_test_file,
                    });
                }
                parsed_files.push((parsed, file_path.clone(), is_test_file));
            }
        }

        // Phase 2-3: Duplication detection
        let mut issues: Vec<CodeIssue> = Vec::new();
        *self.cross_detector.borrow_mut() = CrossFileDupDetector::new();
        for (parsed, _, _) in &parsed_files {
            self.cross_detector.borrow_mut().process_file(parsed);
        }
        issues.extend(self.cross_detector.borrow().find_duplicates());
        issues.extend(self.cross_detector.borrow().find_near_duplicates());

        for (parsed, _, _) in &parsed_files {
            issues.extend(IntraFileDupDetector::check(parsed));
        }

        let mut findings: Vec<StyleFinding> = issues.iter().map(From::from).collect();

        if !self.detectors.is_empty() && !parsed_files.is_empty() {
            let parsed_for_scores: Vec<ParsedFile> =
                parsed_files.iter().map(|(p, _, _)| p.clone()).collect();
            let test_flags: Vec<bool> = parsed_files
                .iter()
                .map(|(_, _, is_test)| *is_test)
                .collect();
            let skip_tests_config = self.project_config.signals.skip_tests;
            *self.direct_scores.borrow_mut() = aggregate_detector_scores(
                &self.detectors,
                &parsed_for_scores,
                &test_flags,
                skip_tests_config,
            );

            for (parsed, file_path, is_test_file) in &parsed_files {
                let lang = parsed.language;
                let ir = StyleIr::from_parsed(parsed);
                for detector in &self.detectors {
                    if !detector.supported_languages().contains(&lang) {
                        continue;
                    }
                    let findings_iter = if let Some(ref ir) = ir {
                        detector.detect_findings_with_ir(
                            ir,
                            parsed,
                            *is_test_file,
                            skip_tests_config,
                        )
                    } else {
                        detector.detect_findings(parsed, *is_test_file, skip_tests_config)
                    };
                    for (signal, count) in findings_iter {
                        let count = if *is_test_file {
                            (count as f64 * 0.2).round() as usize
                        } else {
                            count
                        };
                        if count > 0 {
                            findings.push(StyleFinding::for_signal(
                                signal,
                                count,
                                file_path.clone(),
                            ));
                        }
                    }
                }
            }
        }

        FullAnalysisResult {
            findings,
            file_count,
            total_lines,
            style_ir_files,
        }
    }

    fn is_generated_file(path: &Path) -> bool {
        let name = path.to_string_lossy();
        // Protobuf generated files
        name.ends_with(".pb.go")
            || name.contains("_grpc.pb.go")
            || name.ends_with(".pb.gw.go")
            || name.ends_with(".pulsar.go")
            || name.ends_with(".pb.cc")
            || name.ends_with(".pb.h")
        // Dependencies
            || name.contains("/node_modules/")
            || name.contains("\\node_modules\\")
            || name.contains("/vendor/")
            || name.contains("\\vendor\\")
        // Minified bundles
            || name.contains("/swagger-ui/")
        // Generated files from code generators
            || name.contains(".gen.")
            || name.contains(".generated.")
        // Minified / bundled JavaScript
            || name.ends_with(".min.js")
            || name.ends_with(".bundle.js")
    }

    pub fn analyze_file(&self, file_path: &Path) -> Vec<CodeIssue> {
        if Self::is_generated_file(file_path) {
            return vec![];
        }
        self.analyze_path(file_path)
    }

    fn is_test_file(path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        let normalized = path_str.strip_prefix("./").unwrap_or(&path_str);

        if normalized.contains("/tests/")
            || normalized.contains("\\tests\\")
            || normalized.starts_with("tests/")
            || normalized.starts_with("tests\\")
            || normalized.contains("/test/")
            || normalized.contains("\\test\\")
            || normalized.ends_with("_test.rs")
            || normalized.ends_with("_tests.rs")
            || normalized.ends_with("_test.c")
            || normalized.ends_with("_test.cpp")
            || normalized.ends_with("_test.cc")
            || normalized.ends_with("_test.go")
            || normalized.ends_with(".test.js")
            || normalized.ends_with(".spec.js")
            || normalized.ends_with(".test.jsx")
            || normalized.ends_with(".spec.jsx")
            || normalized.ends_with(".test.ts")
            || normalized.ends_with(".spec.ts")
            || normalized.ends_with(".test.tsx")
            || normalized.ends_with(".spec.tsx")
            || normalized.ends_with("_test.rb")
            || normalized.ends_with("_spec.rb")
            || normalized.ends_with("Test.java")
            || normalized.ends_with("Tests.java")
            || normalized.ends_with("Tests.swift")
            || normalized.ends_with("Test.swift")
            || normalized.ends_with("_test.zig")
            || normalized.starts_with("test_")
        {
            return true;
        }
        // Check for example files (singular and plural)
        if normalized.contains("/examples/")
            || normalized.contains("\\examples\\")
            || normalized.starts_with("examples/")
            || normalized.starts_with("examples\\")
            || normalized.contains("/example/")
            || normalized.contains("\\example\\")
            || normalized.starts_with("example/")
            || normalized.starts_with("example\\")
            || normalized.ends_with("_example.rs")
            || normalized.ends_with("_examples.rs")
        {
            return true;
        }
        // Check for benchmark files
        if normalized.contains("/benches/")
            || normalized.contains("\\benches\\")
            || normalized.starts_with("benches/")
            || normalized.starts_with("benches\\")
            || normalized.ends_with("_bench.rs")
            || normalized.ends_with("_benches.rs")
        {
            return true;
        }
        // Check for test-files directories
        if normalized.contains("/test-files/")
            || normalized.contains("\\test-files\\")
            || normalized.starts_with("test-files/")
            || normalized.starts_with("test-files\\")
            || normalized.contains("/test_files/")
            || normalized.contains("\\test_files\\")
        {
            return true;
        }
        // Check for fixture/mock directories
        if normalized.contains("/fixtures/")
            || normalized.contains("\\fixtures\\")
            || normalized.contains("/mocks/")
            || normalized.contains("\\mocks\\")
        {
            return true;
        }
        false
    }
}

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

    // ── is_generated_file ────────────────────────────────────────

    /// Objective: Verify that protobuf-generated files (.pb.go, _grpc.pb.go, .pb.gw.go,
    ///            .pulsar.go, .pb.cc, .pb.h) are correctly identified as generated.
    /// Invariants: All protobuf suffix patterns must be detected regardless of path prefix.
    #[test]
    fn test_is_generated_file_detects_all_protobuf_suffixes() {
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("api.pb.go")),
            "expected .pb.go to be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("service_grpc.pb.go")),
            "expected _grpc.pb.go to be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("gateway.pb.gw.go")),
            "expected .pb.gw.go to be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("topic.pulsar.go")),
            "expected .pulsar.go to be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("types.pb.cc")),
            "expected .pb.cc to be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("types.pb.h")),
            "expected .pb.h to be generated"
        );
    }

    /// Objective: Verify that dependency/vendor directories are detected.
    /// Invariants: Paths containing /node_modules/, /vendor/, or /swagger-ui/ are generated,
    ///             regardless of the file extension.
    #[test]
    fn test_is_generated_file_detects_dependency_directories() {
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("/project/node_modules/foo/index.js")),
            "node_modules should be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("/project/vendor/bar/main.rs")),
            "vendor should be generated"
        );
        assert!(
            CodeAnalyzer::is_generated_file(Path::new("/project/swagger-ui/index.html")),
            "swagger-ui should be generated"
        );
    }

    /// Objective: Verify that user-written source files are NOT marked as generated.
    /// Invariants: Any path that does not match a generated suffix or generated directory
    ///             pattern must return false.
    #[test]
    fn test_is_generated_file_does_not_flag_user_code() {
        assert!(
            !CodeAnalyzer::is_generated_file(Path::new("src/main.rs")),
            "src/main.rs should not be generated"
        );
        assert!(
            !CodeAnalyzer::is_generated_file(Path::new("src/server.go")),
            "src/server.go (Go source) should not be generated"
        );
        assert!(
            !CodeAnalyzer::is_generated_file(Path::new("app.py")),
            "app.py should not be generated"
        );
    }

    /// Objective: Verify that a file ending in .go but not matching any protobuf pattern
    ///            is correctly treated as user code, even in a path containing "vendor"
    ///            as a substring (not the /vendor/ directory).
    /// Invariants: Only exact /vendor/ path component must match, not partial substring.
    #[test]
    fn test_is_generated_file_does_not_false_positive_go_source() {
        assert!(
            !CodeAnalyzer::is_generated_file(Path::new("src/vendor_service.go")),
            "vendor_service.go should not be treated as generated just because 'vendor' appears in the name"
        );
    }

    // ── is_test_file ─────────────────────────────────────────────

    #[test]
    fn test_is_test_file_detects_test_directories() {
        assert!(CodeAnalyzer::is_test_file(Path::new("src/tests/helper.rs")));
        assert!(CodeAnalyzer::is_test_file(Path::new("examples/hello.rs")));
        assert!(CodeAnalyzer::is_test_file(Path::new("benches/perf.rs")));
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "tests/fixtures/data.rs"
        )));
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "tests/mocks/service.rs"
        )));
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "test-files/input.txt"
        )));
    }

    #[test]
    fn test_is_test_file_detects_rust_c_cpp() {
        assert!(CodeAnalyzer::is_test_file(Path::new("src/foo_test.rs")));
        assert!(CodeAnalyzer::is_test_file(Path::new("src/foo_tests.rs")));
        assert!(CodeAnalyzer::is_test_file(Path::new("test_main.c")));
        assert!(CodeAnalyzer::is_test_file(Path::new("foo_test.c")));
        assert!(CodeAnalyzer::is_test_file(Path::new("foo_test.cpp")));
        assert!(CodeAnalyzer::is_test_file(Path::new("foo_test.cc")));
    }

    #[test]
    fn test_is_test_file_detects_go() {
        assert!(CodeAnalyzer::is_test_file(Path::new("handler_test.go")));
        assert!(CodeAnalyzer::is_test_file(Path::new("pkg/service_test.go")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("handler.go")));
    }

    #[test]
    fn test_is_test_file_detects_js_ts() {
        assert!(CodeAnalyzer::is_test_file(Path::new("app.test.js")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.spec.js")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.test.jsx")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.spec.jsx")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.test.ts")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.spec.ts")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.test.tsx")));
        assert!(CodeAnalyzer::is_test_file(Path::new("app.spec.tsx")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("app.js")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("app.ts")));
    }

    #[test]
    fn test_is_test_file_detects_java() {
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "UserServiceTest.java"
        )));
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "UserServiceTests.java"
        )));
        assert!(!CodeAnalyzer::is_test_file(Path::new("UserService.java")));
    }

    #[test]
    fn test_is_test_file_detects_ruby() {
        assert!(CodeAnalyzer::is_test_file(Path::new("user_test.rb")));
        assert!(CodeAnalyzer::is_test_file(Path::new("user_spec.rb")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("user.rb")));
    }

    #[test]
    fn test_is_test_file_detects_swift() {
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "UserServiceTests.swift"
        )));
        assert!(CodeAnalyzer::is_test_file(Path::new(
            "UserServiceTest.swift"
        )));
        assert!(!CodeAnalyzer::is_test_file(Path::new("UserService.swift")));
    }

    #[test]
    fn test_is_test_file_detects_zig() {
        assert!(CodeAnalyzer::is_test_file(Path::new("main_test.zig")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("main.zig")));
    }

    #[test]
    fn test_is_test_file_does_not_flag_normal_source() {
        assert!(!CodeAnalyzer::is_test_file(Path::new("src/main.rs")));
        assert!(!CodeAnalyzer::is_test_file(Path::new("src/lib.rs")));
    }

    #[test]
    fn test_is_test_file_strips_leading_dot_slash() {
        assert!(CodeAnalyzer::is_test_file(Path::new("./tests/test.rs")));
    }

    // ── should_exclude ───────────────────────────────────────────

    /// Objective: Verify that default exclude patterns (target, node_modules, .git etc.)
    ///            are applied automatically even without custom patterns.
    /// Invariants: CodeAnalyzer::new with empty custom patterns still excludes common dirs.
    #[test]
    fn test_should_exclude_applies_default_patterns() {
        let analyzer = CodeAnalyzer::new(&[], "en");
        assert!(
            analyzer.should_exclude(Path::new("node_modules/foo")),
            "node_modules should be excluded by default"
        );
        assert!(
            analyzer.should_exclude(Path::new("target/debug/build")),
            "target/ should be excluded by default"
        );
        assert!(
            !analyzer.should_exclude(Path::new("src/main.rs")),
            "src/ should not be excluded"
        );
    }

    /// Objective: Verify that custom exclude patterns are added alongside defaults.
    /// Invariants: Both custom and default patterns are checked.
    #[test]
    fn test_should_exclude_combines_custom_and_default_patterns() {
        let analyzer = CodeAnalyzer::new(&["generated".to_string()], "en");
        assert!(
            analyzer.should_exclude(Path::new("build/generated/code.rs")),
            "custom pattern 'generated' should match"
        );
        assert!(
            analyzer.should_exclude(Path::new("target/release/exe")),
            "default pattern 'target' should still match"
        );
    }

    /// Objective: Verify that a pattern does NOT match unrelated directories.
    /// Invariants: Glob-to-regex conversion creates "build" => "build.*", which should
    ///             match "build/..." but not "src/main.rs".
    #[test]
    fn test_should_exclude_only_matches_intended_directories() {
        let analyzer = CodeAnalyzer::new(&["build".to_string()], "en");
        assert!(
            analyzer.should_exclude(Path::new("build/foo.o")),
            "'build' pattern should match build/ path"
        );
        assert!(
            !analyzer.should_exclude(Path::new("src/main.rs")),
            "'build' pattern should NOT match src/ path"
        );
    }

    // ── analyze_to_findings ───────────────────────────────────────

    /// Objective: Verify that `analyze_to_findings()` produces both rule-based
    /// findings (from CodeIssue conversion) AND direct detector signal findings.
    /// Invariants: With a file containing panics + naming issues, the output must
    /// include at least some PanicAddiction findings and some findings with a signal
    /// other than Duplication (the default when no signal is recognized).
    #[test]
    fn test_analyze_to_findings_includes_detector_findings() {
        use crate::detectors::PanicAddictionDetector;
        use std::io::Write;

        let dir = tempfile::tempdir().expect("tempdir");
        let file_path = dir.path().join("code.rs");
        let mut f = std::fs::File::create(&file_path).expect("create temp file");
        write!(
            f,
            "fn main() {{
    let _ = foo.unwrap();
    let _ = bar.expect(\"msg\");
    panic!(\"boom\");
    let x = 1;
}}
"
        )
        .expect("write");

        let analyzer = CodeAnalyzer::new(&[], "en")
            .with_detectors(vec![
                Box::new(PanicAddictionDetector::new()) as Box<dyn SignalDetector>
            ]);

        let findings = analyzer.analyze_to_findings(dir.path());

        // Must have at least one finding with PanicAddiction signal
        let panic_signal_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.signal == StyleSignal::PanicAddiction)
            .collect();
        assert!(
            !panic_signal_findings.is_empty(),
            "expected at least one PanicAddiction finding from detector, got {} total findings",
            findings.len()
        );

        // Verify at least 1 finding exists from the detector
        assert!(
            !findings.is_empty(),
            "expected at least 1 total finding, got {}",
            findings.len()
        );
    }
}