fastshell 0.3.6

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
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use crate::shell::{CommandOutput, Shell};

const XARGS_HELP_TEXT: &str = "\
Usage: xargs [OPTION]... COMMAND [ARG]...
Build and execute command lines from standard input.

  -n N      use at most N arguments per command line
  -I R      replace occurrences of R with input lines
  -0        items are separated by null, not whitespace
  -P N      run up to N commands in parallel
  -t        print each command line to stderr before executing
  -h, --help  display this help and exit
";

impl Shell {
    pub fn cmd_xargs(&mut self, args: &[&str], stdin: Option<&str>) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(XARGS_HELP_TEXT.to_string());
        }
        let mut max_args: Option<usize> = None;
        let mut max_lines: Option<usize> = None;
        let mut max_chars: Option<usize> = None;
        let mut replace_str: Option<String> = None;
        let mut null_delimited = false;
        let mut parallel: Option<usize> = None;
        let mut verbose = false;
        let mut target_cmd: Vec<String> = Vec::new();
        let mut parsing_cmd = false;

        let mut i = 0;
        while i < args.len() {
            match args[i] {
                "-n" => {
                    if i + 1 < args.len() {
                        max_args = args[i + 1].parse::<usize>().ok();
                        i += 1;
                    }
                }
                a if a.starts_with("-n") && a.len() > 2 => {
                    max_args = a[2..].parse::<usize>().ok();
                }
                "-I" => {
                    if i + 1 < args.len() {
                        replace_str = Some(args[i + 1].to_string());
                        i += 1;
                    }
                }
                a if a.starts_with("-I") && a.len() > 2 => {
                    replace_str = Some(a[2..].to_string());
                }
                "-0" | "--null" => {
                    null_delimited = true;
                }
                "-P" => {
                    if i + 1 < args.len() {
                        parallel = args[i + 1].parse::<usize>().ok();
                        i += 1;
                    }
                }
                a if a.starts_with("-P") && a.len() > 2 => {
                    parallel = a[2..].parse::<usize>().ok();
                }
                "-t" => {
                    verbose = true;
                }
                "-r" | "--no-run-if-empty" => {}
                "-p" | "--interactive" | "--verbose" => {}
                "-L" | "--max-lines" => {
                    if i + 1 < args.len() {
                        max_lines = args[i + 1].parse::<usize>().ok();
                        i += 1;
                    }
                }
                a if a.starts_with("-L") && a.len() > 2 => {
                    max_lines = a[2..].parse::<usize>().ok();
                }
                "-s" | "--max-chars" => {
                    if i + 1 < args.len() {
                        max_chars = args[i + 1].parse::<usize>().ok();
                        i += 1;
                    }
                }
                a if a.starts_with("-s") && a.len() > 2 => {
                    max_chars = a[2..].parse::<usize>().ok();
                }
                "-d" | "--delimiter" | "-E" | "--eof" => {
                    if i + 1 < args.len() {
                        i += 1;
                    }
                }
                a if !a.starts_with('-') && !parsing_cmd => {
                    parsing_cmd = true;
                    target_cmd.push(a.to_string());
                }
                a if parsing_cmd => {
                    target_cmd.push(a.to_string());
                }
                _ => {
                    crate::warn!("xargs: warning: unsupported option '{}'", args[i]);
                }
            }
            i += 1;
        }

        if target_cmd.is_empty() {
            // GNU xargs defaults to `echo`.
            target_cmd.push("echo".to_string());
        }

        let input = match stdin {
            Some(s) => s.to_string(),
            None => {
                if replace_str.is_some() {
                    // With -I, xargs runs the command even with empty input
                    let cmd =
                        build_command_with_replace(&target_cmd, "", replace_str.as_ref().unwrap());
                    let mut out = self.execute(
                        &cmd[0],
                        &cmd[1..].iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                        None,
                    );
                    if verbose {
                        out.stderr = format!("{}\n{}", cmd.join(" "), out.stderr);
                    }
                    return out;
                }
                return CommandOutput::error("xargs: no input\n".to_string(), 1);
            }
        };

        let input_items: Vec<String> = if null_delimited {
            if input.is_empty() {
                Vec::new()
            } else {
                let mut v: Vec<String> = input.split('\0').map(|s| s.to_string()).collect();
                // A single trailing NUL is a terminator, not an empty record.
                if v.last().map(|s| s.is_empty()).unwrap_or(false) {
                    v.pop();
                }
                v
            }
        } else if replace_str.is_some() {
            input
                .lines()
                .map(|s| s.to_string())
                .filter(|s| !s.is_empty())
                .collect()
        } else {
            // Default: split on any whitespace, honoring quotes and backslashes
            // (GNU xargs semantics), so `'a b'` stays one argument.
            xargs_split(&input)
        };

        if input_items.is_empty() {
            return CommandOutput::success(String::new());
        }

        // Mobile (allow_subprocess=false): the parallel paths spawn external
        // processes (SIGSYS on Android). Fall back to the sequential in-process
        // path — same functionality, no spawn.
        if !self.allow_subprocess {
            parallel = None;
        }

        if let Some(ref rep) = replace_str {
            return exec_xargs_replace(self, &target_cmd, rep, &input_items, parallel, verbose);
        }

        // Group items into per-invocation chunks: `-L` groups input LINES,
        // otherwise `-n` groups N items; `-s` further bounds the command length.
        let mut chunks: Vec<Vec<String>> = if let Some(l) = max_lines {
            let per_line: Vec<Vec<String>> = input
                .lines()
                .map(xargs_split)
                .filter(|v| !v.is_empty())
                .collect();
            per_line
                .chunks(l.max(1))
                .map(|g| g.iter().flatten().cloned().collect())
                .collect()
        } else {
            let n_per = max_args.unwrap_or(input_items.len()).max(1);
            input_items.chunks(n_per).map(|c| c.to_vec()).collect()
        };
        if let Some(limit) = max_chars {
            let base: usize = target_cmd.iter().map(|s| s.len() + 1).sum();
            let mut limited: Vec<Vec<String>> = Vec::new();
            for ch in chunks {
                let mut cur: Vec<String> = Vec::new();
                let mut len = base;
                for item in ch {
                    if !cur.is_empty() && len + item.len() + 1 > limit {
                        limited.push(std::mem::take(&mut cur));
                        len = base;
                    }
                    len += item.len() + 1;
                    cur.push(item);
                }
                if !cur.is_empty() {
                    limited.push(cur);
                }
            }
            chunks = limited;
        }
        let refs: Vec<&[String]> = chunks.iter().map(|c| c.as_slice()).collect();

        exec_xargs_chunks(self, &target_cmd, &refs, parallel, verbose)
    }
}

