fastshell 0.3.3

Lightweight Bash + Python runtime SDK for mobile AI agents
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
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use crate::shell::{CommandOutput, Shell};
use regex::Regex;
use std::sync::atomic::Ordering;

const GREP_HELP_TEXT: &str = "\
Usage: grep [OPTION]... PATTERN [FILE]...
       rg [OPTION]... PATTERN [PATH]...

Pattern matching:
  -F, --fixed-strings     Interpret pattern as fixed string
  -e, --regexp PATTERN    Use PATTERN as the pattern
  -w, --word-regexp       Match whole words only

Matching control:
  -i                       Ignore case
  -v                       Invert match (select non-matching lines)
  -c                       Count matching lines
  -o, --only-matching      Print only matched parts
  -l, --files-with-matches Print only file names
  -n                       Show line numbers
  -r, -R                   Recursive search
  -N, --no-line-number     Suppress line numbers (rg)

rg extras: -g (glob), -t (type), -T (type-not), -A/-B/-C (context),
            -m (max-count), --max-depth, -S (smart-case), --count

  -h, --help               Show this help\n";

impl Shell {
    /// ripgrep-style entry point mapped onto the built-in grep engine:
    /// line numbers on by default, searches `.` recursively when no path is
    /// given, and directory arguments are searched recursively automatically.
    pub fn cmd_rg(&self, args: &[&str], stdin: Option<&str>) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(GREP_HELP_TEXT.to_string());
        }
        let mut flags: Vec<String> = Vec::new();
        let mut positional: Vec<String> = Vec::new();
        let mut no_line_number = false;
        let mut count_or_list = false;

        let mut i = 0;
        while i < args.len() {
            let a = args[i];
            match a {
                "-N" | "--no-line-number" => no_line_number = true,
                "-e" | "--regexp" => {
                    if i + 1 < args.len() {
                        positional.insert(0, args[i + 1].to_string());
                        i += 1;
                    }
                }
                // Value-taking rg options we don't model — consume the value.
                "-g" | "--glob" | "-t" | "--type" | "-T" | "--type-not" | "-m" | "--max-count"
                | "--max-depth" => {
                    i += 1;
                }
                // Context lines — forward to cmd_grep.
                "-A" | "-B" | "-C" | "--after-context" | "--before-context" | "--context" => {
                    if i + 1 < args.len() {
                        let flag = match args[i] {
                            "--after-context" => "-A",
                            "--before-context" => "-B",
                            "--context" => "-C",
                            other => other,
                        };
                        flags.push(flag.to_string());
                        flags.push(args[i + 1].to_string());
                        i += 1;
                    }
                }
                "--fixed-strings" => flags.push("-F".to_string()),
                "--ignore-case" | "-S" | "--smart-case" => flags.push("-i".to_string()),
                "--files-with-matches" => {
                    flags.push("-l".to_string());
                    count_or_list = true;
                }
                "--word-regexp" => flags.push("-w".to_string()),
                "--invert-match" => flags.push("-v".to_string()),
                "--count" => {
                    flags.push("-c".to_string());
                    count_or_list = true;
                }
                a if a.starts_with("--") => {
                    crate::warn!("grep: warning: unsupported option '{}'", a);
                } // --no-heading, --color=..., etc.
                a if a.starts_with('-') && a.len() > 1 => {
                    if a.contains('c') || a.contains('l') {
                        count_or_list = true;
                    }
                    flags.push(a.to_string());
                }
                _ => positional.push(a.to_string()),
            }
            i += 1;
        }

        // rg prints line numbers by default (when not counting/listing).
        if !no_line_number && !count_or_list {
            flags.push("-n".to_string());
        }

        // Paths: everything after the pattern. Default to a recursive search
        // of the current directory when reading from files (not stdin).
        let has_paths = positional.len() > 1;
        if !has_paths && stdin.is_none() {
            flags.push("-r".to_string());
            positional.push(".".to_string());
        } else if has_paths {
            // A directory argument implies recursion (rg behavior).
            let any_dir = positional[1..].iter().any(|p| {
                self.vfs
                    .resolve(p, &self.cwd)
                    .map(|r| r.is_dir())
                    .unwrap_or(false)
            });
            if any_dir {
                flags.push("-r".to_string());
            }
        }

        let mut full: Vec<&str> = flags.iter().map(|s| s.as_str()).collect();
        full.extend(positional.iter().map(|s| s.as_str()));
        self.cmd_grep(&full, stdin)
    }

    pub fn cmd_grep(&self, args: &[&str], stdin: Option<&str>) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(GREP_HELP_TEXT.to_string());
        }
        let mut pattern: Option<String> = None;
        let mut files = Vec::new();
        let mut ignore_case = false;
        let mut invert = false;
        let mut count_only = false;
        let mut show_line_number = false;
        let mut fixed_strings = false;
        let mut recursive = false;
        let mut files_with_matches = false;
        let mut only_matching = false;
        let mut word_regexp = false;
        let mut quiet = false;
        let mut after_context: usize = 0;
        let mut before_context: usize = 0;
        let mut line_regexp = false;
        let mut max_count: Option<usize> = None;
        let mut files_without_match = false;

        let mut i = 0;
        while i < args.len() {
            let arg = args[i];
            match arg {
                "-i" => ignore_case = true,
                "-v" => invert = true,
                "-c" => count_only = true,
                "-n" => show_line_number = true,
                "-F" | "--fixed-strings" => fixed_strings = true,
                "-r" | "-R" => recursive = true,
                "-l" | "--files-with-matches" => files_with_matches = true,
                "-o" | "--only-matching" => only_matching = true,
                "-w" | "--word-regexp" => word_regexp = true,
                "-q" | "--quiet" | "--silent" => quiet = true,
                "-x" | "--line-regexp" => line_regexp = true,
                "-L" | "--files-without-match" => files_without_match = true,
                "-m" | "--max-count" => {
                    if i + 1 < args.len() {
                        max_count = args[i + 1].parse().ok();
                        i += 1;
                    }
                }
                // -E / -P: the regex engine is extended by default; accept -E
                // silently. -P (PCRE) is not available, but tolerate it.
                "-E" | "--extended-regexp" | "-P" | "--perl-regexp" => {}
                "-A" | "--after-context" => {
                    if i + 1 < args.len() {
                        after_context = args[i + 1].parse().unwrap_or(0);
                        i += 1;
                    }
                }
                "-B" | "--before-context" => {
                    if i + 1 < args.len() {
                        before_context = args[i + 1].parse().unwrap_or(0);
                        i += 1;
                    }
                }
                "-C" | "--context" => {
                    if i + 1 < args.len() {
                        after_context = args[i + 1].parse().unwrap_or(0);
                        before_context = args[i + 1].parse().unwrap_or(0);
                        i += 1;
                    }
                }
                "--" => {}, // end of options
                a if a.starts_with('-') && a.len() > 2 => {
                    // Support combined short flags: -ril, -rn, -vc, -ic, etc.
                    for ch in a.chars().skip(1) {
                        match ch {
                            'i' => ignore_case = true,
                            'v' => invert = true,
                            'c' => count_only = true,
                            'n' => show_line_number = true,
                            'F' => fixed_strings = true,
                            'r' | 'R' => recursive = true,
                            'l' => files_with_matches = true,
                            'o' => only_matching = true,
                            'w' => word_regexp = true,
                            'q' => quiet = true,
                            'x' => line_regexp = true,
                            'L' => files_without_match = true,
                            'E' => {}
                            _ => crate::warn!("grep: warning: unsupported option '-{}'", ch),
                        }
                    }
                }
                // Attached value forms: -A2, -B2, -C2
                a if a.starts_with("-A") && a.len() > 2 => {
                    after_context = a[2..].parse().unwrap_or(0);
                }
                a if a.starts_with("-B") && a.len() > 2 => {
                    before_context = a[2..].parse().unwrap_or(0);
                }
                a if a.starts_with("-C") && a.len() > 2 => {
                    after_context = a[2..].parse().unwrap_or(0);
                    before_context = a[2..].parse().unwrap_or(0);
                }
                a if a.starts_with("-m") && a.len() > 2 => {
                    max_count = a[2..].parse().ok();
                }
                _ if arg.starts_with('-') => {
                    crate::warn!("grep: warning: unsupported option '{}'", arg);
                } // unknown single-char flags
                _ if pattern.is_none() => pattern = Some(arg.to_string()),
                _ => files.push(arg.to_string()),
            }
            i += 1;
        }

        let pattern = match pattern {
            Some(p) => p,
            None => return CommandOutput::error("grep: missing pattern\n".to_string(), 2),
        };

        // Build pattern, optionally wrapping in word boundaries / line anchors.
        let effective_pattern = if line_regexp {
            format!(
                r"^(?:{})$",
                if fixed_strings { regex::escape(&pattern) } else { pattern.clone() }
            )
        } else if word_regexp {
            format!(r"\b{}\b", if fixed_strings { regex::escape(&pattern) } else { pattern.clone() })
        } else if fixed_strings {
            regex::escape(&pattern)
        } else {
            pattern.to_string()
        };

        let regex = match build_regex(&effective_pattern, ignore_case) {
            Ok(r) => Some(r),
            Err(e) => {
                return CommandOutput::error(format!("grep: {e}"), 2);
            }
        };

        let matcher: Box<dyn Fn(&str) -> Option<Vec<String>>> = match regex {
            Some(re) => {
                if only_matching {
                    Box::new(move |line: &str| {
                        let found: Vec<String> = re.find_iter(line)
                            .map(|m| m.as_str().to_string())
                            .collect();
                        if found.is_empty() { None } else { Some(found) }
                    })
                } else {
                    Box::new(move |line: &str| {
                        if re.is_match(line) { Some(vec![line.to_string()]) } else { None }
                    })
                }
            }
            None => {
                let p = if word_regexp { pattern.clone() } else { pattern.clone() };
                if ignore_case {
                    let pl = p.to_lowercase();
                    if only_matching {
                        Box::new(move |line: &str| {
                            let lower = line.to_lowercase();
                            if lower.contains(&pl) {
                                Some(vec![find_substring_match(line, &p, true)])
                            } else {
                                None
                            }
                        })
                    } else {
                        Box::new(move |line: &str| {
                            if line.to_lowercase().contains(&pl) {
                                Some(vec![line.to_string()])
                            } else {
                                None
                            }
                        })
                    }
                } else {
                    if only_matching {
                        Box::new(move |line: &str| {
                            if line.contains(&p) {
                                Some(vec![p.clone()])
                            } else {
                                None
                            }
                        })
                    } else {
                        Box::new(move |line: &str| {
                            if line.contains(&p) {
                                Some(vec![line.to_string()])
                            } else {
                                None
                            }
                        })
                    }
                }
            }
        };

        let mut output = String::new();
        let mut stderr = String::new();
        let mut file_errors = 0usize;
        let mut total_matches = 0usize;

        // Expand recursive directories into flat file list
        let mut all_files: Vec<String> = Vec::new();
        for file in &files {
            let path = self.vfs.resolve(file, &self.cwd);
            match path {
                Ok(p) if p.is_dir() && recursive => {
                    self.collect_files_recursive(file, &mut all_files, &mut stderr);
                }
                _ => {
                    all_files.push(file.to_string());
                }
            }
        }

        if all_files.is_empty() && files.is_empty() {
            let input = match stdin {
                Some(s) => s.to_string(),
                None => return CommandOutput::error("grep: missing file operand\n".to_string(), 2),
            };
            let count = grep_lines(
                &input, &matcher, invert, count_only, show_line_number,
                files_with_matches, only_matching, quiet,
                before_context, after_context, max_count, None, &mut output,
            );
            total_matches = count;
            if count_only {
                output.push_str(&format!("{}\n", count));
            }
        } else {
            let multi_file = all_files.len() > 1;
            for file in &all_files {
                if self.cancel.load(Ordering::SeqCst) {
                    return CommandOutput {
                        stdout: output,
                        stderr: format!("{}cancelled\n", stderr),
                        exit_code: 143,
                    };
                }
                match self.vfs.read_to_string(file, &self.cwd) {
                    Ok(content) => {
                        let count = grep_lines(
                            &content, &matcher, invert, count_only, show_line_number,
                            files_with_matches || files_without_match, only_matching, quiet,
                            before_context, after_context, max_count,
                            Some((file, multi_file)), &mut output,
                        );
                        if count > 0 {
                            if files_with_matches {
                                output.push_str(file);
                                output.push('\n');
                            }
                            total_matches += 1; // count files, not lines, for -l
                        } else if !files_with_matches {
                            total_matches += 0; // for non-l mode, total is line count
                        }
                        if files_without_match {
                            if count == 0 {
                                output.push_str(file);
                                output.push('\n');
                            }
                        }
                        if !files_with_matches {
                            total_matches += count;
                        }
                        // -q: stop scanning at the first match.
                        if quiet && total_matches > 0 {
                            break;
                        }
                    }
                    Err(e) => {
                        stderr.push_str(&format!("grep: {}: {}\n", file, e));
                        file_errors += 1;
                    }
                }
            }
        }

        let exit_code = if file_errors > 0 {
            2
        } else if files_without_match {
            if output.is_empty() { 1 } else { 0 }
        } else if total_matches == 0 {
            1
        } else {
            0
        };

        CommandOutput {
            stdout: output,
            stderr,
            exit_code,
        }
    }

    /// Recursively collect regular files under `dir_path` into `out`.
    fn collect_files_recursive(&self, dir_path: &str, out: &mut Vec<String>, stderr: &mut String) {
        if self.cancel.load(Ordering::SeqCst) {
            return;
        }
        match self.vfs.list_dir(dir_path, &self.cwd) {
            Ok(entries) => {
                for entry in &entries {
                    let full = if dir_path.ends_with('/') {
                        format!("{}{}", dir_path, entry.name)
                    } else {
                        format!("{}/{}", dir_path, entry.name)
                    };
                    if entry.is_dir {
                        self.collect_files_recursive(&full, out, stderr);
                    } else {
                        out.push(full);
                    }
                }
            }
            Err(e) => {
                stderr.push_str(&format!("grep: {}: {}\n", dir_path, e));
            }
        }
    }
}

