repolens 1.4.0

A CLI tool to audit and prepare repositories for open source or enterprise standards
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
//! Audit results caching module
//!
//! This module provides a caching system for audit results to avoid
//! re-auditing files that haven't changed since the last audit.
//!
//! The cache uses SHA256 content hashing to detect file changes.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::error::RepoLensError;
use crate::rules::results::Finding;

/// Default cache directory name within the project
const DEFAULT_CACHE_DIR: &str = ".repolens/cache";

/// Default maximum age for cache entries in hours
const DEFAULT_MAX_AGE_HOURS: u64 = 24;

/// Cache file name
const CACHE_FILE_NAME: &str = "audit_cache.json";

/// A single cache entry for a file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheEntry {
    /// Relative path to the file from repository root
    pub file_path: String,

    /// SHA256 hash of the file content
    pub content_hash: String,

    /// Findings for this file
    pub findings: Vec<Finding>,

    /// Timestamp when the entry was created (seconds since UNIX epoch)
    pub timestamp: u64,
}

impl CacheEntry {
    /// Create a new cache entry
    #[allow(dead_code)]
    pub fn new(file_path: String, content_hash: String, findings: Vec<Finding>) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_secs();

        Self {
            file_path,
            content_hash,
            findings,
            timestamp,
        }
    }

    /// Check if the entry is expired based on max age
    pub fn is_expired(&self, max_age_hours: u64) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_secs();

        let max_age_secs = max_age_hours * 3600;
        now.saturating_sub(self.timestamp) > max_age_secs
    }

    /// Check if the entry matches the current file hash
    #[allow(dead_code)]
    pub fn matches_hash(&self, current_hash: &str) -> bool {
        self.content_hash == current_hash
    }
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Whether caching is enabled
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Maximum age for cache entries in hours
    #[serde(default = "default_max_age_hours")]
    pub max_age_hours: u64,

    /// Cache directory path (relative to project root or absolute)
    #[serde(default = "default_directory")]
    pub directory: String,
}

fn default_enabled() -> bool {
    true
}

fn default_max_age_hours() -> u64 {
    DEFAULT_MAX_AGE_HOURS
}

fn default_directory() -> String {
    DEFAULT_CACHE_DIR.to_string()
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_age_hours: DEFAULT_MAX_AGE_HOURS,
            directory: DEFAULT_CACHE_DIR.to_string(),
        }
    }
}

/// Main audit cache structure
#[derive(Debug)]
pub struct AuditCache {
    /// Cache entries indexed by file path
    entries: HashMap<PathBuf, CacheEntry>,

    /// Path to the cache directory
    cache_dir: PathBuf,

    /// Cache configuration
    #[allow(dead_code)]
    config: CacheConfig,

    /// Whether the cache has been modified since loading
    dirty: bool,
}

impl AuditCache {
    /// Create a new audit cache with the given configuration
    ///
    /// # Arguments
    ///
    /// * `project_root` - The root directory of the project
    /// * `config` - Cache configuration
    ///
    /// # Returns
    ///
    /// A new `AuditCache` instance
    #[allow(dead_code)]
    pub fn new(project_root: &Path, config: CacheConfig) -> Self {
        let cache_dir = Self::resolve_cache_dir(project_root, &config.directory);

        Self {
            entries: HashMap::new(),
            cache_dir,
            config,
            dirty: false,
        }
    }

    /// Resolve the cache directory path
    fn resolve_cache_dir(project_root: &Path, directory: &str) -> PathBuf {
        let path = Path::new(directory);

        if path.is_absolute() {
            path.to_path_buf()
        } else if directory.starts_with("~") {
            // Handle home directory expansion
            if let Some(home) = dirs::home_dir() {
                home.join(directory.trim_start_matches("~/"))
            } else {
                project_root.join(directory)
            }
        } else {
            project_root.join(directory)
        }
    }