fn build_command_with_replace(
    target_cmd: &[String],
    replacement: &str,
    replace_str: &str,
) -> Vec<String> {
    target_cmd
        .iter()
        .map(|arg| arg.replace(replace_str, replacement))
        .collect()
}

fn exec_xargs_replace(
    shell: &mut Shell,
    target_cmd: &[String],
    replace_str: &str,
    items: &[String],
    parallel: Option<usize>,
    verbose: bool,
) -> CommandOutput {
    let max_parallel = parallel.unwrap_or(1);

    if max_parallel <= 1 {
        let mut combined_stdout = String::new();
        let mut combined_stderr = String::new();
        let mut last_exit = 0i32;

        for item in items {
            let cmd = build_command_with_replace(target_cmd, item, replace_str);
            if verbose {
                combined_stderr.push_str(&cmd.join(" "));
                combined_stderr.push('\n');
            }
            let out = shell.execute(
                &cmd[0],
                &cmd[1..].iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                None,
            );
            combined_stdout.push_str(&out.stdout);
            combined_stderr.push_str(&out.stderr);
            if out.exit_code != 0 {
                last_exit = out.exit_code;
                if out.exit_code == 255 {
                    break;
                }
            }
        }

        return CommandOutput {
            stdout: combined_stdout,
            stderr: combined_stderr,
            exit_code: last_exit,
        };
    }

    run_parallel_replace(shell, target_cmd, replace_str, items, max_parallel, verbose)
}