fn build_regex(pattern: &str, ignore_case: bool) -> Result<Regex, regex::Error> {
    if ignore_case {
        Regex::new(&format!("(?i){}", pattern))
    } else {
        Regex::new(pattern)
    }
}

fn find_substring_match(line: &str, pattern: &str, ignore_case: bool) -> String {
    if ignore_case {
        let lower = line.to_lowercase();
        let pl = pattern.to_lowercase();
        if let Some(pos) = lower.find(&pl) {
            line[pos..pos + pattern.len()].to_string()
        } else {
            pattern.to_string()
        }
    } else {
        if let Some(pos) = line.find(pattern) {
            line[pos..pos + pattern.len()].to_string()
        } else {
            pattern.to_string()
        }
    }
}

fn grep_lines(
    content: &str,
    matcher: &dyn Fn(&str) -> Option<Vec<String>>,
    invert: bool,
    count_only: bool,
    show_line_number: bool,
    files_with_matches: bool,
    only_matching: bool,
    quiet: bool,
    before_context: usize,
    after_context: usize,
    max_count: Option<usize>,
    file_label: Option<(&str, bool)>, // (filename, multi_file)
    output: &mut String,
) -> usize {
    if files_with_matches || quiet {
        // Just check if any line matches (short-circuits on first match).
        for line in content.lines() {
            let matches = matcher(line);
            let has_match = matches.is_some();
            if (invert && !has_match) || (!invert && has_match) {
                return 1;
            }
        }
        return 0;
    }

    let (fname, multi) = file_label.unwrap_or(("", false));
    let lines: Vec<&str> = content.lines().collect();

    // Precompute per-line match flags (needed for context windows).
    let matched: Vec<bool> = lines
        .iter()
        .map(|l| {
            let has = matcher(l).is_some();
            if invert { !has } else { has }
        })
        .collect();
    let mut count = matched.iter().filter(|&&m| m).count();
    if let Some(m) = max_count {
        count = count.min(m);
    }

    if count_only {
        let prefix = if multi { format!("{}:", fname) } else { String::new() };
        output.push_str(&format!("{}{}\n", prefix, count));
        return count;
    }

    let context_on = before_context > 0 || after_context > 0;

    if context_on {
        // Context mode: print each match plus the surrounding lines, with
        // `--` separating non-adjacent groups (GNU grep style).
        let mut last_printed: isize = -(before_context as isize + after_context as isize + 2);
        let mut i = 0;
        let mut printed_matches = 0usize;
        while i < lines.len() {
            if !matched[i] {
                i += 1;
                continue;
            }
            if let Some(m) = max_count {
                if printed_matches >= m {
                    break;
                }
            }
            printed_matches += 1;
            let start = i.saturating_sub(before_context);
            let end = (i + after_context + 1).min(lines.len());
            if (start as isize) > last_printed + 1 && !output.is_empty() {
                output.push_str("--\n");
            }
            for j in start..end {
                let prefix = if multi {
                    if show_line_number {
                        format!("{}-{}-", fname, j + 1)
                    } else {
                        format!("{}-", fname)
                    }
                } else if show_line_number {
                    format!("{}-", j + 1)
                } else {
                    String::new()
                };
                output.push_str(&prefix);
                output.push_str(lines[j]);
                output.push('\n');
                last_printed = j as isize;
            }
            i = end;
        }
        return count;
    }

    // No context: original line-oriented output.
    let mut printed_matches = 0usize;
    for (line_num, line) in lines.iter().enumerate() {
        if !matched[line_num] {
            continue;
        }
        if let Some(m) = max_count {
            if printed_matches >= m {
                break;
            }
        }
        printed_matches += 1;
        let prefix = if multi {
            format!("{}:", fname)
        } else {
            String::new()
        };
        if only_matching {
            if let Some(matches) = matcher(line) {
                for m in matches {
                    if !prefix.is_empty() {
                        output.push_str(&prefix);
                    }
                    if show_line_number {
                        output.push_str(&format!("{}:", line_num + 1));
                    }
                    output.push_str(&m);
                    output.push('\n');
                }
            }
        } else {
            if !prefix.is_empty() {
                output.push_str(&prefix);
            }
            if show_line_number {
                output.push_str(&format!("{}:", line_num + 1));
            }
            output.push_str(line);
            output.push('\n');
        }
    }

    count
}

