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