From 4eb0c39a6687c883af1731c3fd89accbcf004055 Mon Sep 17 00:00:00 2001 From: jasmine Date: Sat, 7 Jun 2025 15:04:26 +0800 Subject: [PATCH] refactor --- src/core.rs | 38 +++++++++++++++++++++++++++++++++++++ src/main.rs | 54 +++++++++-------------------------------------------- 2 files changed, 47 insertions(+), 45 deletions(-) create mode 100644 src/core.rs diff --git a/src/core.rs b/src/core.rs new file mode 100644 index 0000000..7e3c3a6 --- /dev/null +++ b/src/core.rs @@ -0,0 +1,38 @@ +use std::io::{self, Write}; +use std::process::Command; + +pub fn display_prompt() { + print!("> "); + io::stdout().flush().expect("unable to flush buffer"); +} + +pub fn get_input() -> String { + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("failed to readline"); + // Remove newline character from the input. + input.pop(); + input +} + +pub fn parse_input(s: &str) -> Vec<&str> { + s.split_whitespace().collect() +} + +pub fn get_command(tokens: Vec<&str>) -> &str { + tokens[0] +} + +pub fn get_args(tokens: Vec<&str>) -> Vec<&str> { + tokens[1..].to_vec() +} + +pub fn execute(cmd: &str, args: Vec<&str>) { + let status = Command::new(cmd) + .args(args) + .status() + .expect("failed to execute process"); + + assert!(status.success()); +} diff --git a/src/main.rs b/src/main.rs index 6538f91..60a9dd9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,52 +1,16 @@ -use std::io::{self, Write}; -use std::process::Command; - -fn display_prompt() { - print!("> "); - io::stdout().flush().expect("unable to flush buffer"); -} - -fn get_input() -> String { - let mut input = String::new(); - io::stdin() - .read_line(&mut input) - .expect("failed to readline"); - // Remove newline character from the input. - input.pop(); - input -} - -fn parse_input(s: &str) -> Vec<&str> { - s.split_whitespace().collect() -} - -fn get_command(tokens: Vec<&str>) -> &str { - tokens[0] -} - -fn get_args(tokens: Vec<&str>) -> Vec<&str> { - tokens[1..].to_vec() -} - -fn run_command(cmd: &str, args: Vec<&str>) { - let status = Command::new(cmd) - .args(args) - .status() - .expect("failed to execute process"); - - assert!(status.success()); -} +mod core; +mod inbuilt; fn main() { loop { // Display the prompt for the user. - display_prompt(); + core::display_prompt(); // Get the users input. - let input = get_input(); + let input = core::get_input(); // Parse the users input and create tokens. - let tokens = parse_input(&input); + let tokens = core::parse_input(&input); // If the user enters empty input don't execute the command. if tokens.is_empty() { @@ -54,10 +18,10 @@ fn main() { } // Convert our tokens to our command and arguments. - let cmd = get_command(tokens.clone()); - let args = get_args(tokens); + let cmd = core::get_command(tokens.clone()); + let args = core::get_args(tokens); - // Run the command and arguments. - run_command(cmd, args); + // Execute command and argument. + core::execute(cmd, args); } }