#[cfg(test)]
mod tests {
    use crate::shell::Shell;
    use crate::vfs::Vfs;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEST_COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn mk_shell() -> Shell {
        use std::fs;
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!(
            "fastshell_grep_test_{}_{}",
            std::process::id(),
            n
        ));
        let _ = fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        Shell::new(vfs)
    }

    #[test]
    fn test_grep_help() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-h"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }

    #[test]
    fn test_grep_help_long() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["--help"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }

    #[test]
    fn test_rg_help() {
        let mut shell = mk_shell();
        let out = shell.execute("rg", &["-h"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }

    #[test]
    fn test_rg_help_long() {
        let mut shell = mk_shell();
        let out = shell.execute("rg", &["--help"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }

    #[test]
    fn test_grep_quiet_no_output_on_match() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-q", "foo"], Some("foobar\nbaz\n"));
        assert_eq!(out.exit_code, 0, "grep -q with match should exit 0");
        assert!(out.stdout.is_empty(), "grep -q should not print matches: {}", out.stdout);
    }

    #[test]
    fn test_grep_quiet_exit_1_on_no_match() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-q", "zzz"], Some("foobar\nbaz\n"));
        assert_eq!(out.exit_code, 1, "grep -q without match should exit 1");
    }

    #[test]
    fn test_grep_extended_regexp_no_warning() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-E", "^foo[0-9]+$"], Some("foo123\nbar\n"));
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("foo123"));
        assert!(!out.stderr.contains("unsupported"), "-E should not warn: {}", out.stderr);
    }

    #[test]
    fn test_grep_context_after() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-A", "1", "foo"], Some("a\nfoo\nb\nc\n"));
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("foo"), "match line should be present: {}", out.stdout);
        assert!(out.stdout.contains("\nb\n"), "after-context line should follow");
        assert!(!out.stdout.contains("\nc\n"), "line outside context should be absent");
    }

    #[test]
    fn test_grep_context_before() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-B", "1", "foo"], Some("a\nfoo\nb\n"));
        assert!(out.stdout.contains("a"), "before-context line should be present: {}", out.stdout);
        assert!(out.stdout.contains("foo"));
    }

    #[test]
    fn test_grep_context_both() {
        let mut shell = mk_shell();
        let out = shell.execute("grep", &["-C", "1", "foo"], Some("a\nfoo\nb\n"));
        assert!(out.stdout.contains("a"));
        assert!(out.stdout.contains("foo"));
        assert!(out.stdout.contains("b"));
    }

    #[test]
    fn test_grep_context_separator() {
        let mut shell = mk_shell();
        // Two matches far apart → groups separated by `--`.
        let out = shell.execute("grep", &["-A", "1", "x"], Some("x\n1\n2\n3\n4\nx\n5\n"));
        assert!(out.stdout.contains("--"), "separate context groups should be split by --: {}", out.stdout);
    }
}