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
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
// 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 std::sync::atomic::Ordering;
use std::time::SystemTime;

const FIND_HELP_TEXT: &str = "\
Usage: find [PATH] [OPTIONS] [EXPRESSION]

Predicates:
  -name PATTERN    File name matches shell pattern
  -type [fdl]      File type: f=file, d=directory, l=symlink
  -empty           File is empty
  -mtime [+-]N     Modified time in days
  -size [+-]N[c]   File size in bytes

Actions:
  -print           Print file path (default)
  -print0          Print null-terminated
  -delete          Delete matching files
  -exec CMD {} \\;  Execute command per file
  -exec CMD {} +   Execute command with batch

Options:
  -maxdepth N      Maximum recursion depth
  -mindepth N      Minimum recursion depth
  -o               OR conditions
  !  -not          Negate condition

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

#[derive(Debug, Clone)]
enum ConditionKind {
    Name(String),
    Iname(String),
    Type(char),
    Empty,
    Mtime { days: i64, greater_than: bool },
    Size { bytes: i64, greater_than: bool },
    Regex(String),
    IRegex(String),
    Newer(SystemTime),
}

#[derive(Debug, Clone)]
struct Condition {
    negate: bool,
    kind: ConditionKind,
}

#[derive(Debug, Clone)]
enum Action {
    Print,
    Print0,
    Delete,
    /// -exec cmd args {} ;   (run per matched file)
    Exec(Vec<String>),
    /// -exec cmd args {} +   (run once with all matched files)
    ExecBatch(Vec<String>),
}

