embed as column when embedding a list

This commit is contained in:
Andrés N. Robalino 2019-12-03 02:26:01 -05:00
parent 3fa03eb7a4
commit e5405d7f5c
2 changed files with 71 additions and 11 deletions

View file

@ -11,18 +11,40 @@ use nu_source::Tag;
struct Embed { struct Embed {
field: Option<String>, field: Option<String>,
are_all_rows: bool,
values: Vec<Value>, values: Vec<Value>,
} }
impl Embed { impl Embed {
fn new() -> Embed { fn new() -> Embed {
Embed { Embed {
field: None, field: None,
are_all_rows: true,
values: Vec::new(), values: Vec::new(),
} }
} }
fn embed(&mut self, value: Value) -> Result<(), ShellError> { fn embed(&mut self, value: Value) -> Result<(), ShellError> {
match &value {
Value {
value: UntaggedValue::Row(_),
..
} => {
self.values.push(value); self.values.push(value);
}
_ => {
self.are_all_rows = false;
self.values.push(
value::row(indexmap! {
match &self.field {
Some(key) => key.clone(),
None => "Column".into()
} => value
})
.into_value(Tag::unknown()),
);
}
}
Ok(()) Ok(())
} }
} }
@ -58,15 +80,23 @@ impl Plugin for Embed {
} }
fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> { fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
if self.are_all_rows {
let row = value::row(indexmap! { let row = value::row(indexmap! {
match &self.field { match &self.field {
Some(key) => key.clone(), Some(key) => key.clone(),
None => "root".into(), None => "Column".into(),
} => value::table(&self.values).into_value(Tag::unknown()), } => value::table(&self.values).into_value(Tag::unknown()),
}) })
.into_untagged_value(); .into_untagged_value();
Ok(vec![ReturnSuccess::value(row)]) Ok(vec![ReturnSuccess::value(row)])
} else {
Ok(self
.values
.iter()
.map(|row| ReturnSuccess::value(row.clone()))
.collect::<Vec<_>>())
}
} }
} }

View file

@ -727,8 +727,8 @@ fn can_get_reverse_first() {
} }
#[test] #[test]
fn embed() { fn embed_rows_into_a_row() {
Playground::setup("embed_test", |dirs, sandbox| { Playground::setup("embed_test_1", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContentToBeTrimmed( sandbox.with_files(vec![FileWithContentToBeTrimmed(
"los_tres_caballeros.txt", "los_tres_caballeros.txt",
r#" r#"
@ -756,6 +756,36 @@ fn embed() {
}) })
} }
#[test]
fn embed_rows_into_a_table() {
Playground::setup("embed_test_2", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
first_name,last_name
Andrés,Robalino
Jonathan,Turner
Yehuda,Katz
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open los_tres_caballeros.txt
| from-csv
| get last_name
| embed caballero
| nth 2
| get caballero
| echo $it
"#
));
assert_eq!(actual, "Katz");
})
}
#[test] #[test]
fn get() { fn get() {
Playground::setup("get_test", |dirs, sandbox| { Playground::setup("get_test", |dirs, sandbox| {