From 1257b0bd2eabede7ee330243a241e2849b6115cd Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sat, 25 Dec 2021 18:50:30 -0500 Subject: refactor --- Cargo.lock | 1 + Cargo.toml | 1 + src/state/history/builtins.rs | 19 +++++++++++++++---- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fbde278..17eac54 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -466,6 +466,7 @@ dependencies = [ "hostname", "libc", "nix", + "once_cell", "pest", "pest_derive", "pty-process", diff --git a/Cargo.toml b/Cargo.toml index 18b07ed..1942ac4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ futures-lite = "1.12.0" hostname = "0.3.1" libc = "0.2.112" nix = "0.23.0" +once_cell = "1.9.0" pest = "2.1.3" pest_derive = "2.1.0" pty-process = { version = "0.2.0", features = ["backend-async-std"] } diff --git a/src/state/history/builtins.rs b/src/state/history/builtins.rs index 2b2084b..dd293a1 100644 --- a/src/state/history/builtins.rs +++ b/src/state/history/builtins.rs @@ -1,12 +1,23 @@ use std::os::unix::process::ExitStatusExt as _; +type Builtin = &'static (dyn Fn(&crate::parse::Exe) -> std::process::ExitStatus + + Sync + + Send); + +// i don't know how to do this without an as conversion +#[allow(clippy::as_conversions)] +static BUILTINS: once_cell::sync::Lazy< + std::collections::HashMap<&'static str, Builtin>, +> = once_cell::sync::Lazy::new(|| { + let mut builtins = std::collections::HashMap::new(); + builtins.insert("cd", &cd as Builtin); + builtins +}); + pub fn run( exe: &crate::parse::Exe, ) -> Option { - match exe.exe() { - "cd" => Some(cd(exe)), - _ => None, - } + BUILTINS.get(exe.exe()).map(|f| f(exe)) } fn cd(exe: &crate::parse::Exe) -> async_std::process::ExitStatus { -- cgit v1.2.3-54-g00ecf