Shell Words Tokenizer

Split a command line into arguments with single quotes, double quotes, escapes, and explicit errors for unterminated quotes.

RustSecurity Boundaries

Code

snippet
#[derive(Clone, Copy, PartialEq)]
enum Quote {
    None,
    Single,
    Double,
}

fn split_shell_words(input: &str) -> Result<Vec<String>, String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut started = false;
    let mut quote = Quote::None;
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        match (quote, ch) {
            (Quote::None, '\'') => {
                quote = Quote::Single;
                started = true;
            }
            (Quote::None, '"') => {
                quote = Quote::Double;
                started = true;
            }
            (Quote::None, '\\') => match chars.next() {
                Some(escaped) => {
                    current.push(escaped);
                    started = true;
                }
                None => return Err("trailing backslash".to_string()),
            },
            (Quote::None, whitespace) if whitespace.is_whitespace() => {
                if started {
                    words.push(std::mem::take(&mut current));
                    started = false;
                }
            }
            (Quote::Single, '\'') => quote = Quote::None,
            (Quote::Double, '"') => quote = Quote::None,
            (Quote::Double, '\\') => match chars.next() {
                Some(escaped) => current.push(escaped),
                None => return Err("trailing backslash".to_string()),
            },
            (_, character) => {
                current.push(character);
                started = true;
            }
        }
    }

    if quote != Quote::None {
        return Err("unterminated quote".to_string());
    }
    if started {
        words.push(current);
    }
    Ok(words)
}

fn main() {
    let command = r#"git commit -m "fix: handle \"quoted\" text" --no-verify"#;
    println!("{:?}", split_shell_words(command));
    println!("{:?}", split_shell_words("echo 'literal value'"));
    println!("{:?}", split_shell_words("run \"a b\" c"));
    println!("error: {:?}", split_shell_words("echo 'unterminated"));
}