perg 0.8.0

A fast, feature-rich text search tool similar to grep, written in Rust
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
use crate::error::{PergError, Result};
use console::style;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader, Write, stdin};
use std::path::Path;
use walkdir::WalkDir;

/// Helper function to determine if we should use colors
fn use_colors(color_option: &str) -> bool {
    match color_option {
        "always" => true,
        "never" => false,
        "auto" => console::colors_enabled(),
        _ => console::colors_enabled(),
    }
}

/// Helper function to colorize matches in a line
fn colorize_matches(line: &str, regex: &Regex, color_option: &str) -> String {
    if !use_colors(color_option) {
        return line.to_string();
    }
    
    // Use the regex to find all matches and replace them with colored versions
    regex.replace_all(line, |caps: &regex::Captures| {
        style(&caps[0]).red().bold().to_string()
    }).to_string()
}

/// Search configuration
#[derive(Debug, Clone)]
pub struct SearchConfig {
    pub pattern: String,
    pub ignore_case: bool,
    pub line_number: bool,
    pub with_filename: bool,
    pub invert_match: bool,
    pub files_with_matches: bool,
    pub files_without_match: bool,
    pub count: bool,
    pub before_context: usize,
    pub after_context: usize,
    pub context: usize,
    pub max_count: Option<usize>,
    pub only_matching: bool,
    pub extended_regexp: bool,
    pub color: String,
}

impl SearchConfig {
    pub fn new(
        pattern: String,
        ignore_case: bool,
        line_number: bool,
        with_filename: bool,
        invert_match: bool,
        files_with_matches: bool,
        files_without_match: bool,
        count: bool,
        before_context: usize,
        after_context: usize,
        context: usize,
        max_count: Option<usize>,
        only_matching: bool,
        extended_regexp: bool,
        color: String,
    ) -> Self {
        Self {
            pattern,
            ignore_case,
            line_number,
            with_filename,
            invert_match,
            files_with_matches,
            files_without_match,
            count,
            before_context,
            after_context,
            context,
            max_count,
            only_matching,
            extended_regexp,
            color,
        }
    }
}

/// Search result for a single match
#[derive(Debug)]
pub struct MatchResult {
    pub file_path: String,
    pub line_number: usize,
    pub line_content: String,
}

/// Search for pattern in a single file
pub fn search_file(
    config: &SearchConfig,
    file_path: &str,
    writer: &mut impl Write,
) -> Result<bool> {
    let path = Path::new(file_path);

    // Handle directory case for files_with_matches/files_without_match
    if path.is_dir() && (config.files_with_matches || config.files_without_match) {
        // For directories in these modes, we consider them as having no matches
        // since directories themselves don't contain searchable text
        if config.files_without_match {
            writeln!(writer, "{}", file_path)?;
            return Ok(false);
        }
        return Ok(false);
    }

    let file = File::open(path).map_err(|_| PergError::FileNotFound(file_path.to_string()))?;
    let reader = BufReader::new(file);

    let pattern = if config.ignore_case {
        format!("(?i){}", config.pattern)
    } else {
        config.pattern.clone()
    };

    let regex = Regex::new(&pattern)?;

    let mut has_matches = false;
    let mut match_count = 0;
    let mut _line_number = 0;
    let mut lines: Vec<String> = Vec::new();
    let mut matching_line_indices = Vec::new();
    
    // Read all lines to enable context functionality
    for line in reader.lines() {
        lines.push(line?);
        _line_number += 1;
    }

    // Use context: if -C is specified, it overrides -A and -B
    let before_context = if config.context > 0 { config.context } else { config.before_context };
    let after_context = if config.context > 0 { config.context } else { config.after_context };

    // First pass: find all matching lines
    for (idx, line) in lines.iter().enumerate() {
        let matches = regex.is_match(line);

        // Apply invert match logic
        let should_include = if config.invert_match { !matches } else { matches };

        if should_include {
            has_matches = true;
            match_count += 1;
            matching_line_indices.push(idx);

            // For files_with_matches/files_without_match modes, we just need to know if there are matches
            if config.files_with_matches || config.files_without_match {
                continue;
            }
        }
    }

    // Handle count-only mode
    if config.count {
        writeln!(writer, "{}:{}", file_path, match_count)?;
        return Ok(match_count > 0);
    }

    // Handle files_with_matches/files_without_match output
    if config.files_with_matches && has_matches {
        writeln!(writer, "{}", file_path)?;
        return Ok(has_matches);
    } else if config.files_without_match && !has_matches {
        writeln!(writer, "{}", file_path)?;
        return Ok(has_matches);
    }

    // Output results with context
    let mut output_lines = std::collections::BTreeSet::new(); // Use BTreeSet to keep lines in order
    for &match_idx in &matching_line_indices {
        let start_idx = if match_idx >= before_context { match_idx - before_context } else { 0 };
        let end_idx = std::cmp::min(match_idx + after_context, lines.len() - 1);

        // Add this matching line and its context
        for idx in start_idx..=end_idx {
            output_lines.insert((idx, match_idx == idx)); // (line_idx, is_match)
        }
    }

    let mut output_count = 0;
    for (line_idx, is_match) in output_lines {
        // Check max count limit
        if is_match {
            if let Some(max) = config.max_count {
                if output_count >= max {
                    break;
                }
                output_count += 1;
            }
        }

        if is_match {
            // This is a matching line
            if config.only_matching {
                // Extract only the matching parts
                for mat in regex.find_iter(&lines[line_idx]) {
                    writeln!(writer, "{}", mat.as_str())?;
                }
            } else {
                // Output the full line with proper formatting
                let original_line = &lines[line_idx];
                let line_to_output = if use_colors(&config.color) && !config.only_matching {
                    colorize_matches(original_line, &regex, &config.color)
                } else {
                    original_line.clone()
                };
                
                let output = format_match_with_content(config, file_path, line_idx + 1, &line_to_output);
                writeln!(writer, "{}", output)?;
            }
        } else {
            // This is just context, output with dashes to separate
            let output = format_context_line(config, file_path, line_idx + 1, &lines[line_idx]);
            writeln!(writer, "{}", output)?;
        }
    }

    Ok(has_matches)
}

