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;
|
|
|
|
|
|
|
|
pub struct Context {
|
2019-05-16 02:21:46 +02:00
|
|
|
commands: indexmap::IndexMap<String, Box<dyn crate::Command>>,
|
2019-05-15 18:12:38 +02:00
|
|
|
crate host: Box<dyn crate::Host>,
|
|
|
|
crate env: Environment,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Context {
|
|
|
|
crate fn basic() -> Result<Context, Box<Error>> {
|
|
|
|
Ok(Context {
|
2019-05-16 00:58:44 +02:00
|
|
|
commands: indexmap::IndexMap::new(),
|
2019-05-15 18:12:38 +02:00
|
|
|
host: Box::new(crate::env::host::BasicHost),
|
|
|
|
env: crate::Environment::basic()?,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-05-16 02:21:46 +02:00
|
|
|
pub fn add_commands(&mut self, commands: Vec<(&str, Box<dyn crate::Command>)>) {
|
2019-05-15 18:12:38 +02:00
|
|
|
for (name, command) in commands {
|
|
|
|
self.commands.insert(name.to_string(), command);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
crate fn has_command(&mut self, name: &str) -> bool {
|
|
|
|
self.commands.contains_key(name)
|
|
|
|
}
|
|
|
|
|
2019-05-16 02:21:46 +02:00
|
|
|
crate fn run_command(
|
|
|
|
&self,
|
2019-05-15 18:12:38 +02:00
|
|
|
name: &str,
|
|
|
|
arg_list: Vec<Value>,
|
2019-05-16 02:21:46 +02:00
|
|
|
input: VecDeque<Value>,
|
|
|
|
) -> Result<VecDeque<ReturnValue>, ShellError> {
|
|
|
|
let command_args = CommandArgs {
|
|
|
|
host: &self.host,
|
|
|
|
env: &self.env,
|
|
|
|
args: arg_list,
|
|
|
|
input,
|
|
|
|
};
|
|
|
|
|
2019-05-15 18:12:38 +02:00
|
|
|
match self.commands.get(name) {
|
2019-05-16 02:21:46 +02:00
|
|
|
None => Err(ShellError::string(format!(
|
|
|
|
"Command {} did not exist",
|
|
|
|
name
|
|
|
|
))),
|
|
|
|
Some(command) => command.run(command_args),
|
2019-05-15 18:12:38 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|