    /// Load cache from disk
    ///
    /// # Arguments
    ///
    /// * `project_root` - The root directory of the project
    /// * `config` - Cache configuration
    ///
    /// # Returns
    ///
    /// A loaded `AuditCache` instance, or a new empty cache if loading fails
    pub fn load(project_root: &Path, config: CacheConfig) -> Self {
        let cache_dir = Self::resolve_cache_dir(project_root, &config.directory);
        let cache_file = cache_dir.join(CACHE_FILE_NAME);

        let entries = if cache_file.exists() {
            match fs::read_to_string(&cache_file) {
                Ok(content) => match serde_json::from_str::<Vec<CacheEntry>>(&content) {
                    Ok(entries) => {
                        let mut map = HashMap::new();
                        for entry in entries {
                            // Skip expired entries during load
                            if !entry.is_expired(config.max_age_hours) {
                                map.insert(PathBuf::from(&entry.file_path), entry);
                            }
                        }
                        tracing::debug!(
                            "Loaded {} cache entries from {}",
                            map.len(),
                            cache_file.display()
                        );
                        map
                    }
                    Err(e) => {
                        tracing::warn!("Failed to parse cache file: {}", e);
                        HashMap::new()
                    }
                },
                Err(e) => {
                    tracing::debug!("Failed to read cache file: {}", e);
                    HashMap::new()
                }
            }
        } else {
            tracing::debug!("No cache file found at {}", cache_file.display());
            HashMap::new()
        };

        Self {
            entries,
            cache_dir,
            config,
            dirty: false,
        }
    }

    /// Save cache to disk
    ///
    /// # Returns
    ///
    /// `Ok(())` if the cache was saved successfully, or an error if it failed
    pub fn save(&self) -> Result<(), RepoLensError> {
        if !self.dirty {
            tracing::debug!("Cache not modified, skipping save");
            return Ok(());
        }

        // Create cache directory if it doesn't exist
        fs::create_dir_all(&self.cache_dir).map_err(|e| {
            RepoLensError::Action(crate::error::ActionError::DirectoryCreate {
                path: self.cache_dir.display().to_string(),
                source: e,
            })
        })?;

        let cache_file = self.cache_dir.join(CACHE_FILE_NAME);
        let entries: Vec<&CacheEntry> = self.entries.values().collect();
        let content = serde_json::to_string_pretty(&entries)?;

        fs::write(&cache_file, content).map_err(|e| {
            RepoLensError::Action(crate::error::ActionError::FileWrite {
                path: cache_file.display().to_string(),
                source: e,
            })
        })?;

        tracing::debug!(
            "Saved {} cache entries to {}",
            entries.len(),
            cache_file.display()
        );

        Ok(())
    }

    /// Get cached findings for a file if the cache entry is valid
    ///
    /// # Arguments
    ///
    /// * `file_path` - Relative path to the file
    /// * `current_hash` - Current SHA256 hash of the file content
    ///
    /// # Returns
    ///
    /// `Some(&Vec<Finding>)` if a valid cache entry exists, `None` otherwise
    #[allow(dead_code)]
    pub fn get(&self, file_path: &Path, current_hash: &str) -> Option<&Vec<Finding>> {
        self.entries.get(file_path).and_then(|entry| {
            if entry.matches_hash(current_hash) && !entry.is_expired(self.config.max_age_hours) {
                tracing::trace!("Cache hit for {}", file_path.display());
                Some(&entry.findings)
            } else {
                tracing::trace!("Cache miss for {} (hash or expiry)", file_path.display());
                None
            }
        })
    }

    /// Insert or update a cache entry
    ///
    /// # Arguments
    ///
    /// * `file_path` - Relative path to the file
    /// * `hash` - SHA256 hash of the file content
    /// * `findings` - Findings for this file
    #[allow(dead_code)]
    pub fn insert(&mut self, file_path: PathBuf, hash: String, findings: Vec<Finding>) {
        let entry = CacheEntry::new(file_path.to_string_lossy().to_string(), hash, findings);
        self.entries.insert(file_path, entry);
        self.dirty = true;
    }

    /// Invalidate cache entry for a specific file
    ///
    /// # Arguments
    ///
    /// * `file_path` - Relative path to the file
    #[allow(dead_code)]
    pub fn invalidate(&mut self, file_path: &Path) {
        if self.entries.remove(file_path).is_some() {
            self.dirty = true;
            tracing::debug!("Invalidated cache for {}", file_path.display());
        }
    }

