scribe-scanner 0.5.1

High-performance file system scanning and indexing for Scribe
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
//! Core scanning functionality for efficient file system traversal.
//!
//! This module provides the main Scanner implementation with support for
//! parallel processing, git integration, and advanced filtering.

use crate::{GitIntegrator, LanguageDetector, MetadataExtractor};
use scribe_core::{
    FileInfo, GitFileStatus, GitStatus, Language, RenderDecision, Result, ScribeError,
};

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Instant;

use futures::stream::{self, StreamExt};
use ignore::{DirEntry as IgnoreDirEntry, WalkBuilder, WalkState};
use rayon::prelude::*;
use tokio::sync::{RwLock, Semaphore};
use walkdir::{DirEntry, WalkDir};

/// High-performance file system scanner with parallel processing
#[derive(Debug)]
pub struct Scanner {
    stats: Arc<ScannerStats>,
    semaphore: Arc<Semaphore>,
}

/// Internal statistics tracking for the scanner
#[derive(Debug, Default)]
pub struct ScannerStats {
    files_processed: AtomicUsize,
    directories_traversed: AtomicUsize,
    binary_files_skipped: AtomicUsize,
    errors_encountered: AtomicUsize,
}

/// Configuration options for scanning operations
#[derive(Debug, Clone)]
pub struct ScanOptions {
    /// Enable parallel processing using Rayon
    pub parallel_processing: bool,
    /// Maximum number of concurrent file operations
    pub max_concurrency: usize,
    /// Extract detailed file metadata
    pub metadata_extraction: bool,
    /// Use git integration when available
    pub git_integration: bool,
    /// Follow symbolic links
    pub follow_symlinks: bool,
    /// Include hidden files and directories
    pub include_hidden: bool,
    /// Maximum file size to process (bytes)
    pub max_file_size: Option<u64>,
    /// Custom file extensions to include
    pub include_extensions: Option<Vec<String>>,
    /// Custom file extensions to exclude
    pub exclude_extensions: Option<Vec<String>>,
}

/// Result of a scanning operation
#[derive(Debug, Clone)]
pub struct ScanResult {
    pub files: Vec<FileInfo>,
    pub stats: ScanProgress,
    pub duration: std::time::Duration,
    pub errors: Vec<String>,
}

/// Progress information during scanning
#[derive(Debug, Clone)]
pub struct ScanProgress {
    pub files_processed: usize,
    pub directories_traversed: usize,
    pub binary_files_skipped: usize,
    pub errors_encountered: usize,
    pub bytes_processed: u64,
}

impl Default for ScanOptions {
    fn default() -> Self {
        Self {
            parallel_processing: true,
            max_concurrency: num_cpus::get().min(16), // Cap at 16 for memory efficiency
            metadata_extraction: true,
            git_integration: false,
            follow_symlinks: false,
            include_hidden: false,
            max_file_size: Some(50 * 1024 * 1024), // 50MB
            include_extensions: None,
            exclude_extensions: None,
        }
    }
}

impl ScanOptions {
    /// Enable parallel processing
    pub fn with_parallel_processing(mut self, enabled: bool) -> Self {
        self.parallel_processing = enabled;
        self
    }

    /// Set maximum concurrency level
    pub fn with_max_concurrency(mut self, max: usize) -> Self {
        self.max_concurrency = max;
        self
    }

    /// Enable metadata extraction
    pub fn with_metadata_extraction(mut self, enabled: bool) -> Self {
        self.metadata_extraction = enabled;
        self
    }

    /// Enable git integration
    pub fn with_git_integration(mut self, enabled: bool) -> Self {
        self.git_integration = enabled;
        self
    }

    /// Follow symbolic links
    pub fn with_follow_symlinks(mut self, enabled: bool) -> Self {
        self.follow_symlinks = enabled;
        self
    }

    /// Include hidden files
    pub fn with_include_hidden(mut self, enabled: bool) -> Self {
        self.include_hidden = enabled;
        self
    }

    /// Set maximum file size limit
    pub fn with_max_file_size(mut self, size: Option<u64>) -> Self {
        self.max_file_size = size;
        self
    }

