nushell/src/context.rs

51 lines
1.3 KiB
Rust
Raw Normal View History

2019-05-15 18:12:38 +02:00
use crate::prelude::*;
2019-05-16 02:21:46 +02:00
2019-05-15 18:12:38 +02:00
use std::error::Error;
2019-05-22 09:12:03 +02:00
use std::sync::Arc;
2019-05-15 18:12:38 +02:00
pub struct Context {
2019-05-23 06:30:43 +02:00
commands: indexmap::IndexMap<String, Arc<dyn Command>>,
crate host: Arc<Mutex<dyn Host>>,
crate env: Arc<Mutex<Environment>>,
2019-05-15 18:12:38 +02:00
}
impl Context {
crate fn basic() -> Result<Context, Box<Error>> {
Ok(Context {
2019-05-16 00:58:44 +02:00
commands: indexmap::IndexMap::new(),
host: Arc::new(Mutex::new(crate::env::host::BasicHost)),
env: Arc::new(Mutex::new(Environment::basic()?)),
2019-05-15 18:12:38 +02:00
})
}
2019-05-23 06:30:43 +02:00
pub fn add_commands(&mut self, commands: Vec<(&str, Arc<dyn Command>)>) {
2019-05-15 18:12:38 +02:00
for (name, command) in commands {
self.commands.insert(name.to_string(), command);
}
}
2019-05-22 09:12:03 +02:00
crate fn has_command(&self, name: &str) -> bool {
2019-05-15 18:12:38 +02:00
self.commands.contains_key(name)
}
2019-05-22 09:12:03 +02:00
crate fn get_command(&self, name: &str) -> Arc<dyn Command> {
self.commands.get(name).unwrap().clone()
}
2019-05-16 02:21:46 +02:00
crate fn run_command(
2019-05-22 09:12:03 +02:00
&mut self,
command: Arc<dyn Command>,
2019-05-15 18:12:38 +02:00
arg_list: Vec<Value>,
input: InputStream,
) -> Result<OutputStream, ShellError> {
2019-05-16 02:21:46 +02:00
let command_args = CommandArgs {
host: self.host.clone(),
env: self.env.clone(),
2019-05-16 02:21:46 +02:00
args: arg_list,
input,
};
2019-05-22 09:12:03 +02:00
command.run(command_args)
2019-05-15 18:12:38 +02:00
}
}