Add missing files

This commit is contained in:
Jonathan Turner 2019-05-28 16:00:00 +12:00
parent 94a6c754ac
commit 420b840cd6
3 changed files with 61 additions and 0 deletions

32
src/commands/from_json.rs Normal file
View File

@ -0,0 +1,32 @@
use crate::object::{Primitive, Value, Dictionary, DataDescriptor};
use crate::prelude::*;
fn convert_json_value_to_nu_value(v: &serde_json::Value) -> Value {
match v {
serde_json::Value::Null => Value::Primitive(Primitive::String("".to_string())),
serde_json::Value::Bool(b) => Value::Primitive(Primitive::Boolean(*b)),
serde_json::Value::Number(n) => Value::Primitive(Primitive::Int(n.as_i64().unwrap())),
serde_json::Value::String(s) => Value::Primitive(Primitive::String(s.clone())),
serde_json::Value::Array(a) => Value::List(a.iter().map(|x| convert_json_value_to_nu_value(x)).collect()),
serde_json::Value::Object(o) => {
let mut collected = Dictionary::default();
for (k, v) in o.iter() {
collected.add(DataDescriptor::from(k.clone()), convert_json_value_to_nu_value(v));
}
Value::Object(collected)
}
}
}
pub fn from_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
Ok(out
.map(|a| match a {
Value::Primitive(Primitive::String(s)) => {
let v: serde_json::Value = serde_json::from_str(&s).unwrap();
ReturnValue::Value(convert_json_value_to_nu_value(&v))
}
_ => ReturnValue::Value(Value::Primitive(Primitive::String("".to_string()))),
})
.boxed())
}

20
src/commands/open.rs Normal file
View File

@ -0,0 +1,20 @@
use crate::errors::ShellError;
use crate::object::{Primitive, Value};
use crate::prelude::*;
use std::path::PathBuf;
pub fn open(args: CommandArgs) -> Result<OutputStream, ShellError> {
let cwd = args.env.lock().unwrap().cwd().to_path_buf();
let mut full_path = PathBuf::from(cwd);
match &args.args[0] {
Value::Primitive(Primitive::String(s)) => full_path.push(s),
_ => {}
}
let contents = std::fs::read_to_string(&full_path).unwrap();
let mut stream = VecDeque::new();
stream.push_back(ReturnValue::Value(Value::Primitive(Primitive::String(contents))));
Ok(stream.boxed())
}

9
src/commands/to_json.rs Normal file
View File

@ -0,0 +1,9 @@
use crate::object::{Primitive, Value};
use crate::prelude::*;
pub fn to_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
Ok(out
.map(|a| ReturnValue::Value(Value::Primitive(Primitive::String(serde_json::to_string(&a).unwrap()))))
.boxed())
}