    /// Set extensions to include
    pub fn with_include_extensions(mut self, extensions: Vec<String>) -> Self {
        self.include_extensions = Some(extensions);
        self
    }

    /// Set extensions to exclude
    pub fn with_exclude_extensions(mut self, extensions: Vec<String>) -> Self {
        self.exclude_extensions = Some(extensions);
        self
    }
}

impl Scanner {
    /// Create a new scanner with default configuration
    pub fn new() -> Self {
        Self {
            stats: Arc::new(ScannerStats::default()),
            semaphore: Arc::new(Semaphore::new(16)), // Default concurrency limit
        }
    }

    /// Scan a directory with the given options
    pub async fn scan<P: AsRef<Path>>(
        &self,
        path: P,
        options: ScanOptions,
    ) -> Result<Vec<FileInfo>> {
        let start_time = Instant::now();
        let path = path.as_ref();

        // Validate input path
        if !path.exists() {
            return Err(ScribeError::path(
                format!("Path does not exist: {}", path.display()),
                path,
            ));
        }

        if !path.is_dir() {
            return Err(ScribeError::path(
                format!("Path is not a directory: {}", path.display()),
                path,
            ));
        }

        // Initialize components
        let metadata_extractor = if options.metadata_extraction {
            Some(MetadataExtractor::new())
        } else {
            None
        };

        let git_integrator = if options.git_integration {
            GitIntegrator::new(path).ok()
        } else {
            None
        };

        let language_detector = LanguageDetector::new();

        // Try git-based discovery first if enabled
        let file_paths = if let Some(ref git) = git_integrator {
            match git.list_tracked_files().await {
                Ok(paths) => {
                    log::debug!(
                        "Using git ls-files for file discovery: {} files",
                        paths.len()
                    );
                    paths
                }
                Err(_) => {
                    log::debug!("Git discovery failed, falling back to filesystem walk");
                    self.discover_files_filesystem(path, &options).await?
                }
            }
        } else {
            self.discover_files_filesystem(path, &options).await?
        };

        log::info!("Discovered {} files for processing", file_paths.len());

        // Load batch git status for performance if git integration is enabled
        if let Some(ref git) = git_integrator {
            if let Err(e) = git.load_batch_file_statuses().await {
                log::debug!("Failed to load batch git statuses: {}", e);
            }
        }

        // Process files with appropriate strategy
        let files = if options.parallel_processing {
            log::debug!(
                "Processing files in parallel with concurrency={}",
                options.max_concurrency
            );
            self.process_files_parallel(
                file_paths,
                &options,
                metadata_extractor.as_ref(),
                git_integrator.as_ref(),
                &language_detector,
            )
            .await?
        } else {
            log::debug!("Processing files sequentially");
            self.process_files_sequential(
                file_paths,
                &options,
                metadata_extractor.as_ref(),
                git_integrator.as_ref(),
                &language_detector,
            )
            .await?
        };

        log::info!(
            "Scanning completed in {:.2}s: {} files processed",
            start_time.elapsed().as_secs_f64(),
            files.len()
        );

        Ok(files)
    }

    /// Discover files using filesystem traversal with ignore patterns
    async fn discover_files_filesystem(
        &self,
        root: &Path,
        options: &ScanOptions,
    ) -> Result<Vec<PathBuf>> {
        let mut builder = WalkBuilder::new(root);

        builder
            .follow_links(options.follow_symlinks)
            .hidden(!options.include_hidden)
            .git_ignore(true)
            .git_exclude(true)
            .require_git(false);

        let mut files = Vec::new();

        // Use the ignore crate for efficient traversal with gitignore support
        builder.build().for_each(|entry| {
            match entry {
                Ok(entry) => {
                    if entry.file_type().map_or(false, |ft| ft.is_file()) {
                        let path = entry.path().to_path_buf();

                        // Apply extension filters
                        if self.should_include_file(&path, options) {
                            files.push(path);
                        }
                    }

                    if entry.file_type().map_or(false, |ft| ft.is_dir()) {
                        self.stats
                            .directories_traversed
                            .fetch_add(1, Ordering::Relaxed);
                    }
                }
                Err(err) => {
                    log::warn!("Error during filesystem traversal: {}", err);
                    self.stats
                        .errors_encountered
                        .fetch_add(1, Ordering::Relaxed);
                }
            }
            // Continue walking
        });

        Ok(files)
    }