impl Shell {
    pub fn cmd_find(&self, args: &[&str]) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(FIND_HELP_TEXT.to_string());
        }
        let mut path = ".".to_string();
        let mut path_set = false;
        let mut conditions: Vec<Vec<Condition>> = vec![vec![]];
        let mut actions: Vec<Action> = Vec::new();
        let mut maxdepth: Option<usize> = None;
        let mut mindepth: Option<usize> = None;
        let mut i = 0;
        let mut negate_next = false;

        while i < args.len() {
            match args[i] {
                "-maxdepth" => {
                    if i + 1 < args.len() {
                        if let Ok(d) = args[i + 1].parse::<usize>() {
                            maxdepth = Some(d);
                        }
                        i += 1;
                    }
                }
                "-mindepth" => {
                    if i + 1 < args.len() {
                        if let Ok(d) = args[i + 1].parse::<usize>() {
                            mindepth = Some(d);
                        }
                        i += 1;
                    }
                }
                "-empty" => {
                    add_condition(
                        &mut conditions,
                        Condition {
                            negate: negate_next,
                            kind: ConditionKind::Empty,
                        },
                    );
                    negate_next = false;
                }
                "-name" => {
                    if i + 1 < args.len() {
                        let pat = args[i + 1].to_string();
                        add_condition(
                            &mut conditions,
                            Condition {
                                negate: negate_next,
                                kind: ConditionKind::Name(pat),
                            },
                        );
                        negate_next = false;
                        i += 1;
                    }
                }
                "-iname" => {
                    if i + 1 < args.len() {
                        let pat = args[i + 1].to_string();
                        add_condition(
                            &mut conditions,
                            Condition {
                                negate: negate_next,
                                kind: ConditionKind::Iname(pat),
                            },
                        );
                        negate_next = false;
                        i += 1;
                    }
                }
                "-type" => {
                    if i + 1 < args.len() {
                        if let Some(ch) = args[i + 1].chars().next() {
                            add_condition(
                                &mut conditions,
                                Condition {
                                    negate: negate_next,
                                    kind: ConditionKind::Type(ch),
                                },
                            );
                        }
                        negate_next = false;
                        i += 1;
                    }
                }
                "-mtime" => {
                    if i + 1 < args.len() {
                        if let Some(cond) = parse_mtime(args[i + 1]) {
                            add_condition(
                                &mut conditions,
                                Condition {
                                    negate: negate_next,
                                    kind: cond,
                                },
                            );
                        }
                        negate_next = false;
                        i += 1;
                    }
                }
                "-size" => {
                    if i + 1 < args.len() {
                        if let Some(cond) = parse_size(args[i + 1]) {
                            add_condition(
                                &mut conditions,
                                Condition {
                                    negate: negate_next,
                                    kind: cond,
                                },
                            );
                        }
                        negate_next = false;
                        i += 1;
                    }
                }
                "-regex" => {
                    if i + 1 < args.len() {
                        add_condition(
                            &mut conditions,
                            Condition {
                                negate: negate_next,
                                kind: ConditionKind::Regex(args[i + 1].to_string()),
                            },
                        );
                        negate_next = false;
                        i += 1;
                    }
                }
                "-iregex" => {
                    if i + 1 < args.len() {
                        add_condition(
                            &mut conditions,
                            Condition {
                                negate: negate_next,
                                kind: ConditionKind::IRegex(args[i + 1].to_string()),
                            },
                        );
                        negate_next = false;
                        i += 1;
                    }
                }
                "-newer" => {
                    if i + 1 < args.len() {
                        let ref_time = self
                            .vfs
                            .resolve(args[i + 1], &self.cwd)
                            .ok()
                            .and_then(|p| std::fs::metadata(&p).ok())
                            .and_then(|m| m.modified().ok());
                        if let Some(t) = ref_time {
                            add_condition(
                                &mut conditions,
                                Condition {
                                    negate: negate_next,
                                    kind: ConditionKind::Newer(t),
                                },
                            );
                        }
                        negate_next = false;
                        i += 1;
                    }
                }
                "-print0" => {
                    actions.push(Action::Print0);
                }
                "-delete" => {
                    actions.push(Action::Delete);
                }
                "-exec" => {
                    i += 1;
                    let mut exec_args: Vec<String> = Vec::new();
                    let mut batch = false;
                    while i < args.len() && args[i] != ";" && args[i] != "\\;" {
                        if args[i] == "+" {
                            batch = true;
                            break;
                        }
                        exec_args.push(args[i].to_string());
                        i += 1;
                    }
                    if !exec_args.is_empty() {
                        if batch {
                            actions.push(Action::ExecBatch(exec_args));
                        } else {
                            actions.push(Action::Exec(exec_args));
                        }
                    }
                }
                "-o" => {
                    conditions.push(vec![]);
                }
                "!" | "-not" => {
                    negate_next = !negate_next;
                }
                arg if !arg.starts_with('-') && !path_set => {
                    path = arg.to_string();
                    path_set = true;
                }
                _ => crate::warn!("find: warning: unsupported option '{}'", args[i]),
            }
            i += 1;
        }

        if actions.is_empty() {
            actions.push(Action::Print);
        }

        let compiled_conditions: Vec<Vec<(bool, Option<regex::Regex>, ConditionKind)>> = conditions
            .iter()
            .map(|group| {
                group
                    .iter()
                    .map(|c| {
                        let compiled = match &c.kind {
                            ConditionKind::Name(pat) => Some(compile_glob_ci(pat, false)),
                            ConditionKind::Iname(pat) => Some(compile_glob_ci(pat, true)),
                            ConditionKind::Regex(pat) => regex::Regex::new(pat).ok(),
                            ConditionKind::IRegex(pat) => regex::Regex::new(&format!("(?i){}", pat)).ok(),
                            _ => None,
                        };
                        (c.negate, compiled, c.kind.clone())
                    })
                    .collect()
            })
            .collect();

        let mut output = String::new();
        let mut exit_code = 0;
        let mut batch_paths: Vec<String> = Vec::new();

        // Check the starting path itself
        if let Ok(resolved) = self.vfs.resolve(&path, &self.cwd) {
            if let Ok(metadata) = std::fs::symlink_metadata(&resolved) {
                let entry_name = resolved
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| path.clone());
                let start_entry = crate::vfs::DirEntry {
                    name: entry_name.clone(),
                    is_dir: resolved.metadata().map(|m| m.is_dir()).unwrap_or(false),
                    is_symlink: metadata.file_type().is_symlink(),
                    size: metadata.len(),
                    modified: metadata.modified().ok(),
                };
                if evaluate_conditions(&compiled_conditions, entry_name, &start_entry, &self.vfs, &self.cwd) {
                    apply_actions(&actions, &path, self, &mut output, &mut exit_code, &mut batch_paths);
                }
            }
        }

        if let Err(e) = self.find_recursive(
            &path,
            0,
            maxdepth,
            mindepth,
            &compiled_conditions,
            &actions,
            &mut output,
            &mut exit_code,
            &mut batch_paths,
        ) {
            return CommandOutput::error(format!("find: {}\n", e), 1);
        }

        // `-exec ... {} +`: run once with all matched paths substituted.
        if !batch_paths.is_empty() {
            for action in &actions {
                if let Action::ExecBatch(cmd_args) = action {
                    let mut args: Vec<String> = Vec::new();
                    let mut replaced = false;
                    for a in cmd_args {
                        if a == "{}" {
                            args.extend(batch_paths.iter().cloned());
                            replaced = true;
                        } else {
                            args.push(a.clone());
                        }
                    }
                    if !replaced {
                        args.extend(batch_paths.iter().cloned());
                    }
                    run_exec_builtin(self, &args, &mut output, &mut exit_code);
                }
            }
        }

        CommandOutput {
            stdout: output,
            stderr: String::new(),
            exit_code,
        }
    }

    fn find_recursive(
        &self,
        path: &str,
        depth: usize,
        maxdepth: Option<usize>,
        mindepth: Option<usize>,
        conditions: &[Vec<(bool, Option<regex::Regex>, ConditionKind)>],
        actions: &[Action],
        output: &mut String,
        exit_code: &mut i32,
        batch_paths: &mut Vec<String>,
    ) -> Result<(), crate::vfs::VfsError> {
        if let Some(md) = maxdepth {
            if depth >= md {
                return Ok(());
            }
        }
        let entries = self.vfs.list_dir(path, &self.cwd)?;

        for entry in &entries {
            if self.cancel.load(Ordering::SeqCst) {
                return Ok(());
            }
            let entry_path = format!("{}/{}", path.trim_end_matches('/'), entry.name);

            if entry.is_dir {
                if maxdepth.map_or(true, |md| depth < md) {
                    let _ = self.find_recursive(
                        &entry_path,
                        depth + 1,
                        maxdepth,
                        mindepth,
                        conditions,
                        actions,
                        output,
                        exit_code,
                        batch_paths,
                    );
                }
            }

            // mindepth: only evaluate conditions if depth >= mindepth
            if mindepth.map_or(true, |md| depth >= md) {
                if evaluate_conditions(conditions, entry.name.clone(), entry, &self.vfs, &self.cwd) {
                    apply_actions(actions, &entry_path, self, output, exit_code, batch_paths);
                }
            }
        }

        Ok(())
    }
}

