From 1f33402a42cbe8b674068b91a5e002733fdfffa2 Mon Sep 17 00:00:00 2001 From: mars Date: Wed, 12 Apr 2023 17:27:01 -0400 Subject: [PATCH] Parse commands as strings + wq --- src/main.rs | 51 +++++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/main.rs b/src/main.rs index a9d82c9..5b64678 100644 --- a/src/main.rs +++ b/src/main.rs @@ -333,39 +333,42 @@ impl State { Ok(()) } + fn write_command(&mut self, command: &str, args: &[&str]) -> std::result::Result<(), String> { + let handle = match self.file.clone() { + Some(handle) => handle, + None => match args.get(0) { + Some(part) => OsString::from(part), + None => { + return Err(format!("{}: No file name.", command)); + } + }, + }; + + self.write_buffer(handle).map_err(|err| format!("{}", err)) + } + fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> { let command_parts = command.split(' ').collect::>(); - let commands = match command_parts.get(0) { - Some(parts) => parts.chars().collect::>(), + let command = match command_parts.get(0) { + Some(command) => command, None => return Ok(()), }; - for command in commands.clone().iter() { - match command { - 'q' => self.quit = true, - 'w' => { - let handle: OsString; + let args = &command_parts[1..]; - if let Some(part) = self.file.clone() { - handle = part; - } else { - handle = match command_parts.get(1) { - Some(part) => OsString::from(part), - None => { - return Err(format!("{}: No file name.", command)); - } - }; - } - - self.write_buffer(handle) - .map_err(|err| format!("{}", err))?; - } - command => { - return Err(format!("{}: Unrecognized command.", command)); - } + match *command { + "q" => self.quit = true, + "w" => return self.write_command(command, args), + "wq" => { + self.write_command(command, args)?; + self.quit = true; + } + command => { + return Err(format!("{}: Unrecognized command.", command)); } } + Ok(()) }