fastshell 0.3.6

Lightweight Bash + Python runtime SDK for mobile AI agents
Documentation
// 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 CUT_HELP_TEXT: &str = "\
cut: remove sections from each line
Usage: cut [OPTIONS] [FILE...]
Options:
  -d DELIM    Use DELIM instead of TAB
  -f LIST     Select only these fields
  -c LIST     Select only these characters
  --complement  Select complement of field/char set
  -h, --help  Show this help message
";

impl Shell {
    pub fn cmd_cut(&self, args: &[&str], stdin: Option<&str>) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(CUT_HELP_TEXT.to_string());
        }
        let mut delimiter = '\t';
        let mut fields: Vec<FieldRange> = Vec::new();
        let mut char_mode = false;
        let mut complement = false;
        let mut only_delimited = false;
        let mut output_delimiter: Option<String> = None;
        let mut files = Vec::new();

        let mut i = 0;
        while i < args.len() {
            match args[i] {
                "-d" => {
                    if i + 1 < args.len() {
                        delimiter = args[i + 1].chars().next().unwrap_or('\t');
                        i += 1;
                    }
                }
                "-f" => {
                    if i + 1 < args.len() {
                        fields = parse_field_spec(args[i + 1]);
                        i += 1;
                    }
                }
                "-c" | "-b" => {
                    if i + 1 < args.len() {
                        fields = parse_field_spec(args[i + 1]);
                        char_mode = true;
                        i += 1;
                    }
                }
                "-s" | "--only-delimited" => only_delimited = true,
                "--complement" => complement = true,
                "--output-delimiter" => {
                    if i + 1 < args.len() {
                        output_delimiter = Some(args[i + 1].to_string());
                        i += 1;
                    }
                }
                arg if arg.starts_with("--output-delimiter=") => {
                    output_delimiter = Some(arg["--output-delimiter=".len()..].to_string());
                }
                arg if arg.starts_with("-d") && arg.len() > 2 => {
                    delimiter = arg[2..].chars().next().unwrap_or('\t');
                }
                arg if arg.starts_with("-f") && arg.len() > 2 => {
                    fields = parse_field_spec(&arg[2..]);
                }
                arg if (arg.starts_with("-c") || arg.starts_with("-b")) && arg.len() > 2 => {
                    fields = parse_field_spec(&arg[2..]);
                    char_mode = true;
                }
                arg if !arg.starts_with('-') => files.push(arg.to_string()),
                _ => crate::warn!("cut: warning: unsupported option '{}'", args[i]),
            }
            i += 1;
        }

        if fields.is_empty() {
            return CommandOutput::error("cut: missing field list\n".to_string(), 1);
        }

        let input = if files.is_empty() {
            match stdin {
                Some(s) => s.to_string(),
                None => return CommandOutput::error("cut: missing input\n".to_string(), 1),
            }
        } else {
            let mut content = String::new();
            for file in &files {
                match self.read_text_lossy(file) {
                    Ok(c) => content.push_str(&c),
                    Err(e) => return CommandOutput::error(format!("cut: {}: {}\n", file, e), 1),
                }
            }
            content
        };

        let mut output = String::new();
        let out_delim = output_delimiter.unwrap_or_else(|| delimiter.to_string());
        for line in input.lines() {
            if only_delimited && !line.contains(delimiter) {
                continue;
            }
            if char_mode {
                let chars: Vec<char> = line.chars().collect();
                let total = chars.len();
                let mut selected = Vec::new();
                for range in &fields {
                    let start = range.start.saturating_sub(1);
                    let end = match range.end {
                        Some(e) => (e.saturating_sub(1)).min(total.saturating_sub(1)),
                        None => total.saturating_sub(1),
                    };
                    if start <= end && start < total {
                        for idx in start..=end {
                            selected.push(idx);
                        }
                    }
                }
                if complement {
                    let mut result = String::new();
                    for idx in 0..total {
                        if !selected.contains(&idx) {
                            result.push(chars[idx]);
                        }
                    }
                    output.push_str(&result);
                } else {
                    for idx in selected {
                        output.push(chars[idx]);
                    }
                }
            } else {
                let cols: Vec<&str> = line.split(delimiter).collect();
                let total_cols = cols.len();
                let mut parts = Vec::new();
                for range in &fields {
                    let start = range.start.saturating_sub(1);
                    let end = match range.end {
                        Some(e) => (e.saturating_sub(1)).min(total_cols.saturating_sub(1)),
                        None => total_cols.saturating_sub(1),
                    };
                    if start <= end && start < total_cols {
                        for idx in start..=end {
                            parts.push(idx);
                        }
                    }
                }
                if complement {
                    let mut selected: Vec<bool> = vec![false; total_cols];
                    for &idx in &parts {
                        selected[idx] = true;
                    }
                    let mut result_parts = Vec::new();
                    for idx in 0..total_cols {
                        if !selected[idx] {
                            result_parts.push(cols[idx].to_string());
                        }
                    }
                    if !result_parts.is_empty() {
                        output.push_str(&result_parts.join(&out_delim));
                    }
                } else if !parts.is_empty() {
                    let mut result_parts = Vec::new();
                    for &idx in &parts {
                        result_parts.push(cols[idx].to_string());
                    }
                    output.push_str(&result_parts.join(&out_delim));
                }
            }
            output.push('\n');
        }

        CommandOutput::success(output)
    }
}

struct FieldRange {
    start: usize,
    end: Option<usize>,
}

fn parse_field_spec(spec: &str) -> Vec<FieldRange> {
    let mut fields = Vec::new();
    for part in spec.split(',') {
        let part = part.trim();
        if part == "-" {
            continue;
        }
        if part.contains('-') {
            let mut range = part.splitn(2, '-');
            let start_str = range.next().unwrap_or("");
            let end_str = range.next().unwrap_or("");
            let start: usize = if start_str.is_empty() {
                1
            } else {
                start_str.parse().unwrap_or(1)
            };
            let end: Option<usize> = if end_str.is_empty() {
                None
            } else {
                Some(end_str.parse().unwrap_or(1))
            };
            fields.push(FieldRange { start, end });
        } else {
            let n: usize = part.parse().unwrap_or(1);
            fields.push(FieldRange {
                start: n,
                end: Some(n),
            });
        }
    }
    fields
}

#[cfg(test)]
mod tests {
    use crate::shell::Shell;
    use crate::vfs::Vfs;

    fn mk_shell() -> Shell {
        use std::fs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_test_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4()
        ));
        let _ = fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        Shell::new(vfs)
    }

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

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