fn exec_xargs_chunks(
    shell: &mut Shell,
    target_cmd: &[String],
    chunks: &[&[String]],
    parallel: Option<usize>,
    verbose: bool,
) -> CommandOutput {
    let max_parallel = parallel.unwrap_or(1);

    if max_parallel <= 1 {
        let mut combined_stdout = String::new();
        let mut combined_stderr = String::new();
        let mut last_exit = 0i32;

        for chunk in chunks {
            let cmd_name = &target_cmd[0];
            let mut all_args: Vec<&str> = target_cmd[1..].iter().map(|s| s.as_str()).collect();
            all_args.extend(chunk.iter().map(|s| s.as_str()));

            if verbose {
                let mut full = vec![cmd_name.as_str()];
                full.extend(&all_args);
                combined_stderr.push_str(&full.join(" "));
                combined_stderr.push('\n');
            }

            let out = shell.execute(cmd_name, &all_args, None);
            combined_stdout.push_str(&out.stdout);
            combined_stderr.push_str(&out.stderr);
            if out.exit_code != 0 {
                last_exit = out.exit_code;
                if out.exit_code == 255 {
                    break;
                }
            }
        }

        return CommandOutput {
            stdout: combined_stdout,
            stderr: combined_stderr,
            exit_code: last_exit,
        };
    }

    run_parallel_chunks(shell, target_cmd, chunks, max_parallel, verbose)
}

fn run_parallel_replace(
    _shell: &Shell,
    target_cmd: &[String],
    replace_str: &str,
    items: &[String],
    max_parallel: usize,
    verbose: bool,
) -> CommandOutput {
    let cmd_clone = target_cmd.to_vec();
    let rep_clone = replace_str.to_string();
    let items_clone: Vec<String> = items.iter().map(|s| s.clone()).collect();

    let mut outputs: Vec<(String, String, i32)> = Vec::new();

    {
        let mut handles = Vec::new();
        let items_chunks: Vec<Vec<String>> = items_clone
            .chunks((items_clone.len() + max_parallel - 1) / max_parallel)
            .map(|c| c.to_vec())
            .collect();

        for chunk in items_chunks {
            let cmd = cmd_clone.clone();
            let rep = rep_clone.clone();
            let handle = std::thread::spawn(move || {
                let mut results = Vec::new();
                for item in &chunk {
                    let full_cmd = build_command_with_replace(&cmd, item, &rep);
                    let trace = if verbose {
                        format!("{}\n", full_cmd.join(" "))
                    } else {
                        String::new()
                    };
                    // In threads, we can't call shell.execute because it borrows mutably
                    // So use std::process::Command directly
                    let result = std::process::Command::new(&full_cmd[0])
                        .args(&full_cmd[1..])
                        .output();
                    match result {
                        Ok(out) => {
                            results.push((
                                String::from_utf8_lossy(&out.stdout).to_string(),
                                format!("{}{}", trace, String::from_utf8_lossy(&out.stderr)),
                                out.status.code().unwrap_or(1),
                            ));
                        }
                        Err(e) => {
                            results.push((
                                String::new(),
                                format!("{}xargs: {}: {}\n", trace, full_cmd[0], e),
                                127,
                            ));
                        }
                    }
                }
                results
            });
            handles.push(handle);
        }

        for handle in handles {
            if let Ok(results) = handle.join() {
                outputs.extend(results);
            }
        }
    }

    let mut combined_stdout = String::new();
    let mut combined_stderr = String::new();
    let mut last_exit = 0i32;

    for (so, se, ec) in outputs {
        combined_stdout.push_str(&so);
        combined_stderr.push_str(&se);
        if ec != 0 {
            last_exit = ec;
        }
    }

    CommandOutput {
        stdout: combined_stdout,
        stderr: combined_stderr,
        exit_code: if last_exit != 0 { 123 } else { 0 },
    }
}

