You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.3 KiB

  1. use crate::error::ShellError;
  2. pub fn parse_line(line: &str) -> Result<(&str, Vec<String>), ShellError> {
  3. let (keyword, unparsed_args) = line.split_once(' ').unwrap_or((line, ""));
  4. if let Some(args) = shlex::split(unparsed_args) {
  5. Ok((keyword, args))
  6. } else {
  7. Err(ShellError::MalformedArgs(unparsed_args.to_string()))
  8. }
  9. }
  10. #[cfg(test)]
  11. mod tests {
  12. use super::*;
  13. #[test]
  14. fn test_parse_single() {
  15. assert_eq!(parse_line("keyword"), Ok(("keyword", vec![])))
  16. }
  17. #[test]
  18. fn test_parse_multiple() {
  19. assert_eq!(
  20. parse_line("keyword arg1 arg2"),
  21. Ok(("keyword", vec!["arg1".to_string(), "arg2".to_string()]))
  22. )
  23. }
  24. #[test]
  25. fn test_parse_complex() {
  26. assert_eq!(
  27. parse_line("keyword 'this is arg 1' arg2 \"arg3 \""),
  28. Ok((
  29. "keyword",
  30. vec![
  31. "this is arg 1".to_string(),
  32. "arg2".to_string(),
  33. "arg3 ".to_string()
  34. ]
  35. ))
  36. )
  37. }
  38. #[test]
  39. fn test_parse_malformed() {
  40. assert_eq!(
  41. parse_line("keyword \"malformed"),
  42. Err(ShellError::MalformedArgs("keyword \"malformed".to_string()))
  43. )
  44. }
  45. }