nushell/src/commands/config.rs

107 lines
3.0 KiB
Rust
Raw Normal View History

use crate::prelude::*;
use crate::errors::ShellError;
use crate::object::config;
use crate::object::Value;
2019-06-22 05:43:37 +02:00
use crate::parser::registry::{CommandConfig, NamedType, NamedValue};
use indexmap::IndexMap;
use log::trace;
use std::iter::FromIterator;
pub struct Config;
impl Command for Config {
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
config(args)
}
fn name(&self) -> &str {
"config"
}
fn config(&self) -> CommandConfig {
let mut named: IndexMap<String, NamedType> = IndexMap::new();
2019-06-22 05:43:37 +02:00
named.insert("set".to_string(), NamedType::Optional(NamedValue::Single));
named.insert("get".to_string(), NamedType::Optional(NamedValue::Single));
named.insert("clear".to_string(), NamedType::Switch);
named.insert(
"remove".to_string(),
NamedType::Optional(NamedValue::Single),
);
CommandConfig {
name: self.name().to_string(),
positional: vec![],
rest_positional: false,
named,
2019-07-02 09:56:20 +02:00
is_sink: true,
is_filter: false,
can_load: vec![],
can_save: vec![],
}
}
}
pub fn config(args: CommandArgs) -> Result<OutputStream, ShellError> {
2019-07-08 18:44:53 +02:00
let mut result = crate::object::config::config(args.name_span)?;
2019-06-22 05:43:37 +02:00
trace!("{:#?}", args.args.positional);
trace!("{:#?}", args.args.named);
2019-06-22 05:43:37 +02:00
if let Some(v) = args.get("get") {
let key = v.as_string()?;
let value = result
.get(&key)
.ok_or_else(|| ShellError::string(&format!("Missing key {} in config", key)))?;
return Ok(
2019-07-08 18:44:53 +02:00
stream![value.clone()], // futures::stream::once(futures::future::ready(ReturnSuccess::Value(value.clone()))).into(),
);
}
2019-06-22 05:43:37 +02:00
if let Some(v) = args.get("set") {
if let Ok((key, value)) = v.as_pair() {
2019-06-23 00:20:13 +02:00
result.insert(key.as_string()?.to_string(), value.clone());
config::write_config(&result)?;
2019-07-08 18:44:53 +02:00
return Ok(
stream![Spanned::from_item(Value::Object(result.into()), v.span())]
.from_input_stream(),
);
}
}
2019-07-08 18:44:53 +02:00
if let Some(c) = args.get("clear") {
result.clear();
config::write_config(&result)?;
2019-07-08 18:44:53 +02:00
return Ok(
stream![Spanned::from_item(Value::Object(result.into()), c.span())].from_input_stream(),
);
}
2019-06-22 05:43:37 +02:00
if let Some(v) = args.get("remove") {
let key = v.as_string()?;
if result.contains_key(&key) {
result.remove(&key);
} else {
return Err(ShellError::string(&format!(
"{} does not exist in config",
key
)));
}
2019-07-08 18:44:53 +02:00
let obj = VecDeque::from_iter(vec![Value::Object(result.into()).spanned(v)]);
return Ok(obj.from_input_stream());
}
2019-06-22 05:43:37 +02:00
if args.len() == 0 {
return Ok(vec![Value::Object(result.into())].into());
}
Err(ShellError::string(format!("Unimplemented")))
}