    /// Process files in parallel using Rayon
    async fn process_files_parallel(
        &self,
        file_paths: Vec<PathBuf>,
        options: &ScanOptions,
        metadata_extractor: Option<&MetadataExtractor>,
        git_integrator: Option<&GitIntegrator>,
        language_detector: &LanguageDetector,
    ) -> Result<Vec<FileInfo>> {
        let semaphore = Arc::new(Semaphore::new(options.max_concurrency));
        let results = Arc::new(RwLock::new(Vec::new()));

        // Process files in chunks to manage memory usage
        let chunk_size = 1000;
        for chunk in file_paths.chunks(chunk_size) {
            let futures: Vec<_> = chunk
                .iter()
                .map(|path| {
                    let semaphore = Arc::clone(&semaphore);
                    let results = Arc::clone(&results);
                    let path = path.clone();

                    async move {
                        let _permit = semaphore.acquire().await.unwrap();

                        match self
                            .process_single_file(
                                &path,
                                options,
                                metadata_extractor,
                                git_integrator,
                                language_detector,
                            )
                            .await
                        {
                            Ok(Some(file_info)) => {
                                results.write().await.push(file_info);
                            }
                            Ok(None) => {
                                // File was filtered out or is binary
                            }
                            Err(err) => {
                                log::debug!("Error processing file {}: {}", path.display(), err);
                                self.stats
                                    .errors_encountered
                                    .fetch_add(1, Ordering::Relaxed);
                            }
                        }
                    }
                })
                .collect();

            // Process chunk concurrently
            stream::iter(futures)
                .buffer_unordered(options.max_concurrency)
                .collect::<Vec<_>>()
                .await;
        }

        let results = results.read().await;
        Ok(results.clone())
    }

    /// Process files sequentially
    async fn process_files_sequential(
        &self,
        file_paths: Vec<PathBuf>,
        options: &ScanOptions,
        metadata_extractor: Option<&MetadataExtractor>,
        git_integrator: Option<&GitIntegrator>,
        language_detector: &LanguageDetector,
    ) -> Result<Vec<FileInfo>> {
        let mut results = Vec::new();

        for path in file_paths {
            match self
                .process_single_file(
                    &path,
                    options,
                    metadata_extractor,
                    git_integrator,
                    language_detector,
                )
                .await
            {
                Ok(Some(file_info)) => {
                    results.push(file_info);
                }
                Ok(None) => {
                    // File was filtered out or is binary
                }
                Err(err) => {
                    log::debug!("Error processing file {}: {}", path.display(), err);
                    self.stats
                        .errors_encountered
                        .fetch_add(1, Ordering::Relaxed);
                }
            }
        }

        Ok(results)
    }