    /// Clear all cache entries
    #[allow(dead_code)]
    pub fn clear(&mut self) {
        if !self.entries.is_empty() {
            self.entries.clear();
            self.dirty = true;
            tracing::info!("Cleared all cache entries");
        }
    }

    /// Get the number of cached entries
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if the cache is empty
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            total_entries: self.entries.len(),
            cache_dir: self.cache_dir.clone(),
        }
    }

    /// Check if caching is enabled
    #[allow(dead_code)]
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }
}

/// Cache statistics
#[derive(Debug)]
pub struct CacheStats {
    /// Total number of cache entries
    pub total_entries: usize,
    /// Cache directory path
    #[allow(dead_code)]
    pub cache_dir: PathBuf,
}

/// Calculate SHA256 hash of a file's content
///
/// # Arguments
///
/// * `path` - Path to the file
///
/// # Returns
///
/// The SHA256 hash as a hexadecimal string
#[allow(dead_code)]
pub fn calculate_file_hash(path: &Path) -> io::Result<String> {
    let mut file = fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];

    loop {
        let bytes_read = file.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        hasher.update(&buffer[..bytes_read]);
    }

    Ok(format!("{:x}", hasher.finalize()))
}

/// Calculate SHA256 hash of content bytes
///
/// # Arguments
///
/// * `content` - The content to hash
///
/// # Returns
///
/// The SHA256 hash as a hexadecimal string
#[allow(dead_code)]
pub fn calculate_content_hash(content: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content);
    format!("{:x}", hasher.finalize())
}