fn apply_actions(
    actions: &[Action],
    entry_path: &str,
    shell: &Shell,
    output: &mut String,
    exit_code: &mut i32,
    batch_paths: &mut Vec<String>,
) {
    let vfs = &shell.vfs;
    let cwd = &shell.cwd;
    for action in actions {
        match action {
            Action::Print => {
                output.push_str(&format!("{}\n", entry_path));
            }
            Action::Print0 => {
                output.push_str(entry_path);
                output.push('\0');
            }
            Action::Delete => {
                // Try as directory first, fall back to file
                if let Err(e) = vfs.remove_dir_all(entry_path, cwd) {
                    if let Err(e2) = vfs.remove_file(entry_path, cwd) {
                        *exit_code = 1;
                        output.push_str(&format!(
                            "find: cannot delete '{}': {} / {}\n",
                            entry_path, e, e2
                        ));
                    }
                }
            }
            Action::ExecBatch(_) => {
                // Collected here, executed once after the traversal.
                batch_paths.push(entry_path.to_string());
            }
            Action::Exec(cmd_args) => {
                let args: Vec<String> = cmd_args
                    .iter()
                    .map(|a| {
                        if a == "{}" {
                            entry_path.to_string()
                        } else {
                            a.clone()
                        }
                    })
                    .collect();
                run_exec_builtin(shell, &args, output, exit_code);
            }
        }
    }
}