/// Search for pattern in multiple files/directories
pub fn search_paths(
    config: &SearchConfig,
    paths: &[String],
    recursive: bool,
    no_messages: bool,
    writer: &mut impl Write,
) -> Result<()> {
    let mut all_files = Vec::new();

    for path_str in paths {
        let path = Path::new(path_str);

        if path.is_file() {
            all_files.push(path_str.clone());
        } else if path.is_dir() {
            if recursive {
                // Use walkdir for recursive directory traversal
                for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
                    if entry.file_type().is_file() {
                        if let Some(path_str) = entry.path().to_str() {
                            all_files.push(path_str.to_string());
                        }
                    }
                }
            } else {
                // For files_with_matches/files_without_match, we should list the directory itself
                // but only if it doesn't exist as a file (which we're checking here)
                if config.files_with_matches || config.files_without_match {
                    // For these modes, we should still report the directory
                    all_files.push(path_str.clone());
                }
                if !no_messages {
                    eprintln!("{}: Is a directory", path_str);
                }
            }
        } else {
            if !no_messages {
                eprintln!("{}: No such file or directory", path_str);
            }
            // Return error for non-existent files
            return Err(PergError::FileNotFound(path_str.to_string()));
        }
    }

    // If only one file and filename display is not forced, don't show filenames
    let should_show_filename = config.with_filename || all_files.len() > 1;
    let mut effective_config = config.clone();
    effective_config.with_filename = should_show_filename;

    for (i, file_path) in all_files.iter().enumerate() {
        if let Err(err) = search_file(&effective_config, file_path, writer) {
            if !no_messages {
                eprintln!("perg: {}: {}", file_path, err);
            }
            // Return error for critical failures like file not found or regex errors
            match err {
                PergError::FileNotFound(_) | PergError::Regex(_) => return Err(err),
                _ => {} // Continue for other errors like I/O errors
            }
        }
        
        // Add separator between files if context is enabled and there are multiple files
        if i < all_files.len() - 1 && (config.before_context > 0 || config.after_context > 0 || config.context > 0) {
            writeln!(writer, "--")?;
        }
    }

    Ok(())
}

/// Search stdin for the pattern
pub fn search_stdin(config: &SearchConfig, writer: &mut impl Write) -> Result<()> {
    let stdin = stdin();
    let reader = stdin.lock();

    let pattern = if config.ignore_case {
        format!("(?i){}", config.pattern)
    } else {
        config.pattern.clone()
    };

    let regex = Regex::new(&pattern)?;

    let mut match_count = 0;
    let mut _line_number = 0;
    let mut lines: Vec<String> = Vec::new();
    let mut matching_line_indices = Vec::new();
    
    // Read all lines to enable context functionality
    for line_result in reader.lines() {
        lines.push(line_result?);
        _line_number += 1;
    }

    // Use context: if -C is specified, it overrides -A and -B
    let before_context = if config.context > 0 { config.context } else { config.before_context };
    let after_context = if config.context > 0 { config.context } else { config.after_context };

    // First pass: find all matching lines
    for (idx, line) in lines.iter().enumerate() {
        let matches = regex.is_match(line);

        // Apply invert match logic
        let should_include = if config.invert_match { !matches } else { matches };

        if should_include {
            match_count += 1;
            matching_line_indices.push(idx);

            // For files_with_matches/files_without_match modes, we can't use stdin
            if config.files_with_matches || config.files_without_match {
                // For stdin, these modes don't make sense, so we just continue
                continue;
            }
        }
    }

    // Handle count-only mode
    if config.count {
        writeln!(writer, "{}", match_count)?;
        return Ok(());
    }

    // Handle files_with_matches/files_without_match modes (they don't make sense with stdin)
    if config.files_with_matches || config.files_without_match {
        // These modes don't apply to stdin
        return Ok(());
    }

    // Output results with context
    let mut output_lines = std::collections::BTreeSet::new(); // Use BTreeSet to keep lines in order
    for &match_idx in &matching_line_indices {
        let start_idx = if match_idx >= before_context { match_idx - before_context } else { 0 };
        let end_idx = std::cmp::min(match_idx + after_context, lines.len() - 1);

        // Add this matching line and its context
        for idx in start_idx..=end_idx {
            output_lines.insert((idx, match_idx == idx)); // (line_idx, is_match)
        }
    }

    let mut output_count = 0;
    for (line_idx, is_match) in output_lines {
        // Check max count limit
        if is_match {
            if let Some(max) = config.max_count {
                if output_count >= max {
                    break;
                }
                output_count += 1;
            }
        }

        if is_match {
            // This is a matching line
            if config.only_matching {
                // Extract only the matching parts
                for mat in regex.find_iter(&lines[line_idx]) {
                    writeln!(writer, "{}", mat.as_str())?;
                }
            } else {
                // Output the full line with proper formatting
                let original_line = &lines[line_idx];
                let line_to_output = if use_colors(&config.color) && !config.only_matching {
                    colorize_matches(original_line, &regex, &config.color)
                } else {
                    original_line.clone()
                };
                
                let output = format_line_with_content(config, line_idx + 1, &line_to_output);
                writeln!(writer, "{}", output)?;
            }
        } else {
            // This is just context, output with dashes to separate
            let output = format_context_line_stdin(config, line_idx + 1, &lines[line_idx]);
            writeln!(writer, "{}", output)?;
        }
    }

    Ok(())
}