    /// Process a single file and extract its information
    async fn process_single_file(
        &self,
        path: &Path,
        options: &ScanOptions,
        metadata_extractor: Option<&MetadataExtractor>,
        git_integrator: Option<&GitIntegrator>,
        language_detector: &LanguageDetector,
    ) -> Result<Option<FileInfo>> {
        // Basic file validation
        if !path.exists() {
            return Ok(None);
        }

        let metadata = tokio::fs::metadata(path).await?;

        // Skip if file is too large
        if let Some(max_size) = options.max_file_size {
            if metadata.len() > max_size {
                log::debug!(
                    "Skipping large file: {} ({} bytes)",
                    path.display(),
                    metadata.len()
                );
                return Ok(None);
            }
        }

        // Basic language detection
        let language = language_detector.detect_language(path);

        // Skip binary files unless specifically included
        if self.is_likely_binary(path, &language) {
            self.stats
                .binary_files_skipped
                .fetch_add(1, Ordering::Relaxed);
            return Ok(None);
        }

        // Create base FileInfo
        let relative_path = path.to_string_lossy().to_string();

        let file_type = FileInfo::classify_file_type(
            &relative_path,
            &language,
            path.extension().and_then(|e| e.to_str()).unwrap_or(""),
        );

        let mut file_info = FileInfo {
            path: path.to_path_buf(),
            relative_path,
            size: metadata.len(),
            modified: metadata.modified().ok(),
            decision: RenderDecision::include("scanned file"),
            file_type,
            language,
            content: None,
            token_estimate: None,
            line_count: None,
            char_count: None,
            is_binary: false, // Will be determined by binary detection
            git_status: None,
            centrality_score: None, // Will be calculated during analysis phase
        };

        // Extract metadata if requested
        if let Some(extractor) = metadata_extractor {
            if let Ok(file_metadata) = extractor.extract_metadata(path).await {
                file_info.size = file_metadata.size;
                // Copy over other metadata fields as needed
            }
        }

        // Get git information if available
        if let Some(git) = git_integrator {
            if let Ok(git_info) = git.get_file_info(path).await {
                // Add git status and commit info
                file_info.git_status = Some(GitStatus {
                    working_tree: git_info.status,
                    index: GitFileStatus::Unmodified,
                });
            }
        }

        self.stats.files_processed.fetch_add(1, Ordering::Relaxed);
        Ok(Some(file_info))
    }

    /// Check if a file should be included based on extension filters
    fn should_include_file(&self, path: &Path, options: &ScanOptions) -> bool {
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("")
            .to_lowercase();

        // Check exclusion list first
        if let Some(ref exclude) = options.exclude_extensions {
            if exclude.iter().any(|ext| ext.to_lowercase() == extension) {
                return false;
            }
        }

        // Check inclusion list if specified
        if let Some(ref include) = options.include_extensions {
            return include.iter().any(|ext| ext.to_lowercase() == extension);
        }

        true
    }

    /// Binary file detection backed by libmagic-style signatures with sensible fallbacks.
    fn is_likely_binary(&self, path: &Path, _language: &Language) -> bool {
        let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("");
        FileInfo::detect_binary_with_hint(path, extension)
    }

    /// Get current processing statistics
    pub fn files_processed(&self) -> usize {
        self.stats.files_processed.load(Ordering::Relaxed)
    }

    /// Get number of directories traversed
    pub fn directories_traversed(&self) -> usize {
        self.stats.directories_traversed.load(Ordering::Relaxed)
    }

    /// Get number of binary files skipped
    pub fn binary_files_skipped(&self) -> usize {
        self.stats.binary_files_skipped.load(Ordering::Relaxed)
    }

    /// Get number of errors encountered
    pub fn errors_encountered(&self) -> usize {
        self.stats.errors_encountered.load(Ordering::Relaxed)
    }
}

impl Default for Scanner {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;
    use tokio::fs as async_fs;

    #[tokio::test]
    async fn test_scanner_creation() {
        let scanner = Scanner::new();
        assert_eq!(scanner.files_processed(), 0);
        assert_eq!(scanner.directories_traversed(), 0);
    }

