暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

command.rs 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. use std::ffi::OsString;
  2. use std::str::FromStr;
  3. use std::env;
  4. pub enum Command {
  5. Empty,
  6. Exit,
  7. Cd(Option<OsString>),
  8. }
  9. pub struct CommandNotFoundError;
  10. impl FromStr for Command {
  11. type Err = CommandNotFoundError;
  12. fn from_str(s: &str) -> Result<Self, Self::Err> {
  13. let mut parts = s.split_whitespace();
  14. match parts.next() {
  15. Some("exit") => {
  16. Ok(Command::Exit)
  17. },
  18. Some("cd") => {
  19. Ok(Command::parse_cd(parts.next()))
  20. },
  21. Some(cmd) => {
  22. //For use in next homework, to execute programs.
  23. let _ = cmd;
  24. Err(CommandNotFoundError)
  25. },
  26. None => {
  27. Ok(Command::Empty)
  28. },
  29. }
  30. }
  31. }
  32. impl Command {
  33. /// If the passed String exists, set the path of the Cd in the enum
  34. pub fn parse_cd(cmd: Option<&str>) -> Self {
  35. match cmd {
  36. None => Command::Cd(None),
  37. Some(dest) => Command::Cd(Some(OsString::from(dest))),
  38. }
  39. }
  40. pub fn exec_cd(&self) {
  41. if let Command::Cd(None) = *self {
  42. let possible_home = env::home_dir();
  43. if let Some(home) = possible_home {
  44. let home_path = home.as_path();
  45. let _ = env::set_current_dir(home_path);
  46. }
  47. }
  48. if let Command::Cd(Some(ref path)) = *self {
  49. match path.to_str() {
  50. Some(_) => {
  51. let _ = env::set_current_dir(path);
  52. },
  53. None => {},
  54. }
  55. }
  56. }
  57. }