Simplify split_args code, add a unit test for it and run it into CI

This commit is contained in:
Guillaume Gomez 2023-12-16 17:39:58 +01:00
parent db9b932314
commit 95dfe5ec90
2 changed files with 68 additions and 38 deletions

View File

@ -131,3 +131,12 @@ jobs:
steps:
- uses: actions/checkout@v3
- run: python tools/check_intrinsics_duplicates.py
build_system:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Test build system
run: |
cd build_system
cargo test

View File

@ -306,46 +306,44 @@ pub fn split_args(args: &str) -> Result<Vec<String>, String> {
let args = args.trim();
let mut iter = args.char_indices().peekable();
while iter.peek().is_some() {
while let Some((pos, c)) = iter.next() {
if c == ' ' {
out.push(args[start..pos].to_string());
let mut found_start = false;
while let Some((pos, c)) = iter.peek() {
if *c != ' ' {
start = *pos;
found_start = true;
break;
} else {
iter.next();
}
while let Some((pos, c)) = iter.next() {
if c == ' ' {
out.push(args[start..pos].to_string());
let mut found_start = false;
while let Some((pos, c)) = iter.peek() {
if *c != ' ' {
start = *pos;
found_start = true;
break;
} else {
iter.next();
}
if !found_start {
return Ok(out);
}
} else if c == '"' || c == '\'' {
let end = c;
let mut found_end = false;
while let Some((_, c)) = iter.next() {
if c == end {
found_end = true;
break;
} else if c == '\\' {
// We skip the escaped character.
iter.next();
}
}
if !found_end {
return Err(format!(
"Didn't find `{}` at the end of `{}`",
end,
&args[start..]
));
}
} else if c == '\\' {
// We skip the escaped character.
iter.next();
}
if !found_start {
return Ok(out);
}
} else if c == '"' || c == '\'' {
let end = c;
let mut found_end = false;
while let Some((_, c)) = iter.next() {
if c == end {
found_end = true;
break;
} else if c == '\\' {
// We skip the escaped character.
iter.next();
}
}
if !found_end {
return Err(format!(
"Didn't find `{}` at the end of `{}`",
end,
&args[start..]
));
}
} else if c == '\\' {
// We skip the escaped character.
iter.next();
}
}
let s = args[start..].trim();
@ -364,3 +362,26 @@ pub fn remove_file<P: AsRef<Path>>(file_path: &P) -> Result<(), String> {
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_args() {
// Missing `"` at the end.
assert!(split_args("\"tada").is_err());
// Missing `'` at the end.
assert!(split_args("\'tada").is_err());
assert_eq!(
split_args("a \"b\" c"),
Ok(vec!["a".to_string(), "\"b\"".to_string(), "c".to_string()])
);
// Trailing whitespace characters.
assert_eq!(
split_args(" a \"b\" c "),
Ok(vec!["a".to_string(), "\"b\"".to_string(), "c".to_string()])
);
}
}