/// Format a single match result for output
fn format_match(config: &SearchConfig, file_path: &str, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.with_filename {
        output.push_str(file_path);
        output.push_str(":");
    }

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str(":");
    }

    output.push_str(line);
    output
}

/// Format a single match result for output with custom content
fn format_match_with_content(config: &SearchConfig, file_path: &str, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.with_filename {
        output.push_str(file_path);
        output.push_str(":");
    }

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str(":");
    }

    output.push_str(line);
    output
}

/// Format a line from stdin (without filename prefix)
fn format_line(config: &SearchConfig, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str(":");
    }

    output.push_str(line);
    output
}

/// Format a line from stdin with custom content
fn format_line_with_content(config: &SearchConfig, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str(":");
    }

    output.push_str(line);
    output
}

/// Format a context line for file output
fn format_context_line(config: &SearchConfig, file_path: &str, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.with_filename {
        output.push_str(file_path);
        output.push_str("-");
    }

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str("-");
    }

    output.push_str(line);
    output
}

/// Format a context line from stdin (without filename prefix)
fn format_context_line_stdin(config: &SearchConfig, line_number: usize, line: &str) -> String {
    let mut output = String::new();

    if config.line_number {
        output.push_str(&line_number.to_string());
        output.push_str("-");
    }

    output.push_str(line);
    output
}

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

    #[test]
    fn test_search_file_basic() {
        let content = "line 1\ntest line 2\nline 3";
        let mut file = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut file, content.as_bytes()).unwrap();

        let config = SearchConfig::new(
            "test".to_string(),
            false,
            false,
            false,
            false,
            false,
            false,
            false,        // count
            0,            // before_context
            0,            // after_context
            0,            // context
            None,         // max_count
            false,        // only_matching
            false,        // extended_regexp
            "auto".to_string(), // color
        );

        let mut output = Vec::new();
        let result = search_file(&config, file.path().to_str().unwrap(), &mut output);

        assert!(result.is_ok());
        assert!(result.unwrap()); // Should have matches
        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("test line 2"));
    }

    #[test]
    fn test_search_file_case_insensitive() {
        let content = "Line 1\nTEST line 2\nline 3";
        let mut file = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut file, content.as_bytes()).unwrap();

        let config = SearchConfig::new(
            "test".to_string(),
            true, // ignore_case
            false,
            false,
            false,
            false,
            false,
            false,        // count
            0,            // before_context
            0,            // after_context
            0,            // context
            None,         // max_count
            false,        // only_matching
            false,        // extended_regexp
            "auto".to_string(), // color
        );

        let mut output = Vec::new();
        let result = search_file(&config, file.path().to_str().unwrap(), &mut output);

        assert!(result.is_ok());
        assert!(result.unwrap());
        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("TEST line 2"));
    }

    #[test]
    fn test_search_file_invert_match() {
        let content = "line 1\ntest line 2\nline 3";
        let mut file = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut file, content.as_bytes()).unwrap();

        let config = SearchConfig::new(
            "test".to_string(),
            false,
            false,
            false,
            true, // invert_match
            false,
            false,
            false,        // count
            0,            // before_context
            0,            // after_context
            0,            // context
            None,         // max_count
            false,        // only_matching
            false,        // extended_regexp
            "auto".to_string(), // color
        );

        let mut output = Vec::new();
        let result = search_file(&config, file.path().to_str().unwrap(), &mut output);

        assert!(result.is_ok());
        assert!(result.unwrap());
        let output_str = String::from_utf8(output).unwrap();
        assert!(output_str.contains("line 1"));
        assert!(output_str.contains("line 3"));
        assert!(!output_str.contains("test line 2"));
    }
}