fn run_parallel_chunks(
    _shell: &Shell,
    target_cmd: &[String],
    chunks: &[&[String]],
    max_parallel: usize,
    verbose: bool,
) -> CommandOutput {
    let cmd_clone = target_cmd.to_vec();
    let chunks_clone: Vec<Vec<String>> = chunks
        .iter()
        .map(|c| c.iter().map(|s| s.to_string()).collect())
        .collect();

    let mut outputs: Vec<(String, String, i32)> = Vec::new();

    {
        let mut handles = Vec::new();
        let batch_size = (chunks_clone.len() + max_parallel - 1) / max_parallel;

        for batch in chunks_clone.chunks(batch_size) {
            let cmd = cmd_clone.clone();
            let batch_owned: Vec<Vec<String>> = batch.iter().map(|c| c.clone()).collect();
            let handle = std::thread::spawn(move || {
                let mut results = Vec::new();
                for chunk in &batch_owned {
                    let full_cmd = &cmd[0];
                    let mut all_args: Vec<String> = cmd[1..].to_vec();
                    all_args.extend(chunk.iter().cloned());
                    let trace = if verbose {
                        format!("{} {}\n", full_cmd, all_args.join(" "))
                    } else {
                        String::new()
                    };
                    let result = std::process::Command::new(full_cmd)
                        .args(&all_args)
                        .output();
                    match result {
                        Ok(out) => {
                            results.push((
                                String::from_utf8_lossy(&out.stdout).to_string(),
                                format!("{}{}", trace, String::from_utf8_lossy(&out.stderr)),
                                out.status.code().unwrap_or(1),
                            ));
                        }
                        Err(e) => {
                            results.push((
                                String::new(),
                                format!("{}xargs: {}: {}\n", trace, full_cmd, e),
                                127,
                            ));
                        }
                    }
                }
                results
            });
            handles.push(handle);
        }

        for handle in handles {
            if let Ok(results) = handle.join() {
                outputs.extend(results);
            }
        }
    }

    let mut combined_stdout = String::new();
    let mut combined_stderr = String::new();
    let mut last_exit = 0i32;

    for (so, se, ec) in outputs {
        combined_stdout.push_str(&so);
        combined_stderr.push_str(&se);
        if ec != 0 {
            last_exit = ec;
        }
    }

    CommandOutput {
        stdout: combined_stdout,
        stderr: combined_stderr,
        exit_code: if last_exit != 0 { 123 } else { 0 },
    }
}

/// GNU-xargs-style input splitting: whitespace (space/tab/newline) separates
/// arguments, but single/double quotes group, and backslash escapes the next
/// char. `''` yields an empty argument.
fn xargs_split(input: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut has = false;
    let mut in_sq = false;
    let mut in_dq = false;
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if in_sq {
            if c == '\'' {
                in_sq = false;
            } else {
                current.push(c);
            }
        } else if in_dq {
            if c == '"' {
                in_dq = false;
            } else if c == '\\' {
                if let Some(n) = chars.next() {
                    current.push(n);
                }
            } else {
                current.push(c);
            }
        } else {
            match c {
                '\'' => {
                    in_sq = true;
                    has = true;
                }
                '"' => {
                    in_dq = true;
                    has = true;
                }
                '\\' => {
                    if let Some(n) = chars.next() {
                        current.push(n);
                        has = true;
                    }
                }
                ' ' | '\t' | '\n' | '\r' => {
                    if has {
                        words.push(std::mem::take(&mut current));
                        has = false;
                    }
                }
                _ => {
                    current.push(c);
                    has = true;
                }
            }
        }
    }
    if has {
        words.push(current);
    }
    words
}

#[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_xargs_test_{}_{}", std::process::id(), n));
        let _ = fs::remove_dir_all(&dir);
        Vfs::new(dir).unwrap()
    }

    fn mk_shell() -> Shell {
        let s = Shell::new(setup_vfs());
        s
    }

    #[test]
    fn test_xargs_basic() {
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&["echo"], Some("hello world foo"));
        assert!(out.stdout.contains("hello"));
        assert!(out.stdout.contains("world"));
        assert!(out.stdout.contains("foo"));
        assert_eq!(out.exit_code, 0);
    }

    #[test]
    fn test_xargs_n() {
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&["-n", "1", "echo"], Some("hello world"));
        assert_eq!(out.stdout.trim().lines().count(), 2);
        assert_eq!(out.exit_code, 0);
    }

    #[test]
    fn test_xargs_null() {
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&["-0", "echo"], Some("hello\0world\0"));
        assert!(out.stdout.contains("hello"));
        assert!(out.stdout.contains("world"));
        assert_eq!(out.exit_code, 0);
    }

    #[test]
    fn test_xargs_replace() {
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&["-I{}", "echo", "{}", "suffix"], Some("hello\nworld\n"));
        assert!(out.stdout.contains("hello suffix"));
        assert!(out.stdout.contains("world suffix"));
        assert_eq!(out.exit_code, 0);
    }

    #[test]
    fn test_xargs_no_input() {
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&["echo"], None);
        assert_ne!(out.exit_code, 0);
    }

    #[test]
    fn test_xargs_default_echo() {
        // GNU xargs defaults to `echo` when no command is given.
        let mut shell = mk_shell();
        let out = shell.cmd_xargs(&[], Some("input"));
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("input"), "stdout={:?}", out.stdout);
    }

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

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