2022-10-24 19:27:04 +00:00
|
|
|
use std::{borrow::Cow, collections::HashMap, ffi::OsStr};
|
2022-10-20 13:06:53 +00:00
|
|
|
|
2022-10-21 17:29:42 +00:00
|
|
|
use oyster_builtin_proc::builtin;
|
|
|
|
|
2022-10-20 13:06:53 +00:00
|
|
|
use crate::Shell;
|
|
|
|
|
|
|
|
#[derive(Clone, Copy)]
|
|
|
|
pub struct Builtin {
|
|
|
|
pub name: &'static str,
|
|
|
|
pub description: &'static str,
|
2022-10-24 19:27:04 +00:00
|
|
|
pub fun: fn(shell: &mut Shell, args: &[Cow<OsStr>]),
|
2022-10-20 13:06:53 +00:00
|
|
|
}
|
|
|
|
|
2022-10-21 17:29:42 +00:00
|
|
|
#[builtin(description = "prints help for different builtins")]
|
2022-10-24 19:27:04 +00:00
|
|
|
fn help(shell: &mut Shell, _args: &[Cow<OsStr>]) {
|
2022-10-21 17:29:42 +00:00
|
|
|
println!(
|
|
|
|
r"oyster help:
|
2022-10-20 13:06:53 +00:00
|
|
|
|
|
|
|
These are the loaded builtins:"
|
2022-10-21 17:29:42 +00:00
|
|
|
);
|
2022-10-20 13:06:53 +00:00
|
|
|
|
2022-10-21 17:29:42 +00:00
|
|
|
for builtin in shell.builtins().iter() {
|
|
|
|
println!(" {: <8} {}", builtin.name, builtin.description);
|
2022-10-20 13:06:53 +00:00
|
|
|
}
|
2022-10-21 17:29:42 +00:00
|
|
|
}
|
2022-10-20 13:06:53 +00:00
|
|
|
|
|
|
|
/// Used to register and retrieve builtins.
|
2022-10-24 19:27:04 +00:00
|
|
|
/// Builtin names gotta be valid unicode.
|
2022-10-20 13:06:53 +00:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct BuiltinMap(HashMap<&'static str, Builtin>);
|
|
|
|
|
|
|
|
impl BuiltinMap {
|
|
|
|
/// Register a new builtin.
|
|
|
|
pub fn add(&mut self, builtin: Builtin) {
|
|
|
|
self.0.insert(builtin.name, builtin);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get a builtin with a given name, if it exists.
|
|
|
|
pub fn get(&self, name: &str) -> Option<&Builtin> {
|
|
|
|
self.0.get(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an iterator over all currently registered builtins.
|
|
|
|
pub fn iter(&self) -> impl Iterator<Item = &Builtin> {
|
|
|
|
self.0.iter().map(|(_, v)| v)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add default builtins.
|
|
|
|
pub fn add_defaults(&mut self) {
|
2022-10-21 17:29:42 +00:00
|
|
|
self.add(help);
|
2022-10-20 13:06:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Shell {
|
|
|
|
/// Retrieve builtins.
|
|
|
|
pub fn builtins(&self) -> &BuiltinMap {
|
|
|
|
&self.builtins
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieve builtins, mutably.
|
|
|
|
pub fn builtins_mut(&mut self) -> &mut BuiltinMap {
|
|
|
|
&mut self.builtins
|
|
|
|
}
|
|
|
|
}
|