/// Runs an `-exec` command through the built-in shell (sandbox-safe: no OS
/// process is spawned, so this works on mobile where no binaries exist).
fn run_exec_builtin(shell: &Shell, args: &[String], output: &mut String, exit_code: &mut i32) {
    if args.is_empty() {
        return;
    }
    let mut sub = shell.clone();
    let arg_refs: Vec<&str> = args[1..].iter().map(|s| s.as_str()).collect();
    let result = sub.execute(&args[0], &arg_refs, None);
    output.push_str(&result.stdout);
    if result.exit_code != 0 {
        *exit_code = result.exit_code;
        if !result.stderr.is_empty() {
            output.push_str(&result.stderr);
        }
    }
}

fn evaluate_conditions(
    conditions: &[Vec<(bool, Option<regex::Regex>, ConditionKind)>],
    name: String,
    entry: &crate::vfs::DirEntry,
    vfs: &crate::vfs::Vfs,
    cwd: &str,
) -> bool {
    if conditions.is_empty() || conditions.iter().all(|g| g.is_empty()) {
        return true;
    }
    for group in conditions {
        if group.is_empty() {
            continue;
        }
        let group_match = group.iter().all(|(negate, compiled, kind)| {
            let result = match kind {
                ConditionKind::Name(_) | ConditionKind::Iname(_) => match compiled {
                    Some(re) => re.is_match(&name),
                    None => true,
                },
                ConditionKind::Regex(_) | ConditionKind::IRegex(_) => match compiled {
                    Some(re) => re.is_match(&name),
                    None => false,
                },
                ConditionKind::Newer(ref_time) => match entry.modified {
                    Some(mod_time) => mod_time > *ref_time,
                    None => false,
                },
                ConditionKind::Type(ch) => match ch {
                    'd' => entry.is_dir,
                    'f' => !entry.is_dir,
                    'l' => entry.is_symlink,
                    _ => true,
                },
                ConditionKind::Empty => {
                    if entry.is_dir {
                        vfs.list_dir(&name, cwd)
                            .map(|e| e.is_empty())
                            .unwrap_or(false)
                    } else {
                        entry.size == 0
                    }
                }
                ConditionKind::Mtime { days, greater_than } => match entry.modified {
                    Some(mod_time) => {
                        let now = SystemTime::now();
                        let file_age_secs = match now.duration_since(mod_time) {
                            Ok(d) => d.as_secs() as i64,
                            Err(_) => -1,
                        };
                        if file_age_secs < 0 {
                            return false;
                        }
                        let file_days = file_age_secs / 86400;
                        if *greater_than {
                            file_days > *days
                        } else {
                            file_days < *days
                        }
                    }
                    None => false,
                },
                ConditionKind::Size {
                    bytes,
                    greater_than,
                } => {
                    let size = entry.size as i64;
                    if *greater_than {
                        size > *bytes
                    } else {
                        size < *bytes
                    }
                }
            };
            if *negate {
                !result
            } else {
                result
            }
        });

        if group_match {
            return true;
        }
    }

    false
}

fn add_condition(groups: &mut Vec<Vec<Condition>>, cond: Condition) {
    if groups.is_empty() {
        groups.push(vec![]);
    }
    let last = groups.last_mut().unwrap();
    last.push(cond);
}

fn parse_mtime(arg: &str) -> Option<ConditionKind> {
    if arg.len() < 2 {
        return None;
    }
    let (sign, num_str) = match arg.chars().next().unwrap() {
        '+' => (true, &arg[1..]),
        '-' => (false, &arg[1..]),
        _ => return None,
    };
    let days: i64 = num_str.parse().ok()?;
    Some(ConditionKind::Mtime {
        days,
        greater_than: sign,
    })
}