/// Delete the cache directory and all its contents
///
/// # Arguments
///
/// * `project_root` - The root directory of the project
/// * `config` - Cache configuration
///
/// # Returns
///
/// `Ok(())` if the cache was cleared successfully
pub fn delete_cache_directory(project_root: &Path, config: &CacheConfig) -> io::Result<()> {
    let cache_dir = AuditCache::resolve_cache_dir(project_root, &config.directory);

    if cache_dir.exists() {
        fs::remove_dir_all(&cache_dir)?;
        tracing::info!("Deleted cache directory: {}", cache_dir.display());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rules::results::Severity;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_finding(rule_id: &str, location: Option<&str>) -> Finding {
        let mut finding = Finding::new(rule_id, "test", Severity::Warning, "Test finding");
        if let Some(loc) = location {
            finding = finding.with_location(loc);
        }
        finding
    }

    #[test]
    fn test_cache_entry_creation() {
        let entry = CacheEntry::new(
            "test.rs".to_string(),
            "abc123".to_string(),
            vec![create_test_finding("TEST001", Some("test.rs:1"))],
        );

        assert_eq!(entry.file_path, "test.rs");
        assert_eq!(entry.content_hash, "abc123");
        assert_eq!(entry.findings.len(), 1);
        assert!(entry.timestamp > 0);
    }

    #[test]
    fn test_cache_entry_expiry() {
        let mut entry = CacheEntry::new("test.rs".to_string(), "abc123".to_string(), vec![]);

        // Fresh entry should not be expired
        assert!(!entry.is_expired(24));

        // Set timestamp to 25 hours ago
        entry.timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - (25 * 3600);

        // Should now be expired with 24-hour max age
        assert!(entry.is_expired(24));

        // But not with 48-hour max age
        assert!(!entry.is_expired(48));
    }

    #[test]
    fn test_cache_entry_hash_matching() {
        let entry = CacheEntry::new("test.rs".to_string(), "abc123".to_string(), vec![]);

        assert!(entry.matches_hash("abc123"));
        assert!(!entry.matches_hash("def456"));
    }

    #[test]
    fn test_audit_cache_new() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let cache = AuditCache::new(temp_dir.path(), config);

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert!(cache.is_enabled());
    }

    #[test]
    fn test_audit_cache_insert_and_get() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        let findings = vec![create_test_finding("TEST001", Some("test.rs:1"))];
        cache.insert(
            PathBuf::from("test.rs"),
            "abc123".to_string(),
            findings.clone(),
        );

        // Cache hit with matching hash
        let result = cache.get(Path::new("test.rs"), "abc123");
        assert!(result.is_some());
        assert_eq!(result.unwrap().len(), 1);

        // Cache miss with different hash
        let result = cache.get(Path::new("test.rs"), "def456");
        assert!(result.is_none());

        // Cache miss for non-existent file
        let result = cache.get(Path::new("other.rs"), "abc123");
        assert!(result.is_none());
    }

    #[test]
    fn test_audit_cache_invalidate() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        cache.insert(PathBuf::from("test.rs"), "abc123".to_string(), vec![]);
        assert_eq!(cache.len(), 1);

        cache.invalidate(Path::new("test.rs"));
        assert!(cache.is_empty());
    }

    #[test]
    fn test_audit_cache_clear() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        cache.insert(PathBuf::from("test1.rs"), "abc123".to_string(), vec![]);
        cache.insert(PathBuf::from("test2.rs"), "def456".to_string(), vec![]);
        assert_eq!(cache.len(), 2);

        cache.clear();
        assert!(cache.is_empty());
    }

    #[test]
    fn test_audit_cache_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();

        // Create and populate cache
        let mut cache = AuditCache::new(temp_dir.path(), config.clone());
        let findings = vec![create_test_finding("TEST001", Some("test.rs:1"))];
        cache.insert(
            PathBuf::from("test.rs"),
            "abc123".to_string(),
            findings.clone(),
        );

        // Save cache
        cache.save().unwrap();

        // Load cache in a new instance
        let loaded_cache = AuditCache::load(temp_dir.path(), config);
        assert_eq!(loaded_cache.len(), 1);

        let result = loaded_cache.get(Path::new("test.rs"), "abc123");
        assert!(result.is_some());
        assert_eq!(result.unwrap().len(), 1);
    }

    #[test]
    fn test_calculate_file_hash() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");

        fs::write(&file_path, "Hello, World!").unwrap();

        let hash = calculate_file_hash(&file_path).unwrap();

        // Verify hash is a valid SHA256 hex string
        assert_eq!(hash.len(), 64);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_calculate_content_hash() {
        let hash = calculate_content_hash(b"Hello, World!");

        // Should produce the same hash for the same content
        let hash2 = calculate_content_hash(b"Hello, World!");
        assert_eq!(hash, hash2);

        // Different content should produce different hash
        let hash3 = calculate_content_hash(b"Different content");
        assert_ne!(hash, hash3);
    }

    #[test]
    fn test_delete_cache_directory() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();

        // Create cache and save it
        let mut cache = AuditCache::new(temp_dir.path(), config.clone());
        cache.insert(PathBuf::from("test.rs"), "abc123".to_string(), vec![]);
        cache.save().unwrap();

        // Verify cache directory exists
        let cache_dir = temp_dir.path().join(".repolens/cache");
        assert!(cache_dir.exists());

        // Delete cache directory
        delete_cache_directory(temp_dir.path(), &config).unwrap();
        assert!(!cache_dir.exists());
    }

    #[test]
    fn test_cache_config_defaults() {
        let config = CacheConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_age_hours, 24);
        assert_eq!(config.directory, ".repolens/cache");
    }

    #[test]
    fn test_cache_stats() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        cache.insert(PathBuf::from("test1.rs"), "abc123".to_string(), vec![]);
        cache.insert(PathBuf::from("test2.rs"), "def456".to_string(), vec![]);

        let stats = cache.stats();
        assert_eq!(stats.total_entries, 2);
    }

    #[test]
    fn test_cache_save_not_dirty() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let cache = AuditCache::new(temp_dir.path(), config);

        // Save when not dirty should be a no-op
        let result = cache.save();
        assert!(result.is_ok());

        // Cache file should not exist
        let cache_file = temp_dir.path().join(".repolens/cache/audit_cache.json");
        assert!(!cache_file.exists());
    }

    #[test]
    fn test_cache_load_invalid_json() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join(".repolens/cache");
        fs::create_dir_all(&cache_dir).unwrap();
        fs::write(cache_dir.join("audit_cache.json"), "invalid json content").unwrap();

        let config = CacheConfig::default();
        let cache = AuditCache::load(temp_dir.path(), config);

        // Should load empty cache on parse error
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_load_expired_entries_filtered() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join(".repolens/cache");
        fs::create_dir_all(&cache_dir).unwrap();

        // Create a cache entry with very old timestamp
        let old_entry = CacheEntry {
            file_path: "old.rs".to_string(),
            content_hash: "abc".to_string(),
            findings: vec![],
            timestamp: 1000, // Very old timestamp
        };
        let content = serde_json::to_string_pretty(&vec![old_entry]).unwrap();
        fs::write(cache_dir.join("audit_cache.json"), content).unwrap();

        let config = CacheConfig {
            max_age_hours: 1, // 1 hour
            ..Default::default()
        };
        let cache = AuditCache::load(temp_dir.path(), config);

        // Expired entry should be filtered out
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_load_nonexistent_directory() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig {
            directory: "nonexistent/path".to_string(),
            ..Default::default()
        };
        let cache = AuditCache::load(temp_dir.path(), config);

        // Should load empty cache when directory doesn't exist
        assert!(cache.is_empty());
    }

    #[test]
    fn test_resolve_cache_dir_absolute() {
        let config_dir = "/tmp/test-cache";
        let resolved = AuditCache::resolve_cache_dir(Path::new("/project"), config_dir);
        assert_eq!(resolved, PathBuf::from("/tmp/test-cache"));
    }

    #[test]
    fn test_resolve_cache_dir_home() {
        let resolved = AuditCache::resolve_cache_dir(Path::new("/project"), "~/.cache/repolens");
        // Should expand home directory
        assert!(!resolved.starts_with("~"));
    }

    #[test]
    fn test_cache_is_enabled_false() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig {
            enabled: false,
            ..Default::default()
        };
        let cache = AuditCache::new(temp_dir.path(), config);
        assert!(!cache.is_enabled());
    }

    #[test]
    fn test_cache_clear_empty() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        // Clear on empty cache should be no-op
        cache.clear();
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_invalidate_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        // Invalidating non-existent entry should be no-op
        cache.invalidate(Path::new("nonexistent.rs"));
        assert!(cache.is_empty());
    }

    #[test]
    fn test_delete_cache_directory_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();

        // Deleting non-existent cache should succeed
        let result = delete_cache_directory(temp_dir.path(), &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_cache_get_wrong_hash() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        cache.insert(PathBuf::from("test.rs"), "abc123".to_string(), vec![]);

        // Should return None because hash doesn't match
        assert!(cache.get(Path::new("test.rs"), "different_hash").is_none());
    }

    #[test]
    fn test_cache_save_dirty() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config);

        cache.insert(PathBuf::from("test.rs"), "abc123".to_string(), vec![]);

        // Should save when dirty
        let result = cache.save();
        assert!(result.is_ok());

        // Cache file should exist
        let cache_file = temp_dir.path().join(".repolens/cache/audit_cache.json");
        assert!(cache_file.exists());
    }

    #[test]
    fn test_cache_save_and_load_roundtrip() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let mut cache = AuditCache::new(temp_dir.path(), config.clone());

        let finding = create_test_finding("TEST001", Some("test.rs:1"));
        cache.insert(
            PathBuf::from("test.rs"),
            "abc123".to_string(),
            vec![finding],
        );

        cache.save().unwrap();

        // Load and verify
        let loaded = AuditCache::load(temp_dir.path(), config);
        assert!(!loaded.is_empty());
        assert!(loaded.get(Path::new("test.rs"), "abc123").is_some());
    }

    #[test]
    fn test_cache_delete_existing_directory() {
        let temp_dir = TempDir::new().unwrap();
        let config = CacheConfig::default();
        let cache_dir = temp_dir.path().join(".repolens/cache");
        fs::create_dir_all(&cache_dir).unwrap();
        fs::write(cache_dir.join("audit_cache.json"), "[]").unwrap();

        let result = delete_cache_directory(temp_dir.path(), &config);
        assert!(result.is_ok());
        assert!(!cache_dir.exists());
    }

    #[test]
    fn test_cache_entry_matches_hash() {
        let entry = CacheEntry::new("test.rs".to_string(), "abc123".to_string(), vec![]);
        assert!(entry.matches_hash("abc123"));
        assert!(!entry.matches_hash("other"));
    }
}