feat(builtins): add exit builtin

Signed-off-by: Charlotte Meyer <dev@buffet.sh>
This commit is contained in:
buffet 2022-10-26 14:24:05 +00:00
parent c3bcdf5cd8
commit c0e5aa2308
3 changed files with 13 additions and 6 deletions

View file

@ -9,13 +9,8 @@ fn main() {
shell.builtins_mut().add_defaults(); shell.builtins_mut().add_defaults();
let mut exit_code = Status::SUCCESS; let mut exit_code = Status::SUCCESS;
loop { while shell.is_running() {
let prog = readline("> ").unwrap(); let prog = readline("> ").unwrap();
if prog.trim() == "exit" {
break;
}
let ast = Code::try_from(prog.as_ref()).unwrap(); let ast = Code::try_from(prog.as_ref()).unwrap();
exit_code = shell.run(&ast).unwrap(); exit_code = shell.run(&ast).unwrap();
} }

View file

@ -12,6 +12,11 @@ pub struct Builtin {
pub fun: fn(shell: &mut Shell, args: &[Cow<OsStr>]), pub fun: fn(shell: &mut Shell, args: &[Cow<OsStr>]),
} }
#[builtin(description = "exit the shell", nofork)]
pub fn exit(shell: &mut Shell, _args: &[Cow<OsStr>]) {
shell.is_running = false;
}
#[builtin(description = "prints help for different builtins")] #[builtin(description = "prints help for different builtins")]
pub fn help(shell: &mut Shell, _args: &[Cow<OsStr>]) { pub fn help(shell: &mut Shell, _args: &[Cow<OsStr>]) {
println!( println!(
@ -48,6 +53,7 @@ impl BuiltinMap {
/// Add default builtins. /// Add default builtins.
pub fn add_defaults(&mut self) { pub fn add_defaults(&mut self) {
self.add(exit);
self.add(help); self.add(help);
} }
} }

View file

@ -66,6 +66,7 @@ pub enum RuntimeError {
} }
pub struct Shell { pub struct Shell {
is_running: bool,
builtins: BuiltinMap, builtins: BuiltinMap,
} }
@ -79,10 +80,15 @@ impl Shell {
} }
Ok(Shell { Ok(Shell {
is_running: true,
builtins: Default::default(), builtins: Default::default(),
}) })
} }
pub fn is_running(&self) -> bool {
self.is_running
}
pub fn run<'a>(&mut self, code: &'a ast::Code) -> Result<Status, RuntimeError> { pub fn run<'a>(&mut self, code: &'a ast::Code) -> Result<Status, RuntimeError> {
let mut last_status = Status::SUCCESS; let mut last_status = Status::SUCCESS;