Shell: Stuck on Single quotes #NI6

In my function for parsing the input, in my current function below, there is no extra space that will be added if we’ve finished taking in the characters with single input, but we see a whitespace on the failing test.

pub fn parse_input(input: &str) -> Vec<String> {
    let mut args: Vec<String> = Vec::new();
    let mut extracted_quoted_strings = HashSet::new();
    let mut current_arg_buffer = String::new();
    let mut in_single_quote = false;

    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == SINGLE_QUOTE {
            if in_single_quote {
                args.push(current_arg_buffer.clone());
                extracted_quoted_strings.insert(current_arg_buffer.clone());
                current_arg_buffer.clear();
                in_single_quote = false;
            } else {
                if !current_arg_buffer.is_empty() {
                    args.push(current_arg_buffer.clone());
                    current_arg_buffer.clear();
                }
                in_single_quote = true;
            }
        } else if ch.is_whitespace() && !in_single_quote {
            if !current_arg_buffer.is_empty() {
                args.push(current_arg_buffer.clone());
                current_arg_buffer.clear();
            }
        } else {
            current_arg_buffer.push(ch);
        }
    }

    if !current_arg_buffer.is_empty() {
        if in_single_quote {
            args.push(current_arg_buffer.clone());
            extracted_quoted_strings.insert(current_arg_buffer.clone());
        } else {
            args.push(current_arg_buffer.clone());
        }
    }

    println!("{:?}", extracted_quoted_strings);

    args
}

My code is on github GitHub - Rioba-Ian/codecrafters-shell-rust

Thank you and I appreciate any help or insight I can get

The test is telling you what is wrong. You are parsing 'hello''example' as two arguments.

In Bash “arguments” are referred to as tokens. They are separated by “metacharacters”. When you find the ending single quote you think you are done, so you add the text between ' as its own element to your argument list. This is wrong because we haven’t reached a metacharacter yet (like an unquoted space). Same thing with double quotes .

3 Likes