|
1 | 1 | #[allow(unused_imports)] |
2 | 2 | use std::io::{self, Write}; |
3 | 3 |
|
| 4 | +const BUILT_IN_COMMANDS: [&str;3] = ["echo","exit","type"]; |
| 5 | + |
| 6 | +enum Command{ |
| 7 | + ExitCommand, |
| 8 | + EchoCommand {display_string:String}, |
| 9 | + TypeCommand {command_name: String}, |
| 10 | + CommandNotFound, |
| 11 | +} |
| 12 | + |
| 13 | +impl Command{ |
| 14 | + fn from_input(input:&str) -> Self { |
| 15 | + let input=input.trim(); |
| 16 | + if input == "exit" || input == "exit 0" { |
| 17 | + return Self::ExitCommand; |
| 18 | + }; |
| 19 | + if let Some(pos) = input.find("echo ") { |
| 20 | + if pos ==0{ |
| 21 | + return Self::EchoCommand{ |
| 22 | + display_string: input["echo ".len()..].to_string(), |
| 23 | + }; |
| 24 | + } |
| 25 | + } |
| 26 | + if let Some(pos) = input.find("type "){ |
| 27 | + if pos==0 { |
| 28 | + return Self::TypeCommand{ |
| 29 | + command_name: input["type ".len()..].to_string(), |
| 30 | + }; |
| 31 | + } |
| 32 | + } |
| 33 | + Self::CommandNotFound // we are returning this value |
| 34 | + } |
| 35 | + |
| 36 | +} |
| 37 | + |
4 | 38 | fn main() { |
5 | 39 | loop{ |
6 | 40 | print!("$ "); |
7 | 41 | io::stdout().flush().unwrap(); |
8 | 42 |
|
9 | | - let mut command = String::new(); |
10 | | - io::stdin().read_line(&mut command).unwrap(); |
11 | | - println!("{}: command not found",command.trim()); |
| 43 | + let mut input = String::new(); |
| 44 | + io::stdin().read_line(&mut input).unwrap(); |
| 45 | + |
| 46 | + //implementing internal built_in_commands |
| 47 | + let command = Command::from_input(&input); |
| 48 | + match command{ |
| 49 | + Command::ExitCommand => break, |
| 50 | + Command::EchoCommand {display_string} => println!("{}", display_string), |
| 51 | + Command::TypeCommand {command_name} => { |
| 52 | + if BUILT_IN_COMMANDS.contains(&command_name.as_str()){ |
| 53 | + println!("{} is a shell builtin",command_name); |
| 54 | + } else { |
| 55 | + println!("{}: command not found", command_name); |
| 56 | + } |
| 57 | + }, |
| 58 | + Command::CommandNotFound => println!("{} bruh command not found", input.trim()), |
| 59 | + } |
12 | 60 | } |
13 | 61 | } |
0 commit comments