    #[tokio::test]
    async fn test_scan_empty_directory() {
        let scanner = Scanner::new();
        let temp_dir = TempDir::new().unwrap();

        let options = ScanOptions::default();
        let results = scanner.scan(temp_dir.path(), options).await.unwrap();

        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn test_scan_with_files() {
        let scanner = Scanner::new();
        let temp_dir = TempDir::new().unwrap();

        // Create test files
        let rust_file = temp_dir.path().join("test.rs");
        let python_file = temp_dir.path().join("test.py");
        let binary_file = temp_dir.path().join("test.bin");

        fs::write(&rust_file, "fn main() { println!(\"Hello, world!\"); }").unwrap();
        fs::write(&python_file, "print('Hello, world!')").unwrap();
        fs::write(&binary_file, &[0u8; 256]).unwrap(); // Binary content

        let options = ScanOptions::default();
        let results = scanner.scan(temp_dir.path(), options).await.unwrap();

        // Should find the text files but skip the binary
        assert_eq!(results.len(), 2);
        assert!(results
            .iter()
            .any(|f| f.path.file_name().unwrap() == "test.rs"));
        assert!(results
            .iter()
            .any(|f| f.path.file_name().unwrap() == "test.py"));

        // Check language detection
        let rust_file_info = results
            .iter()
            .find(|f| f.path.file_name().unwrap() == "test.rs")
            .unwrap();
        assert_eq!(rust_file_info.language, Language::Rust);

        let python_file_info = results
            .iter()
            .find(|f| f.path.file_name().unwrap() == "test.py")
            .unwrap();
        assert_eq!(python_file_info.language, Language::Python);
    }

    #[tokio::test]
    async fn test_scan_options_extension_filtering() {
        let scanner = Scanner::new();
        let temp_dir = TempDir::new().unwrap();

        // Create test files with different extensions
        fs::write(temp_dir.path().join("test.rs"), "fn main() {}").unwrap();
        fs::write(temp_dir.path().join("test.py"), "print('hello')").unwrap();
        fs::write(temp_dir.path().join("test.js"), "console.log('hello')").unwrap();

        // Test include filter
        let options = ScanOptions::default()
            .with_include_extensions(vec!["rs".to_string(), "py".to_string()]);
        let results = scanner.scan(temp_dir.path(), options).await.unwrap();

        assert_eq!(results.len(), 2);
        assert!(results.iter().any(|f| f.path.extension().unwrap() == "rs"));
        assert!(results.iter().any(|f| f.path.extension().unwrap() == "py"));
        assert!(!results.iter().any(|f| f.path.extension().unwrap() == "js"));
    }

    #[tokio::test]
    async fn test_parallel_processing() {
        let scanner = Scanner::new();
        let temp_dir = TempDir::new().unwrap();

        // Create multiple test files to trigger parallel processing
        for i in 0..150 {
            let file_path = temp_dir.path().join(format!("test_{}.rs", i));
            fs::write(&file_path, format!("fn main_{i}() {{}}")).unwrap();
        }

        let options = ScanOptions::default()
            .with_parallel_processing(true)
            .with_max_concurrency(4);

        let start = Instant::now();
        let results = scanner.scan(temp_dir.path(), options).await.unwrap();
        let duration = start.elapsed();

        assert_eq!(results.len(), 150);
        log::info!("Parallel scan of 150 files took: {:?}", duration);

        // Verify all files were processed correctly
        for i in 0..150 {
            assert!(results
                .iter()
                .any(|f| { f.path.file_name().unwrap() == format!("test_{}.rs", i).as_str() }));
        }
    }

    #[test]
    fn test_scan_options_builder() {
        let options = ScanOptions::default()
            .with_parallel_processing(true)
            .with_max_concurrency(8)
            .with_metadata_extraction(true)
            .with_git_integration(false)
            .with_follow_symlinks(false)
            .with_include_hidden(true)
            .with_max_file_size(Some(1024 * 1024));

        assert_eq!(options.parallel_processing, true);
        assert_eq!(options.max_concurrency, 8);
        assert_eq!(options.metadata_extraction, true);
        assert_eq!(options.git_integration, false);
        assert_eq!(options.follow_symlinks, false);
        assert_eq!(options.include_hidden, true);
        assert_eq!(options.max_file_size, Some(1024 * 1024));
    }

    #[test]
    fn test_binary_file_detection() {
        let scanner = Scanner::new();
        let temp_dir = tempfile::TempDir::new().unwrap();

        let text_path = temp_dir.path().join("test.rs");
        std::fs::write(&text_path, "fn main() {}\n").unwrap();

        let binary_path = temp_dir.path().join("image.png");
        std::fs::write(&binary_path, &[0u8, 159, 146, 150, 0, 1]).unwrap();

        assert!(scanner.is_likely_binary(&binary_path, &Language::Unknown));
        assert!(!scanner.is_likely_binary(&text_path, &Language::Rust));
    }
}