fn parse_size(arg: &str) -> Option<ConditionKind> {
    if arg.len() < 3 {
        return None;
    }
    let (greater_than, rest) = match arg.chars().next().unwrap() {
        '+' => (true, &arg[1..]),
        '-' => (false, &arg[1..]),
        _ => return None,
    };

    let (num_str, unit) = if rest.ends_with('k') || rest.ends_with('K') {
        (&rest[..rest.len() - 1], 'k')
    } else if rest.ends_with('M') {
        (&rest[..rest.len() - 1], 'M')
    } else if rest.ends_with('G') {
        (&rest[..rest.len() - 1], 'G')
    } else {
        return None;
    };

    let value: i64 = num_str.parse().ok()?;
    let bytes = match unit {
        'k' => value * 1024,
        'M' => value * 1024 * 1024,
        'G' => value * 1024 * 1024 * 1024,
        _ => value,
    };

    Some(ConditionKind::Size {
        bytes,
        greater_than,
    })
}

fn compile_glob_ci(pattern: &str, ignore_case: bool) -> regex::Regex {
    let mut regex_str = String::new();
    if ignore_case {
        regex_str.push_str("(?i)");
    }
    regex_str.push('^');
    for ch in pattern.chars() {
        match ch {
            '*' => regex_str.push_str(".*"),
            '?' => regex_str.push('.'),
            '.' | '+' | '(' | ')' | '|' | '^' | '$' | '{' | '}' | '[' | ']' | '\\' => {
                regex_str.push('\\');
                regex_str.push(ch);
            }
            _ => regex_str.push(ch),
        }
    }
    regex_str.push('$');
    regex::Regex::new(&regex_str).unwrap_or_else(|_| {
        let escaped = regex::escape(pattern);
        regex::Regex::new(&format!("^{}$", escaped)).unwrap_or_else(|_| regex::Regex::new(".*").unwrap())
    })
}

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

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

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

    fn mk_shell() -> Shell {
        Shell::new(setup_vfs())
    }

    #[test]
    fn test_find_basic() {
        let shell = mk_shell();
        let r = shell.cmd_mkdir(&["a"]);
        assert_eq!(r.exit_code, 0, "mkdir a failed: {:?}", r);
        let r = shell.cmd_mkdir(&["a/b"]);
        assert_eq!(r.exit_code, 0, "mkdir a/b failed: {:?}", r);
        let r = shell.cmd_touch(&["a/file.txt"]);
        assert_eq!(r.exit_code, 0, "touch a/file.txt failed: {:?}", r);
        let r = shell.cmd_touch(&["a/b/nested.txt"]);
        assert_eq!(r.exit_code, 0, "touch a/b/nested.txt failed: {:?}", r);

        let out = shell.cmd_find(&["a"]);
        assert!(out.stdout.contains("a/file.txt"));
        assert!(out.stdout.contains("a/b/nested.txt"));

        let out = shell.cmd_find(&["a", "-name", "*.txt", "-type", "f"]);
        assert!(out.stdout.contains("a/file.txt"));
    }

    #[test]
    fn test_find_type_d() {
        let shell = mk_shell();
        shell.cmd_mkdir(&["src"]);
        shell.cmd_touch(&["src/main.rs"]);

        let out = shell.cmd_find(&["src", "-type", "d"]);
        assert!(out.stdout.contains("src"));
    }

    #[test]
    fn test_find_iname_case_insensitive() {
        let shell = mk_shell();
        shell.cmd_touch(&["Report.PDF"]);
        shell.cmd_touch(&["notes.txt"]);

        // -iname matches case-insensitively.
        let out = shell.cmd_find(&[".", "-iname", "*.pdf"]);
        assert!(
            out.stdout.contains("Report.PDF"),
            "-iname should match Report.PDF: {}",
            out.stdout
        );
        assert!(
            !out.stdout.contains("notes.txt"),
            "-iname *.pdf should not match notes.txt"
        );
    }

    #[test]
    fn test_find_name_is_case_sensitive() {
        let shell = mk_shell();
        shell.cmd_touch(&["Report.PDF"]);

        // -name is case-sensitive, so *.pdf must NOT match Report.PDF.
        let out = shell.cmd_find(&[".", "-name", "*.pdf"]);
        assert!(
            !out.stdout.contains("Report.PDF"),
            "-name *.pdf should not match Report.PDF"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_find_type_l() {
        let shell = mk_shell();
        shell.cmd_touch(&["target.txt"]);
        // Create a symlink to target.txt.
        let root = shell.vfs.root().to_path_buf();
        let _ = std::os::unix::fs::symlink(root.join("target.txt"), root.join("link.txt"));

        let out = shell.cmd_find(&[".", "-type", "l"]);
        assert!(
            out.stdout.contains("link.txt"),
            "-type l should match the symlink: {}",
            out.stdout
        );
        assert!(
            !out.stdout.contains("target.txt"),
            "-type l should not match a regular file: {}",
            out.stdout
        );
    }

    #[test]
    fn test_find_maxdepth() {
        let shell = mk_shell();
        shell.cmd_mkdir(&["a"]);
        shell.cmd_mkdir(&["a/b"]);
        shell.cmd_mkdir(&["a/b/c"]);
        shell.cmd_touch(&["a/b/c/deep.txt"]);

        let out = shell.cmd_find(&["a", "-maxdepth", "1"]);
        assert!(out.stdout.contains("a/b"));
        assert!(!out.stdout.contains("a/b/c"));
    }

    #[test]
    fn test_find_mtime() {
        let shell = mk_shell();
        shell.cmd_touch(&["new.txt"]);

        let out = shell.cmd_find(&[".", "-mtime", "-365"]);
        assert!(out.stdout.contains("new.txt"));

        let out = shell.cmd_find(&[".", "-mtime", "+9999"]);
        assert!(!out.stdout.contains("new.txt"));
    }

    #[test]
    fn test_find_size() {
        let shell = mk_shell();
        let out = shell.cmd_find(&[".", "-size", "-100M"]);
        assert!(out.stdout.contains("."));
    }

    #[test]
    fn test_find_not() {
        let shell = mk_shell();
        shell.cmd_mkdir(&["testdir"]);
        shell.cmd_touch(&["testfile.txt"]);

        let out = shell.cmd_find(&[".", "!", "-type", "d", "-maxdepth", "1"]);
        assert!(!out.stdout.contains("testdir"));
        assert!(out.stdout.contains("testfile.txt"));
    }

    #[test]
    fn test_find_or() {
        let shell = mk_shell();
        shell.cmd_touch(&["a.txt"]);
        shell.cmd_touch(&["b.md"]);
        shell.cmd_touch(&["c.rs"]);

        let out = shell.cmd_find(&[
            ".",
            "-name",
            "*.txt",
            "-o",
            "-name",
            "*.md",
            "-maxdepth",
            "1",
        ]);
        assert!(out.stdout.contains("a.txt"));
        assert!(out.stdout.contains("b.md"));
        assert!(!out.stdout.contains("c.rs"));
    }

    #[test]
    fn test_find_print0() {
        let shell = mk_shell();
        shell.cmd_touch(&["file.txt"]);

        let out = shell.cmd_find(&[".", "-print0", "-maxdepth", "1"]);
        assert!(out.stdout.contains('\0'));
    }

    #[test]
    fn test_find_exec() {
        let shell = mk_shell();
        shell.cmd_mkdir(&["sub"]);
        shell.cmd_touch(&["sub/a.txt"]);

        let out = shell.cmd_find(&["sub", "-name", "*.txt", "-exec", "echo", "found", "{}", ";"]);
        // echo should output "found sub/a.txt" including the newline
        assert!(out.stdout.contains("sub/a.txt"));
    }

    #[test]
    fn test_find_not_found_path() {
        let shell = mk_shell();
        let out = shell.cmd_find(&["/nonexistent_path_xyz"]);
        assert_ne!(out.exit_code, 0);
    }

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

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