Move to* and from* to engine-p (#3320)

* WIP

* Finish last batch
This commit is contained in:
JT 2021-04-15 19:43:33 +12:00 committed by GitHub
parent fd7875e572
commit f73732bf1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 299 additions and 445 deletions

View File

@ -161,7 +161,8 @@ table-pager = ["nu-command/table-pager"]
#strip = "symbols" #Couldn't get working +nightly #strip = "symbols" #Couldn't get working +nightly
codegen-units = 1 #Reduce parallel codegen units codegen-units = 1 #Reduce parallel codegen units
lto = true #Link Time Optimization lto = true #Link Time Optimization
opt-level = 'z' #Optimize for size # opt-level = 'z' #Optimize for size
# debug = true
# Core plugins that ship with `cargo install nu` by default # Core plugins that ship with `cargo install nu` by default
# Currently, Cargo limits us to installing only one binary # Currently, Cargo limits us to installing only one binary

View File

@ -115,12 +115,11 @@ Format: #
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let code: Option<Result<Tagged<String>, ShellError>> = args.opt(0); let code: Option<Tagged<String>> = args.opt(0)?;
let escape: Option<Result<Tagged<String>, ShellError>> = args.get_flag("escape"); let escape: Option<Tagged<String>> = args.get_flag("escape")?;
let osc: Option<Result<Tagged<String>, ShellError>> = args.get_flag("osc"); let osc: Option<Tagged<String>> = args.get_flag("osc")?;
if let Some(e) = escape { if let Some(e) = escape {
let e = e?;
let esc_vec: Vec<char> = e.item.chars().collect(); let esc_vec: Vec<char> = e.item.chars().collect();
if esc_vec[0] == '\\' { if esc_vec[0] == '\\' {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
@ -136,7 +135,6 @@ Format: #
} }
if let Some(o) = osc { if let Some(o) = osc {
let o = o?;
let osc_vec: Vec<char> = o.item.chars().collect(); let osc_vec: Vec<char> = o.item.chars().collect();
if osc_vec[0] == '\\' { if osc_vec[0] == '\\' {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
@ -155,7 +153,6 @@ Format: #
} }
if let Some(code) = code { if let Some(code) = code {
let code = code?;
let ansi_code = str_to_ansi(&code.item); let ansi_code = str_to_ansi(&code.item);
if let Some(output) = ansi_code { if let Some(output) = ansi_code {

View File

@ -129,19 +129,19 @@ fn enter(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
scope, scope,
}; };
let tag = tagged_contents.tag.clone(); let tag = tagged_contents.tag.clone();
let mut result = converter let mut result =
.run_with_actions(new_args.with_input(vec![tagged_contents]))?; converter.run(new_args.with_input(vec![tagged_contents]))?;
let result_vec: Vec<Result<ReturnSuccess, ShellError>> = result.drain_vec(); let result_vec: Vec<Value> = result.drain_vec();
Ok(result_vec Ok(result_vec
.into_iter() .into_iter()
.map(move |res| match res { .map(move |res| {
Ok(ReturnSuccess::Value(Value { value, .. })) => Ok( let Value { value, .. } = res;
ReturnSuccess::Action(CommandAction::EnterValueShell(Value { Ok(ReturnSuccess::Action(CommandAction::EnterValueShell(
Value {
value, value,
tag: tag.clone(), tag: tag.clone(),
})), },
), )))
x => x,
}) })
.to_action_stream()) .to_action_stream())
} else { } else {

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue}; use nu_protocol::{Signature, UntaggedValue};
pub struct From; pub struct From;
@ -18,10 +18,10 @@ impl WholeStreamCommand for From {
"Parse content (string or binary) as a table (input format based on subcommand, like csv, ini, json, toml)." "Parse content (string or binary) as a table (input format based on subcommand, like csv, ini, json, toml)."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&From, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&From, &args.scope)).into_value(Tag::unknown()),
))) ))
} }
} }

View File

@ -6,12 +6,6 @@ use nu_protocol::{Primitive, Signature, SyntaxShape, UntaggedValue, Value};
pub struct FromCsv; pub struct FromCsv;
#[derive(Deserialize)]
pub struct FromCsvArgs {
noheaders: bool,
separator: Option<Value>,
}
impl WholeStreamCommand for FromCsv { impl WholeStreamCommand for FromCsv {
fn name(&self) -> &str { fn name(&self) -> &str {
"from csv" "from csv"
@ -36,7 +30,7 @@ impl WholeStreamCommand for FromCsv {
"Parse text as .csv and create table." "Parse text as .csv and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_csv(args) from_csv(args)
} }
@ -66,16 +60,14 @@ impl WholeStreamCommand for FromCsv {
} }
} }
fn from_csv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_csv(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let args = args.evaluate_once()?;
let noheaders = args.has_flag("noheaders");
let separator: Option<Value> = args.get_flag("separator")?;
let input = args.input;
let (
FromCsvArgs {
noheaders,
separator,
},
input,
) = args.process()?;
let sep = match separator { let sep = match separator {
Some(Value { Some(Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),

View File

@ -51,7 +51,7 @@ pub fn from_delimited_data(
format_name: &'static str, format_name: &'static str,
input: InputStream, input: InputStream,
name: Tag, name: Tag,
) -> Result<ActionStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let name_tag = name; let name_tag = name;
let concat_string = input.collect_string(name_tag.clone())?; let concat_string = input.collect_string(name_tag.clone())?;
let sample_lines = concat_string.item.lines().take(3).collect_vec().join("\n"); let sample_lines = concat_string.item.lines().take(3).collect_vec().join("\n");
@ -61,8 +61,8 @@ pub fn from_delimited_data(
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => Ok(list.into_iter().to_action_stream()), } => Ok(list.into_iter().to_output_stream()),
x => Ok(ActionStream::one(x)), x => Ok(OutputStream::one(x)),
}, },
Err(err) => { Err(err) => {
let line_one = match pretty_csv_error(err) { let line_one = match pretty_csv_error(err) {

View File

@ -3,19 +3,13 @@ use ::eml_parser::eml::*;
use ::eml_parser::EmlParser; use ::eml_parser::EmlParser;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue}; use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue};
use nu_source::Tagged; use nu_source::Tagged;
pub struct FromEml; pub struct FromEml;
const DEFAULT_BODY_PREVIEW: usize = 50; const DEFAULT_BODY_PREVIEW: usize = 50;
#[derive(Deserialize, Clone)]
pub struct FromEmlArgs {
#[serde(rename(deserialize = "preview-body"))]
preview_body: Option<Tagged<usize>>,
}
impl WholeStreamCommand for FromEml { impl WholeStreamCommand for FromEml {
fn name(&self) -> &str { fn name(&self) -> &str {
"from eml" "from eml"
@ -34,7 +28,7 @@ impl WholeStreamCommand for FromEml {
"Parse text as .eml and create table." "Parse text as .eml and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_eml(args) from_eml(args)
} }
} }
@ -72,15 +66,15 @@ fn headerfieldvalue_to_value(tag: &Tag, value: &HeaderFieldValue) -> UntaggedVal
} }
} }
fn from_eml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_eml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let tag = args.call_info.name_tag.clone(); let tag = args.call_info.name_tag.clone();
let (eml_args, input): (FromEmlArgs, _) = args.process()?; let args = args.evaluate_once()?;
let value = input.collect_string(tag.clone())?;
let body_preview = eml_args let preview_body: Option<Tagged<usize>> = args.get_flag("preview-body")?;
.preview_body
.map(|b| b.item) let value = args.input.collect_string(tag.clone())?;
.unwrap_or(DEFAULT_BODY_PREVIEW);
let body_preview = preview_body.map(|b| b.item).unwrap_or(DEFAULT_BODY_PREVIEW);
let eml = EmlParser::from_string(value.item) let eml = EmlParser::from_string(value.item)
.with_body_preview(body_preview) .with_body_preview(body_preview)
@ -115,7 +109,7 @@ fn from_eml(args: CommandArgs) -> Result<ActionStream, ShellError> {
dict.insert_untagged("Body", UntaggedValue::string(body)); dict.insert_untagged("Body", UntaggedValue::string(body));
} }
Ok(ActionStream::one(ReturnSuccess::value(dict.into_value()))) Ok(OutputStream::one(dict.into_value()))
} }
#[cfg(test)] #[cfg(test)]

View File

@ -4,7 +4,7 @@ use ical::parser::ical::component::*;
use ical::property::Property; use ical::property::Property;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
use std::io::BufReader; use std::io::BufReader;
pub struct FromIcs; pub struct FromIcs;
@ -22,12 +22,12 @@ impl WholeStreamCommand for FromIcs {
"Parse text as .ics and create table." "Parse text as .ics and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_ics(args) from_ics(args)
} }
} }
fn from_ics(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_ics(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -43,8 +43,8 @@ fn from_ics(args: CommandArgs) -> Result<ActionStream, ShellError> {
for calendar in parser { for calendar in parser {
match calendar { match calendar {
Ok(c) => output.push(ReturnSuccess::value(calendar_to_value(c, tag.clone()))), Ok(c) => output.push(calendar_to_value(c, tag.clone())),
Err(_) => output.push(Err(ShellError::labeled_error( Err(_) => output.push(Value::error(ShellError::labeled_error(
"Could not parse as .ics", "Could not parse as .ics",
"input cannot be parsed as .ics", "input cannot be parsed as .ics",
tag.clone(), tag.clone(),
@ -52,7 +52,7 @@ fn from_ics(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
Ok(output.into_iter().to_action_stream()) Ok(output.into_iter().to_output_stream())
} }
fn calendar_to_value(calendar: IcalCalendar, tag: Tag) -> Value { fn calendar_to_value(calendar: IcalCalendar, tag: Tag) -> Value {

View File

@ -19,7 +19,7 @@ impl WholeStreamCommand for FromIni {
"Parse text as .ini and create table" "Parse text as .ini and create table"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_ini(args) from_ini(args)
} }
} }
@ -59,7 +59,7 @@ pub fn from_ini_string_to_value(
Ok(convert_ini_top_to_nu_value(&v, tag)) Ok(convert_ini_top_to_nu_value(&v, tag))
} }
fn from_ini(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_ini(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -70,8 +70,8 @@ fn from_ini(args: CommandArgs) -> Result<ActionStream, ShellError> {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => Ok(list.into_iter().to_action_stream()), } => Ok(list.into_iter().to_output_stream()),
x => Ok(ActionStream::one(x)), x => Ok(OutputStream::one(x)),
}, },
Err(_) => Err(ShellError::labeled_error_with_secondary( Err(_) => Err(ShellError::labeled_error_with_secondary(
"Could not parse as INI", "Could not parse as INI",

View File

@ -1,15 +1,10 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
pub struct FromJson; pub struct FromJson;
#[derive(Deserialize)]
pub struct FromJsonArgs {
objects: bool,
}
impl WholeStreamCommand for FromJson { impl WholeStreamCommand for FromJson {
fn name(&self) -> &str { fn name(&self) -> &str {
"from json" "from json"
@ -27,7 +22,7 @@ impl WholeStreamCommand for FromJson {
"Parse text as .json and create table." "Parse text as .json and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_json(args) from_json(args)
} }
} }
@ -67,11 +62,13 @@ pub fn from_json_string_to_value(s: String, tag: impl Into<Tag>) -> nu_json::Res
Ok(convert_json_value_to_nu_value(&v, tag)) Ok(convert_json_value_to_nu_value(&v, tag))
} }
fn from_json(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let (FromJsonArgs { objects }, input) = args.process()?; let args = args.evaluate_once()?;
let concat_string = input.collect_string(name_tag.clone())?; let objects = args.has_flag("objects");
let concat_string = args.input.collect_string(name_tag.clone())?;
let string_clone: Vec<_> = concat_string.item.lines().map(|x| x.to_string()).collect(); let string_clone: Vec<_> = concat_string.item.lines().map(|x| x.to_string()).collect();
@ -84,13 +81,13 @@ fn from_json(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
match from_json_string_to_value(json_str, &name_tag) { match from_json_string_to_value(json_str, &name_tag) {
Ok(x) => Some(ReturnSuccess::value(x)), Ok(x) => Some(x),
Err(e) => { Err(e) => {
let mut message = "Could not parse as JSON (".to_string(); let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string()); message.push_str(&e.to_string());
message.push(')'); message.push(')');
Some(Err(ShellError::labeled_error_with_secondary( Some(Value::error(ShellError::labeled_error_with_secondary(
message, message,
"input cannot be parsed as JSON", "input cannot be parsed as JSON",
name_tag.clone(), name_tag.clone(),
@ -100,26 +97,23 @@ fn from_json(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
}) })
.to_action_stream()) .to_output_stream())
} else { } else {
match from_json_string_to_value(concat_string.item, name_tag.clone()) { match from_json_string_to_value(concat_string.item, name_tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => Ok(list } => Ok(list.into_iter().to_output_stream()),
.into_iter()
.map(ReturnSuccess::value)
.to_action_stream()),
x => Ok(ActionStream::one(ReturnSuccess::value(x))), x => Ok(OutputStream::one(x)),
}, },
Err(e) => { Err(e) => {
let mut message = "Could not parse as JSON (".to_string(); let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string()); message.push_str(&e.to_string());
message.push(')'); message.push(')');
Ok(ActionStream::one(Err( Ok(OutputStream::one(Value::error(
ShellError::labeled_error_with_secondary( ShellError::labeled_error_with_secondary(
message, message,
"input cannot be parsed as JSON", "input cannot be parsed as JSON",

View File

@ -3,49 +3,34 @@ use calamine::*;
use nu_data::TaggedListBuilder; use nu_data::TaggedListBuilder;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue}; use nu_protocol::{Signature, TaggedDictBuilder, UntaggedValue};
use std::io::Cursor; use std::io::Cursor;
pub struct FromOds; pub struct FromOds;
#[derive(Deserialize)]
pub struct FromOdsArgs {
noheaders: bool,
}
impl WholeStreamCommand for FromOds { impl WholeStreamCommand for FromOds {
fn name(&self) -> &str { fn name(&self) -> &str {
"from ods" "from ods"
} }
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("from ods").switch( Signature::build("from ods")
"noheaders",
"don't treat the first row as column names",
Some('n'),
)
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Parse OpenDocument Spreadsheet(.ods) data and create table." "Parse OpenDocument Spreadsheet(.ods) data and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_ods(args) from_ods(args)
} }
} }
fn from_ods(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_ods(args: CommandArgs) -> Result<OutputStream, ShellError> {
let tag = args.call_info.name_tag.clone(); let tag = args.call_info.name_tag.clone();
let span = tag.span; let span = tag.span;
let ( let bytes = args.input.collect_binary(tag.clone())?;
FromOdsArgs {
noheaders: _noheaders,
},
input,
) = args.process()?;
let bytes = input.collect_binary(tag.clone())?;
let buf: Cursor<Vec<u8>> = Cursor::new(bytes.item); let buf: Cursor<Vec<u8>> = Cursor::new(bytes.item);
let mut ods = Ods::<_>::new(buf).map_err(|_| { let mut ods = Ods::<_>::new(buf).map_err(|_| {
ShellError::labeled_error("Could not load ods file", "could not load ods file", &tag) ShellError::labeled_error("Could not load ods file", "could not load ods file", &tag)
@ -87,7 +72,7 @@ fn from_ods(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
Ok(ActionStream::one(ReturnSuccess::value(dict.into_value()))) Ok(OutputStream::one(dict.into_value()))
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,22 +1,11 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ use nu_protocol::{Primitive, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value};
Primitive, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value,
};
use nu_source::Tagged; use nu_source::Tagged;
pub struct FromSsv; pub struct FromSsv;
#[derive(Deserialize)]
pub struct FromSsvArgs {
noheaders: bool,
#[serde(rename(deserialize = "aligned-columns"))]
aligned_columns: bool,
#[serde(rename(deserialize = "minimum-spaces"))]
minimum_spaces: Option<Tagged<usize>>,
}
const STRING_REPRESENTATION: &str = "from ssv"; const STRING_REPRESENTATION: &str = "from ssv";
const DEFAULT_MINIMUM_SPACES: usize = 2; const DEFAULT_MINIMUM_SPACES: usize = 2;
@ -45,7 +34,7 @@ impl WholeStreamCommand for FromSsv {
"Parse text as space-separated values and create a table. The default minimum number of spaces counted as a separator is 2." "Parse text as space-separated values and create a table. The default minimum number of spaces counted as a separator is 2."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_ssv(args) from_ssv(args)
} }
} }
@ -246,17 +235,15 @@ fn from_ssv_string_to_value(
UntaggedValue::Table(rows).into_value(&tag) UntaggedValue::Table(rows).into_value(&tag)
} }
fn from_ssv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_ssv(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let ( let args = args.evaluate_once()?;
FromSsvArgs {
noheaders, let noheaders = args.has_flag("noheaders");
aligned_columns, let aligned_columns = args.has_flag("aligned-columns");
minimum_spaces, let minimum_spaces: Option<Tagged<usize>> = args.get_flag("minimum-spaces")?;
},
input, let concat_string = args.input.collect_string(name.clone())?;
) = args.process()?;
let concat_string = input.collect_string(name.clone())?;
let split_at = match minimum_spaces { let split_at = match minimum_spaces {
Some(number) => number.item, Some(number) => number.item,
None => DEFAULT_MINIMUM_SPACES, None => DEFAULT_MINIMUM_SPACES,
@ -273,11 +260,8 @@ fn from_ssv(args: CommandArgs) -> Result<ActionStream, ShellError> {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => list } => list.into_iter().to_output_stream(),
.into_iter() x => OutputStream::one(x),
.map(ReturnSuccess::value)
.to_action_stream(),
x => ActionStream::one(ReturnSuccess::value(x)),
}, },
) )
} }

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
pub struct FromToml; pub struct FromToml;
@ -18,7 +18,7 @@ impl WholeStreamCommand for FromToml {
"Parse text as .toml and create table." "Parse text as .toml and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_toml(args) from_toml(args)
} }
} }
@ -60,7 +60,7 @@ pub fn from_toml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value
Ok(convert_toml_value_to_nu_value(&v, tag)) Ok(convert_toml_value_to_nu_value(&v, tag))
} }
pub fn from_toml(args: CommandArgs) -> Result<ActionStream, ShellError> { pub fn from_toml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -72,11 +72,8 @@ pub fn from_toml(args: CommandArgs) -> Result<ActionStream, ShellError> {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => list } => list.into_iter().to_output_stream(),
.into_iter() x => OutputStream::one(x),
.map(ReturnSuccess::value)
.to_action_stream(),
x => ActionStream::one(ReturnSuccess::value(x)),
}, },
Err(_) => { Err(_) => {
return Err(ShellError::labeled_error_with_secondary( return Err(ShellError::labeled_error_with_secondary(

View File

@ -6,11 +6,6 @@ use nu_protocol::Signature;
pub struct FromTsv; pub struct FromTsv;
#[derive(Deserialize)]
pub struct FromTsvArgs {
noheaders: bool,
}
impl WholeStreamCommand for FromTsv { impl WholeStreamCommand for FromTsv {
fn name(&self) -> &str { fn name(&self) -> &str {
"from tsv" "from tsv"
@ -28,14 +23,16 @@ impl WholeStreamCommand for FromTsv {
"Parse text as .tsv and create table." "Parse text as .tsv and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_tsv(args) from_tsv(args)
} }
} }
fn from_tsv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_tsv(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let (FromTsvArgs { noheaders }, input) = args.process()?; let args = args.evaluate_once()?;
let noheaders = args.has_flag("noheaders");
let input = args.input;
from_delimited_data(noheaders, '\t', "TSV", input, name) from_delimited_data(noheaders, '\t', "TSV", input, name)
} }

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue}; use nu_protocol::{Signature, TaggedDictBuilder, UntaggedValue};
pub struct FromUrl; pub struct FromUrl;
@ -18,12 +18,12 @@ impl WholeStreamCommand for FromUrl {
"Parse url-encoded string as a table." "Parse url-encoded string as a table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_url(args) from_url(args)
} }
} }
fn from_url(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_url(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -40,7 +40,7 @@ fn from_url(args: CommandArgs) -> Result<ActionStream, ShellError> {
row.insert_untagged(k, UntaggedValue::string(v)); row.insert_untagged(k, UntaggedValue::string(v));
} }
Ok(ActionStream::one(ReturnSuccess::value(row.into_value()))) Ok(OutputStream::one(row.into_value()))
} }
_ => Err(ShellError::labeled_error_with_secondary( _ => Err(ShellError::labeled_error_with_secondary(
"String not compatible with url-encoding", "String not compatible with url-encoding",

View File

@ -1,10 +1,9 @@
extern crate ical;
use crate::prelude::*; use crate::prelude::*;
use ical::parser::vcard::component::*; use ical::parser::vcard::component::*;
use ical::property::Property; use ical::property::Property;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
pub struct FromVcf; pub struct FromVcf;
@ -21,12 +20,12 @@ impl WholeStreamCommand for FromVcf {
"Parse text as .vcf and create table." "Parse text as .vcf and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_vcf(args) from_vcf(args)
} }
} }
fn from_vcf(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_vcf(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -37,8 +36,8 @@ fn from_vcf(args: CommandArgs) -> Result<ActionStream, ShellError> {
let parser = ical::VcardParser::new(cursor); let parser = ical::VcardParser::new(cursor);
let iter = parser.map(move |contact| match contact { let iter = parser.map(move |contact| match contact {
Ok(c) => ReturnSuccess::value(contact_to_value(c, tag.clone())), Ok(c) => contact_to_value(c, tag.clone()),
Err(_) => Err(ShellError::labeled_error( Err(_) => Value::error(ShellError::labeled_error(
"Could not parse as .vcf", "Could not parse as .vcf",
"input cannot be parsed as .vcf", "input cannot be parsed as .vcf",
tag.clone(), tag.clone(),
@ -47,7 +46,7 @@ fn from_vcf(args: CommandArgs) -> Result<ActionStream, ShellError> {
let collected: Vec<_> = iter.collect(); let collected: Vec<_> = iter.collect();
Ok(collected.into_iter().to_action_stream()) Ok(collected.into_iter().to_output_stream())
} }
fn contact_to_value(contact: VcardContact, tag: Tag) -> Value { fn contact_to_value(contact: VcardContact, tag: Tag) -> Value {

View File

@ -3,16 +3,11 @@ use calamine::*;
use nu_data::TaggedListBuilder; use nu_data::TaggedListBuilder;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue}; use nu_protocol::{Signature, TaggedDictBuilder, UntaggedValue};
use std::io::Cursor; use std::io::Cursor;
pub struct FromXlsx; pub struct FromXlsx;
#[derive(Deserialize)]
pub struct FromXlsxArgs {
noheaders: bool,
}
impl WholeStreamCommand for FromXlsx { impl WholeStreamCommand for FromXlsx {
fn name(&self) -> &str { fn name(&self) -> &str {
"from xlsx" "from xlsx"
@ -30,21 +25,16 @@ impl WholeStreamCommand for FromXlsx {
"Parse binary Excel(.xlsx) data and create table." "Parse binary Excel(.xlsx) data and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_xlsx(args) from_xlsx(args)
} }
} }
fn from_xlsx(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_xlsx(args: CommandArgs) -> Result<OutputStream, ShellError> {
let tag = args.call_info.name_tag.clone(); let tag = args.call_info.name_tag.clone();
let span = tag.span; let span = tag.span;
let (
FromXlsxArgs { let value = args.input.collect_binary(tag.clone())?;
noheaders: _noheaders,
},
input,
) = args.process()?;
let value = input.collect_binary(tag.clone())?;
let buf: Cursor<Vec<u8>> = Cursor::new(value.item); let buf: Cursor<Vec<u8>> = Cursor::new(value.item);
let mut xls = Xlsx::<_>::new(buf).map_err(|_| { let mut xls = Xlsx::<_>::new(buf).map_err(|_| {
@ -87,7 +77,7 @@ fn from_xlsx(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
Ok(ActionStream::one(ReturnSuccess::value(dict.into_value()))) Ok(OutputStream::one(dict.into_value()))
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value};
pub struct FromXml; pub struct FromXml;
@ -18,7 +18,7 @@ impl WholeStreamCommand for FromXml {
"Parse text as .xml and create table." "Parse text as .xml and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_xml(args) from_xml(args)
} }
} }
@ -94,7 +94,7 @@ pub fn from_xml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value,
Ok(from_document_to_value(&parsed, tag)) Ok(from_document_to_value(&parsed, tag))
} }
fn from_xml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_xml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -107,11 +107,8 @@ fn from_xml(args: CommandArgs) -> Result<ActionStream, ShellError> {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => list } => list.into_iter().to_output_stream(),
.into_iter() x => OutputStream::one(x),
.map(ReturnSuccess::value)
.to_action_stream(),
x => ActionStream::one(ReturnSuccess::value(x)),
}, },
Err(_) => { Err(_) => {
return Err(ShellError::labeled_error_with_secondary( return Err(ShellError::labeled_error_with_secondary(

View File

@ -18,7 +18,7 @@ impl WholeStreamCommand for FromYaml {
"Parse text as .yaml/.yml and create table." "Parse text as .yaml/.yml and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_yaml(args) from_yaml(args)
} }
} }
@ -38,7 +38,7 @@ impl WholeStreamCommand for FromYml {
"Parse text as .yaml/.yml and create table." "Parse text as .yaml/.yml and create table."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
from_yaml(args) from_yaml(args)
} }
} }
@ -131,7 +131,7 @@ pub fn from_yaml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value
convert_yaml_value_to_nu_value(&v, tag) convert_yaml_value_to_nu_value(&v, tag)
} }
fn from_yaml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn from_yaml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -143,8 +143,8 @@ fn from_yaml(args: CommandArgs) -> Result<ActionStream, ShellError> {
Value { Value {
value: UntaggedValue::Table(list), value: UntaggedValue::Table(list),
.. ..
} => Ok(list.into_iter().to_action_stream()), } => Ok(list.into_iter().to_output_stream()),
x => Ok(ActionStream::one(x)), x => Ok(OutputStream::one(x)),
}, },
Err(_) => Err(ShellError::labeled_error_with_secondary( Err(_) => Err(ShellError::labeled_error_with_secondary(
"Could not parse as YAML", "Could not parse as YAML",

View File

@ -42,11 +42,11 @@ impl WholeStreamCommand for SubCommand {
pub fn eval(args: CommandArgs) -> Result<OutputStream, ShellError> { pub fn eval(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let expression: Option<Result<Tagged<String>, ShellError>> = args.opt(0); let expression: Option<Tagged<String>> = args.opt(0)?;
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let input = args.input; let input = args.input;
if let Some(Ok(string)) = expression { if let Some(string) = expression {
match parse(&string, &string.tag) { match parse(&string, &string.tag) {
Ok(value) => Ok(OutputStream::one(value)), Ok(value) => Ok(OutputStream::one(value)),
Err(err) => Err(ShellError::labeled_error( Err(err) => Err(ShellError::labeled_error(
@ -58,10 +58,10 @@ pub fn eval(args: CommandArgs) -> Result<OutputStream, ShellError> {
} else { } else {
let mapped: Result<Vec<_>, _> = input let mapped: Result<Vec<_>, _> = input
.map(move |x| { .map(move |x| {
if let Some(Ok(Tagged { if let Some(Tagged {
tag, tag,
item: expression, item: expression,
})) = &expression }) = &expression
{ {
UntaggedValue::string(expression).into_value(tag) UntaggedValue::string(expression).into_value(tag)
} else { } else {

View File

@ -54,10 +54,10 @@ impl WholeStreamCommand for SubCommand {
fn operate(args: CommandArgs) -> Result<OutputStream, ShellError> { fn operate(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let precision: Option<Result<Tagged<i16>, ShellError>> = args.get_flag("precision"); let precision: Option<Tagged<i16>> = args.get_flag("precision")?;
let input = args.input; let input = args.input;
let precision = if let Some(precision) = precision { let precision = if let Some(precision) = precision {
precision?.item precision.item
} else { } else {
0 0
}; };

View File

@ -2,8 +2,7 @@ use crate::prelude::*;
use nu_engine::{UnevaluatedCallInfo, WholeStreamCommand}; use nu_engine::{UnevaluatedCallInfo, WholeStreamCommand};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ use nu_protocol::{
hir::ExternalRedirection, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, hir::ExternalRedirection, Primitive, Signature, SyntaxShape, UntaggedValue, Value,
Value,
}; };
use nu_source::Tagged; use nu_source::Tagged;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -81,10 +80,10 @@ macro_rules! process_string_return_success {
let mut result_string = String::new(); let mut result_string = String::new();
for res in $result_vec { for res in $result_vec {
match res { match res {
Ok(ReturnSuccess::Value(Value { Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),
.. ..
})) => { } => {
result_string.push_str(&s); result_string.push_str(&s);
} }
_ => { _ => {
@ -105,10 +104,10 @@ macro_rules! process_binary_return_success {
let mut result_binary: Vec<u8> = Vec::new(); let mut result_binary: Vec<u8> = Vec::new();
for res in $result_vec { for res in $result_vec {
match res { match res {
Ok(ReturnSuccess::Value(Value { Value {
value: UntaggedValue::Primitive(Primitive::Binary(b)), value: UntaggedValue::Primitive(Primitive::Binary(b)),
.. ..
})) => { } => {
for u in b.into_iter() { for u in b.into_iter() {
result_binary.push(u); result_binary.push(u);
} }
@ -126,12 +125,6 @@ macro_rules! process_binary_return_success {
}}; }};
} }
#[derive(Deserialize)]
pub struct SaveArgs {
path: Option<Tagged<PathBuf>>,
raw: bool,
}
impl WholeStreamCommand for Save { impl WholeStreamCommand for Save {
fn name(&self) -> &str { fn name(&self) -> &str {
"save" "save"
@ -155,12 +148,12 @@ impl WholeStreamCommand for Save {
"Save the contents of the pipeline to a file." "Save the contents of the pipeline to a file."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
save(args) save(args)
} }
} }
fn save(raw_args: CommandArgs) -> Result<ActionStream, ShellError> { fn save(raw_args: CommandArgs) -> Result<OutputStream, ShellError> {
let mut full_path = PathBuf::from(raw_args.shell_manager.path()); let mut full_path = PathBuf::from(raw_args.shell_manager.path());
let name_tag = raw_args.call_info.name_tag.clone(); let name_tag = raw_args.call_info.name_tag.clone();
let name = raw_args.call_info.name_tag.clone(); let name = raw_args.call_info.name_tag.clone();
@ -172,14 +165,12 @@ fn save(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
let shell_manager = raw_args.shell_manager.clone(); let shell_manager = raw_args.shell_manager.clone();
let head = raw_args.call_info.args.head.clone(); let head = raw_args.call_info.args.head.clone();
let ( let args = raw_args.evaluate_once()?;
SaveArgs {
path, let path: Option<Tagged<PathBuf>> = args.opt(0)?;
raw: save_raw, let save_raw = args.has_flag("raw");
},
input, let input: Vec<Value> = args.input.collect();
) = raw_args.process()?;
let input: Vec<Value> = input.collect();
if path.is_none() { if path.is_none() {
let mut should_return_file_path_error = true; let mut should_return_file_path_error = true;
@ -230,8 +221,8 @@ fn save(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
}, },
scope, scope,
}; };
let mut result = converter.run_with_actions(new_args.with_input(input))?; let mut result = converter.run(new_args.with_input(input))?;
let result_vec: Vec<Result<ReturnSuccess, ShellError>> = result.drain_vec(); let result_vec: Vec<Value> = result.drain_vec();
if converter.is_binary() { if converter.is_binary() {
process_binary_return_success!('scope, result_vec, name_tag) process_binary_return_success!('scope, result_vec, name_tag)
} else { } else {

View File

@ -3,16 +3,11 @@ use crate::utils::arguments::arguments;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ use nu_protocol::{
PathMember, Primitive, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, PathMember, Primitive, Signature, SyntaxShape, TaggedDictBuilder, UnspannedPathMember,
UnspannedPathMember, UntaggedValue, Value, UntaggedValue, Value,
}; };
use nu_value_ext::{as_string, get_data_by_column_path}; use nu_value_ext::{as_string, get_data_by_column_path};
#[derive(Deserialize)]
struct Arguments {
rest: Vec<Value>,
}
pub struct Command; pub struct Command;
impl WholeStreamCommand for Command { impl WholeStreamCommand for Command {
@ -28,7 +23,7 @@ impl WholeStreamCommand for Command {
"Down-select table to only these columns." "Down-select table to only these columns."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
select(args) select(args)
} }
@ -48,9 +43,11 @@ impl WholeStreamCommand for Command {
} }
} }
fn select(args: CommandArgs) -> Result<ActionStream, ShellError> { fn select(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let (Arguments { mut rest }, input) = args.process()?; let args = args.evaluate_once()?;
let mut rest = args.rest(0)?;
let input = args.input;
let (columns, _) = arguments(&mut rest)?; let (columns, _) = arguments(&mut rest)?;
if columns.is_empty() { if columns.is_empty() {
@ -153,7 +150,7 @@ fn select(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
ReturnSuccess::value(out.into_value()) out.into_value()
})) }))
.to_action_stream()) .to_output_stream())
} }

View File

@ -51,11 +51,7 @@ pub fn collect(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (options, input) = args.extract(|params| { let (options, input) = args.extract(|params| {
Ok(Arguments { Ok(Arguments {
separator: if let Some(arg) = params.opt(0) { separator: params.opt(0)?,
Some(arg?)
} else {
None
},
}) })
})?; })?;

View File

@ -71,11 +71,7 @@ impl WholeStreamCommand for SubCommand {
fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> { fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (options, input) = args.extract(|params| { let (options, input) = args.extract(|params| {
Ok(Arguments { Ok(Arguments {
decimals: if let Some(arg) = params.get_flag("decimals") { decimals: params.get_flag("decimals")?,
Some(arg?)
} else {
None
},
group_digits: false, group_digits: false,
column_paths: params.rest_args()?, column_paths: params.rest_args()?,
}) })

View File

@ -93,11 +93,7 @@ fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (options, input) = args.extract(|params| { let (options, input) = args.extract(|params| {
Ok(Arc::new(Arguments { Ok(Arc::new(Arguments {
pattern: params.req(0)?, pattern: params.req(0)?,
range: if let Some(arg) = params.get_flag("range") { range: params.get_flag("range")?,
Some(arg?)
} else {
None
},
end: params.has_flag("end"), end: params.has_flag("end"),
column_paths: params.rest(1)?, column_paths: params.rest(1)?,
})) }))

View File

@ -131,21 +131,9 @@ fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (column_paths, _) = arguments(&mut params.rest_args()?)?; let (column_paths, _) = arguments(&mut params.rest_args()?)?;
Ok(Arguments { Ok(Arguments {
timezone: if let Some(arg) = params.get_flag("timezone") { timezone: params.get_flag("timezone")?,
Some(arg?) offset: params.get_flag("offset")?,
} else { format: params.get_flag("format")?,
None
},
offset: if let Some(arg) = params.get_flag("offset") {
Some(arg?)
} else {
None
},
format: if let Some(arg) = params.get_flag("format") {
Some(arg?)
} else {
None
},
column_paths, column_paths,
}) })
})?; })?;

View File

@ -72,11 +72,7 @@ fn operate(args: CommandArgs) -> Result<ActionStream, ShellError> {
let (column_paths, _) = arguments(&mut params.rest_args()?)?; let (column_paths, _) = arguments(&mut params.rest_args()?)?;
Ok(Arguments { Ok(Arguments {
radix: if let Some(arg) = params.get_flag("radix") { radix: params.get_flag("radix")?,
Some(arg?)
} else {
None
},
column_paths, column_paths,
}) })
})?; })?;

View File

@ -25,11 +25,7 @@ where
{ {
let (options, input) = args.extract(|params| { let (options, input) = args.extract(|params| {
Ok(Arc::new(Arguments { Ok(Arc::new(Arguments {
character: if let Some(arg) = params.get_flag("char") { character: params.get_flag("char")?,
Some(arg?)
} else {
None
},
column_paths: params.rest_args()?, column_paths: params.rest_args()?,
})) }))
})?; })?;

View File

@ -176,8 +176,8 @@ fn table(args: CommandArgs) -> Result<OutputStream, ShellError> {
// config.toml.... yet. // config.toml.... yet.
let color_hm = get_color_config(&configuration); let color_hm = get_color_config(&configuration);
let mut start_number = if let Some(f) = args.get_flag("start_number") { let mut start_number = if let Some(f) = args.get_flag("start_number")? {
f? f
} else { } else {
0 0
}; };

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue}; use nu_protocol::{Signature, UntaggedValue};
#[derive(Clone)] #[derive(Clone)]
pub struct To; pub struct To;
@ -19,10 +19,10 @@ impl WholeStreamCommand for To {
"Convert table into an output format (based on subcommand, like csv, html, json, yaml)." "Convert table into an output format (based on subcommand, like csv, html, json, yaml)."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&To, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&To, &args.scope)).into_value(Tag::unknown()),
))) ))
} }
} }

View File

@ -6,12 +6,6 @@ use nu_protocol::{Primitive, Signature, SyntaxShape, UntaggedValue, Value};
pub struct ToCsv; pub struct ToCsv;
#[derive(Deserialize)]
pub struct ToCsvArgs {
noheaders: bool,
separator: Option<Value>,
}
impl WholeStreamCommand for ToCsv { impl WholeStreamCommand for ToCsv {
fn name(&self) -> &str { fn name(&self) -> &str {
"to csv" "to csv"
@ -36,20 +30,17 @@ impl WholeStreamCommand for ToCsv {
"Convert table into .csv text " "Convert table into .csv text "
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_csv(args) to_csv(args)
} }
} }
fn to_csv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_csv(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let ( let args = args.evaluate_once()?;
ToCsvArgs { let separator: Option<Value> = args.get_flag("separator")?;
separator, let noheaders = args.has_flag("noheaders");
noheaders, let input = args.input;
},
input,
) = args.process()?;
let sep = match separator { let sep = match separator {
Some(Value { Some(Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),

View File

@ -2,7 +2,7 @@ use crate::prelude::*;
use csv::WriterBuilder; use csv::WriterBuilder;
use indexmap::{indexset, IndexSet}; use indexmap::{indexset, IndexSet};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, UntaggedValue, Value}; use nu_protocol::{Primitive, UntaggedValue, Value};
use nu_source::Spanned; use nu_source::Spanned;
use nu_value_ext::{as_string, ValueExt}; use nu_value_ext::{as_string, ValueExt};
@ -170,7 +170,7 @@ pub fn to_delimited_data(
format_name: &'static str, format_name: &'static str,
input: InputStream, input: InputStream,
name: Tag, name: Tag,
) -> Result<ActionStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let name_tag = name; let name_tag = name;
let name_span = name_tag.span; let name_span = name_tag.span;
@ -197,9 +197,7 @@ pub fn to_delimited_data(
x.replace_range(0..start, ""); x.replace_range(0..start, "");
} }
} }
ReturnSuccess::value( UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag)
UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag),
)
} }
Err(_) => { Err(_) => {
let expected = format!( let expected = format!(
@ -207,7 +205,7 @@ pub fn to_delimited_data(
format_name format_name
); );
let requires = format!("requires {}-compatible input", format_name); let requires = format!("requires {}-compatible input", format_name);
Err(ShellError::labeled_error_with_secondary( Value::error(ShellError::labeled_error_with_secondary(
expected, expected,
requires, requires,
name_span, name_span,
@ -217,5 +215,5 @@ pub fn to_delimited_data(
} }
} }
})) }))
.to_action_stream()) .to_output_stream())
} }

View File

@ -3,7 +3,7 @@ use crate::prelude::*;
use nu_data::value::format_leaf; use nu_data::value::format_leaf;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::{AnchorLocation, Tagged}; use nu_source::{AnchorLocation, Tagged};
use regex::Regex; use regex::Regex;
use rust_embed::RustEmbed; use rust_embed::RustEmbed;
@ -81,16 +81,6 @@ struct Assets;
pub struct ToHtml; pub struct ToHtml;
#[derive(Deserialize)]
pub struct ToHtmlArgs {
html_color: bool,
no_color: bool,
dark: bool,
partial: bool,
theme: Option<Tagged<String>>,
list: bool,
}
impl WholeStreamCommand for ToHtml { impl WholeStreamCommand for ToHtml {
fn name(&self) -> &str { fn name(&self) -> &str {
"to html" "to html"
@ -123,7 +113,7 @@ impl WholeStreamCommand for ToHtml {
"Convert table into simple HTML" "Convert table into simple HTML"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_html(args) to_html(args)
} }
} }
@ -267,20 +257,17 @@ fn get_list_of_theme_names() -> Vec<String> {
theme_names theme_names
} }
fn to_html(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let ( let args = args.evaluate_once()?;
ToHtmlArgs { let html_color = args.has_flag("html_color");
html_color, let no_color = args.has_flag("no_color");
no_color, let dark = args.has_flag("dark");
dark, let partial = args.has_flag("partial");
partial, let list = args.has_flag("list");
theme, let theme: Option<Tagged<String>> = args.get_flag("theme")?;
list,
}, let input: Vec<Value> = args.input.collect();
input,
) = args.process()?;
let input: Vec<Value> = input.collect();
let headers = nu_protocol::merge_descriptors(&input); let headers = nu_protocol::merge_descriptors(&input);
let headers = Some(headers) let headers = Some(headers)
.filter(|headers| !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty())); .filter(|headers| !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty()));
@ -300,9 +287,9 @@ fn to_html(args: CommandArgs) -> Result<ActionStream, ShellError> {
output_string.push_str("https://github.com/mbadolato/iTerm2-Color-Schemes\n"); output_string.push_str("https://github.com/mbadolato/iTerm2-Color-Schemes\n");
// Short circuit and return the output_string // Short circuit and return the output_string
Ok(ActionStream::one(ReturnSuccess::value( Ok(OutputStream::one(
UntaggedValue::string(output_string).into_value(name_tag), UntaggedValue::string(output_string).into_value(name_tag),
))) ))
} else { } else {
let theme_tag = match &theme { let theme_tag = match &theme {
Some(v) => &v.tag, Some(v) => &v.tag,
@ -376,9 +363,9 @@ fn to_html(args: CommandArgs) -> Result<ActionStream, ShellError> {
output_string = run_regexes(&regex_hm, &output_string); output_string = run_regexes(&regex_hm, &output_string);
} }
Ok(ActionStream::one(ReturnSuccess::value( Ok(OutputStream::one(
UntaggedValue::string(output_string).into_value(name_tag), UntaggedValue::string(output_string).into_value(name_tag),
))) ))
} }
} }

View File

@ -1,19 +1,12 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::{CoerceInto, ShellError}; use nu_errors::{CoerceInto, ShellError};
use nu_protocol::{ use nu_protocol::{Primitive, Signature, SyntaxShape, UnspannedPathMember, UntaggedValue, Value};
Primitive, ReturnSuccess, Signature, SyntaxShape, UnspannedPathMember, UntaggedValue, Value,
};
use serde::Serialize; use serde::Serialize;
use serde_json::json; use serde_json::json;
pub struct ToJson; pub struct ToJson;
#[derive(Deserialize)]
pub struct ToJsonArgs {
pretty: Option<Value>,
}
impl WholeStreamCommand for ToJson { impl WholeStreamCommand for ToJson {
fn name(&self) -> &str { fn name(&self) -> &str {
"to json" "to json"
@ -32,7 +25,7 @@ impl WholeStreamCommand for ToJson {
"Converts table data into JSON text." "Converts table data into JSON text."
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_json(args) to_json(args)
} }
@ -157,11 +150,13 @@ fn json_list(input: &[Value]) -> Result<Vec<serde_json::Value>, ShellError> {
Ok(out) Ok(out)
} }
fn to_json(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let (ToJsonArgs { pretty }, input) = args.process()?; let args = args.evaluate_once()?;
let pretty: Option<Value> = args.get_flag("pretty")?;
let name_span = name_tag.span; let name_span = name_tag.span;
let input: Vec<Value> = input.collect(); let input: Vec<Value> = args.input.collect();
let to_process_input = match input.len() { let to_process_input = match input.len() {
x if x > 1 => { x if x > 1 => {
@ -221,7 +216,7 @@ fn to_json(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
if pretty_format_failed { if pretty_format_failed {
return Err(ShellError::labeled_error( return Value::error(ShellError::labeled_error(
"Pretty formatting failed", "Pretty formatting failed",
"failed", "failed",
pretty_value.tag(), pretty_value.tag(),
@ -229,12 +224,10 @@ fn to_json(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
} }
ReturnSuccess::value(
UntaggedValue::Primitive(Primitive::String(serde_json_string)) UntaggedValue::Primitive(Primitive::String(serde_json_string))
.into_value(&value.tag), .into_value(&value.tag)
)
} }
_ => Err(ShellError::labeled_error_with_secondary( _ => Value::error(ShellError::labeled_error_with_secondary(
"Expected a table with JSON-compatible structure.tag() from pipeline", "Expected a table with JSON-compatible structure.tag() from pipeline",
"requires JSON-compatible input", "requires JSON-compatible input",
name_span, name_span,
@ -243,13 +236,13 @@ fn to_json(args: CommandArgs) -> Result<ActionStream, ShellError> {
)), )),
} }
} }
_ => Err(ShellError::labeled_error( _ => Value::error(ShellError::labeled_error(
"Expected a table with JSON-compatible structure from pipeline", "Expected a table with JSON-compatible structure from pipeline",
"requires JSON-compatible input", "requires JSON-compatible input",
&name_tag, &name_tag,
)), )),
})) }))
.to_action_stream()) .to_output_stream())
} }
#[cfg(test)] #[cfg(test)]

View File

@ -3,7 +3,7 @@ use crate::prelude::*;
use nu_data::value::format_leaf; use nu_data::value::format_leaf;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue, Value}; use nu_protocol::{Signature, UntaggedValue, Value};
pub struct Command; pub struct Command;
@ -37,7 +37,7 @@ impl WholeStreamCommand for Command {
"Convert table into simple Markdown" "Convert table into simple Markdown"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_md(args) to_md(args)
} }
@ -82,19 +82,23 @@ impl WholeStreamCommand for Command {
} }
} }
fn to_md(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_md(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let (arguments, input) = args.process()?; let args = args.evaluate_once()?;
let arguments = Arguments {
per_element: args.has_flag("per-element"),
pretty: args.has_flag("pretty"),
};
let input: Vec<Value> = input.collect(); let input: Vec<Value> = args.input.collect();
Ok(ActionStream::one(ReturnSuccess::value( Ok(OutputStream::one(
UntaggedValue::string(process(&input, arguments)).into_value(if input.is_empty() { UntaggedValue::string(process(&input, arguments)).into_value(if input.is_empty() {
name_tag name_tag
} else { } else {
input[0].tag() input[0].tag()
}), }),
))) ))
} }
fn process( fn process(

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::{CoerceInto, ShellError}; use nu_errors::{CoerceInto, ShellError};
use nu_protocol::{Primitive, ReturnSuccess, Signature, UnspannedPathMember, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, UnspannedPathMember, UntaggedValue, Value};
pub struct ToToml; pub struct ToToml;
@ -18,20 +18,9 @@ impl WholeStreamCommand for ToToml {
"Convert table into .toml text" "Convert table into .toml text"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_toml(args) to_toml(args)
} }
// TODO: add an example here. What commands to run to get a Row(Dictionary)?
// fn examples(&self) -> Vec<Example> {
// vec![
// Example {
// description:
// "Outputs an TOML string representing TOML document",
// example: "echo [1 2 3] | to json",
// result: Some(vec![Value::from("[1,2,3]")]),
// },
// ]
// }
} }
// Helper method to recursively convert nu_protocol::Value -> toml::Value // Helper method to recursively convert nu_protocol::Value -> toml::Value
@ -139,7 +128,7 @@ fn collect_values(input: &[Value]) -> Result<Vec<toml::Value>, ShellError> {
Ok(out) Ok(out)
} }
fn to_toml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_toml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let name_tag = args.name_tag(); let name_tag = args.name_tag();
let name_span = name_tag.span; let name_span = name_tag.span;
@ -161,10 +150,9 @@ fn to_toml(args: CommandArgs) -> Result<ActionStream, ShellError> {
let value_span = value.tag.span; let value_span = value.tag.span;
match value_to_toml_value(&value) { match value_to_toml_value(&value) {
Ok(toml_value) => match toml::to_string(&toml_value) { Ok(toml_value) => match toml::to_string(&toml_value) {
Ok(x) => ReturnSuccess::value( Ok(x) => UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag),
UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag),
), _ => Value::error(ShellError::labeled_error_with_secondary(
_ => Err(ShellError::labeled_error_with_secondary(
"Expected a table with TOML-compatible structure.tag() from pipeline", "Expected a table with TOML-compatible structure.tag() from pipeline",
"requires TOML-compatible input", "requires TOML-compatible input",
name_span, name_span,
@ -172,14 +160,14 @@ fn to_toml(args: CommandArgs) -> Result<ActionStream, ShellError> {
value_span, value_span,
)), )),
}, },
_ => Err(ShellError::labeled_error( _ => Value::error(ShellError::labeled_error(
"Expected a table with TOML-compatible structure from pipeline", "Expected a table with TOML-compatible structure from pipeline",
"requires TOML-compatible input", "requires TOML-compatible input",
&name_tag, &name_tag,
)), )),
} }
})) }))
.to_action_stream()) .to_output_stream())
} }
#[cfg(test)] #[cfg(test)]

View File

@ -6,11 +6,6 @@ use nu_protocol::Signature;
pub struct ToTsv; pub struct ToTsv;
#[derive(Deserialize)]
pub struct ToTsvArgs {
noheaders: bool,
}
impl WholeStreamCommand for ToTsv { impl WholeStreamCommand for ToTsv {
fn name(&self) -> &str { fn name(&self) -> &str {
"to tsv" "to tsv"
@ -28,16 +23,17 @@ impl WholeStreamCommand for ToTsv {
"Convert table into .tsv text" "Convert table into .tsv text"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_tsv(args) to_tsv(args)
} }
} }
fn to_tsv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_tsv(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let (ToTsvArgs { noheaders }, input) = args.process()?; let args = args.evaluate_once()?;
let noheaders = args.has_flag("noheaders");
to_delimited_data(noheaders, '\t', "TSV", input, name) to_delimited_data(noheaders, '\t', "TSV", args.input, name)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue, Value}; use nu_protocol::{Signature, UntaggedValue, Value};
pub struct ToUrl; pub struct ToUrl;
@ -18,12 +18,12 @@ impl WholeStreamCommand for ToUrl {
"Convert table into url-encoded text" "Convert table into url-encoded text"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_url(args) to_url(args)
} }
} }
fn to_url(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_url(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let tag = args.name_tag(); let tag = args.name_tag();
let input = args.input; let input = args.input;
@ -41,7 +41,7 @@ fn to_url(args: CommandArgs) -> Result<ActionStream, ShellError> {
row_vec.push((k.clone(), s.to_string())); row_vec.push((k.clone(), s.to_string()));
} }
_ => { _ => {
return Err(ShellError::labeled_error_with_secondary( return Value::error(ShellError::labeled_error_with_secondary(
"Expected table with string values", "Expected table with string values",
"requires table with strings", "requires table with strings",
&tag, &tag,
@ -53,15 +53,15 @@ fn to_url(args: CommandArgs) -> Result<ActionStream, ShellError> {
} }
match serde_urlencoded::to_string(row_vec) { match serde_urlencoded::to_string(row_vec) {
Ok(s) => ReturnSuccess::value(UntaggedValue::string(s).into_value(&tag)), Ok(s) => UntaggedValue::string(s).into_value(&tag),
_ => Err(ShellError::labeled_error( _ => Value::error(ShellError::labeled_error(
"Failed to convert to url-encoded", "Failed to convert to url-encoded",
"cannot url-encode", "cannot url-encode",
&tag, &tag,
)), )),
} }
} }
Value { tag: value_tag, .. } => Err(ShellError::labeled_error_with_secondary( Value { tag: value_tag, .. } => Value::error(ShellError::labeled_error_with_secondary(
"Expected a table from pipeline", "Expected a table from pipeline",
"requires table input", "requires table input",
&tag, &tag,
@ -69,7 +69,7 @@ fn to_url(args: CommandArgs) -> Result<ActionStream, ShellError> {
value_tag.span, value_tag.span,
)), )),
}) })
.to_action_stream()) .to_output_stream())
} }
#[cfg(test)] #[cfg(test)]

View File

@ -2,7 +2,7 @@ use crate::prelude::*;
use indexmap::IndexMap; use indexmap::IndexMap;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, SyntaxShape, UntaggedValue, Value};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use std::collections::HashSet; use std::collections::HashSet;
use std::io::Cursor; use std::io::Cursor;
@ -10,11 +10,6 @@ use std::io::Write;
pub struct ToXml; pub struct ToXml;
#[derive(Deserialize)]
pub struct ToXmlArgs {
pretty: Option<Value>,
}
impl WholeStreamCommand for ToXml { impl WholeStreamCommand for ToXml {
fn name(&self) -> &str { fn name(&self) -> &str {
"to xml" "to xml"
@ -33,7 +28,7 @@ impl WholeStreamCommand for ToXml {
"Convert table into .xml text" "Convert table into .xml text"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_xml(args) to_xml(args)
} }
} }
@ -131,11 +126,12 @@ pub fn write_xml_events<W: Write>(
Ok(()) Ok(())
} }
fn to_xml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_xml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name_tag = args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let name_span = name_tag.span; let name_span = name_tag.span;
let (ToXmlArgs { pretty }, input) = args.process()?; let args = args.evaluate_once()?;
let input: Vec<Value> = input.collect(); let pretty: Option<Value> = args.get_flag("pretty")?;
let input: Vec<Value> = args.input.collect();
let to_process_input = match input.len() { let to_process_input = match input.len() {
x if x > 1 => { x if x > 1 => {
@ -166,12 +162,16 @@ fn to_xml(args: CommandArgs) -> Result<ActionStream, ShellError> {
match write_xml_events(&value, &mut w) { match write_xml_events(&value, &mut w) {
Ok(_) => { Ok(_) => {
let b = w.into_inner().into_inner(); let b = w.into_inner().into_inner();
let s = String::from_utf8(b)?; let s = if let Ok(s) = String::from_utf8(b) {
ReturnSuccess::value( s
UntaggedValue::Primitive(Primitive::String(s)).into_value(&name_tag), } else {
) return Value::error(ShellError::untagged_runtime_error(
"Could not convert a string to utf-8",
));
};
UntaggedValue::Primitive(Primitive::String(s)).into_value(&name_tag)
} }
Err(_) => Err(ShellError::labeled_error_with_secondary( Err(_) => Value::error(ShellError::labeled_error_with_secondary(
"Expected a table with XML-compatible structure from pipeline", "Expected a table with XML-compatible structure from pipeline",
"requires XML-compatible input", "requires XML-compatible input",
name_span, name_span,
@ -180,7 +180,7 @@ fn to_xml(args: CommandArgs) -> Result<ActionStream, ShellError> {
)), )),
} }
})) }))
.to_action_stream()) .to_output_stream())
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::WholeStreamCommand; use nu_engine::WholeStreamCommand;
use nu_errors::{CoerceInto, ShellError}; use nu_errors::{CoerceInto, ShellError};
use nu_protocol::{Primitive, ReturnSuccess, Signature, UnspannedPathMember, UntaggedValue, Value}; use nu_protocol::{Primitive, Signature, UnspannedPathMember, UntaggedValue, Value};
pub struct ToYaml; pub struct ToYaml;
@ -18,7 +18,7 @@ impl WholeStreamCommand for ToYaml {
"Convert table into .yaml/.yml text" "Convert table into .yaml/.yml text"
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
to_yaml(args) to_yaml(args)
} }
} }
@ -113,7 +113,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
}) })
} }
fn to_yaml(args: CommandArgs) -> Result<ActionStream, ShellError> { fn to_yaml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
let name_tag = args.name_tag(); let name_tag = args.name_tag();
let name_span = name_tag.span; let name_span = name_tag.span;
@ -137,10 +137,9 @@ fn to_yaml(args: CommandArgs) -> Result<ActionStream, ShellError> {
match value_to_yaml_value(&value) { match value_to_yaml_value(&value) {
Ok(yaml_value) => match serde_yaml::to_string(&yaml_value) { Ok(yaml_value) => match serde_yaml::to_string(&yaml_value) {
Ok(x) => ReturnSuccess::value( Ok(x) => UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag),
UntaggedValue::Primitive(Primitive::String(x)).into_value(&name_tag),
), _ => Value::error(ShellError::labeled_error_with_secondary(
_ => Err(ShellError::labeled_error_with_secondary(
"Expected a table with YAML-compatible structure from pipeline", "Expected a table with YAML-compatible structure from pipeline",
"requires YAML-compatible input", "requires YAML-compatible input",
name_span, name_span,
@ -148,14 +147,14 @@ fn to_yaml(args: CommandArgs) -> Result<ActionStream, ShellError> {
value_span, value_span,
)), )),
}, },
_ => Err(ShellError::labeled_error( _ => Value::error(ShellError::labeled_error(
"Expected a table with YAML-compatible structure from pipeline", "Expected a table with YAML-compatible structure from pipeline",
"requires YAML-compatible input", "requires YAML-compatible input",
&name_tag, &name_tag,
)), )),
} }
})) }))
.to_action_stream()) .to_output_stream())
} }
#[cfg(test)] #[cfg(test)]

View File

@ -229,11 +229,12 @@ impl EvaluatedCommandArgs {
.ok_or_else(|| ShellError::unimplemented("Better error: expect_nth")) .ok_or_else(|| ShellError::unimplemented("Better error: expect_nth"))
} }
pub fn get_flag<T: FromValue>(&self, name: &str) -> Option<Result<T, ShellError>> { pub fn get_flag<T: FromValue>(&self, name: &str) -> Result<Option<T>, ShellError> {
self.call_info if let Some(arg) = self.call_info.args.get(name) {
.args FromValue::from_value(arg).map(Some)
.get(name) } else {
.map(|x| FromValue::from_value(x)) Ok(None)
}
} }
pub fn req_named<T: FromValue>(&self, name: &str) -> Result<T, ShellError> { pub fn req_named<T: FromValue>(&self, name: &str) -> Result<T, ShellError> {
@ -259,11 +260,11 @@ impl EvaluatedCommandArgs {
} }
} }
pub fn opt<T: FromValue>(&self, pos: usize) -> Option<Result<T, ShellError>> { pub fn opt<T: FromValue>(&self, pos: usize) -> Result<Option<T>, ShellError> {
if let Some(v) = self.nth(pos) { if let Some(v) = self.nth(pos) {
Some(FromValue::from_value(v)) FromValue::from_value(v).map(Some)
} else { } else {
None Ok(None)
} }
} }

View File

@ -6,9 +6,8 @@ use nu_parser::ParserScope;
use nu_protocol::hir::{ use nu_protocol::hir::{
Block, Call, ClassifiedCommand, Expression, Pipeline, SpannedExpression, Synthetic, Block, Call, ClassifiedCommand, Expression, Pipeline, SpannedExpression, Synthetic,
}; };
use nu_protocol::{ReturnSuccess, UntaggedValue, Value}; use nu_protocol::{UntaggedValue, Value};
use nu_source::{Span, Tag}; use nu_source::{Span, Tag};
use nu_stream::ToActionStream;
use nu_stream::{InputStream, OutputStream}; use nu_stream::{InputStream, OutputStream};
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
@ -79,17 +78,15 @@ pub fn run_block(
for pipeline in &group.pipelines { for pipeline in &group.pipelines {
match output { match output {
Ok(inp) if inp.is_empty() => {} Ok(inp) if inp.is_empty() => {}
Ok(inp) => { Ok(mut output_stream) => {
let mut output_stream = inp.to_action_stream();
match output_stream.next() { match output_stream.next() {
Some(Ok(ReturnSuccess::Value(Value { Some(Value {
value: UntaggedValue::Error(e), value: UntaggedValue::Error(e),
.. ..
}))) => { }) => {
return Err(e); return Err(e);
} }
Some(Ok(_item)) => { Some(_item) => {
if let Some(err) = ctx.get_errors().get(0) { if let Some(err) = ctx.get_errors().get(0) {
ctx.clear_errors(); ctx.clear_errors();
return Err(err.clone()); return Err(err.clone());
@ -109,9 +106,6 @@ pub fn run_block(
return Err(err.clone()); return Err(err.clone());
} }
} }
Some(Err(e)) => {
return Err(e);
}
} }
} }
Err(e) => { Err(e) => {

View File

@ -9,7 +9,7 @@ use encoding_rs::Encoding;
use nu_data::config::LocalConfigDiff; use nu_data::config::LocalConfigDiff;
use nu_protocol::{CommandAction, ConfigPath, TaggedDictBuilder, Value}; use nu_protocol::{CommandAction, ConfigPath, TaggedDictBuilder, Value};
use nu_source::{Span, Tag}; use nu_source::{Span, Tag};
use nu_stream::{ActionStream, Interruptible, ToActionStream}; use nu_stream::{ActionStream, Interruptible, OutputStream, ToActionStream};
use std::collections::VecDeque; use std::collections::VecDeque;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -860,9 +860,9 @@ impl Shell for FilesystemShell {
full_path: &Path, full_path: &Path,
save_data: &[u8], save_data: &[u8],
name: Span, name: Span,
) -> Result<ActionStream, ShellError> { ) -> Result<OutputStream, ShellError> {
match std::fs::write(full_path, save_data) { match std::fs::write(full_path, save_data) {
Ok(_) => Ok(ActionStream::empty()), Ok(_) => Ok(OutputStream::empty()),
Err(e) => Err(ShellError::labeled_error( Err(e) => Err(ShellError::labeled_error(
e.to_string(), e.to_string(),
"IO error while saving", "IO error while saving",

View File

@ -166,6 +166,26 @@ impl FromValue for PathBuf {
} }
} }
impl FromValue for Tagged<PathBuf> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
match v {
Value {
value: UntaggedValue::Primitive(Primitive::String(s)),
tag,
} => Ok(PathBuf::from(s).tagged(tag)),
Value {
value: UntaggedValue::Primitive(Primitive::FilePath(p)),
tag,
} => Ok(p.clone().tagged(tag)),
Value { tag, .. } => Err(ShellError::labeled_error(
"Can't convert to filepath",
"can't convert to filepath",
tag.span,
)),
}
}
}
impl FromValue for ColumnPath { impl FromValue for ColumnPath {
fn from_value(v: &Value) -> Result<Self, ShellError> { fn from_value(v: &Value) -> Result<Self, ShellError> {
match v { match v {

View File

@ -1,4 +1,4 @@
use nu_stream::ActionStream; use nu_stream::{ActionStream, OutputStream};
use crate::command_args::EvaluatedWholeStreamCommandArgs; use crate::command_args::EvaluatedWholeStreamCommandArgs;
use crate::maybe_text_codec::StringOrBinary; use crate::maybe_text_codec::StringOrBinary;
@ -49,5 +49,5 @@ pub trait Shell: std::fmt::Debug {
path: &Path, path: &Path,
contents: &[u8], contents: &[u8],
name: Span, name: Span,
) -> Result<ActionStream, ShellError>; ) -> Result<OutputStream, ShellError>;
} }

View File

@ -1,7 +1,7 @@
use crate::shell::Shell; use crate::shell::Shell;
use crate::{command_args::EvaluatedWholeStreamCommandArgs, FilesystemShell}; use crate::{command_args::EvaluatedWholeStreamCommandArgs, FilesystemShell};
use crate::{filesystem::filesystem_shell::FilesystemShellMode, maybe_text_codec::StringOrBinary}; use crate::{filesystem::filesystem_shell::FilesystemShellMode, maybe_text_codec::StringOrBinary};
use nu_stream::ActionStream; use nu_stream::{ActionStream, OutputStream};
use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs}; use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
use encoding_rs::Encoding; use encoding_rs::Encoding;
@ -96,7 +96,7 @@ impl ShellManager {
full_path: &Path, full_path: &Path,
save_data: &[u8], save_data: &[u8],
name: Span, name: Span,
) -> Result<ActionStream, ShellError> { ) -> Result<OutputStream, ShellError> {
self.shells.lock()[self.current_shell()].save(full_path, save_data, name) self.shells.lock()[self.current_shell()].save(full_path, save_data, name)
} }

View File

@ -8,7 +8,7 @@ use nu_protocol::ValueStructure;
use nu_protocol::{ReturnSuccess, ShellTypeName, UntaggedValue, Value}; use nu_protocol::{ReturnSuccess, ShellTypeName, UntaggedValue, Value};
use nu_source::SpannedItem; use nu_source::SpannedItem;
use nu_source::{Span, Tag, Tagged}; use nu_source::{Span, Tag, Tagged};
use nu_stream::ActionStream; use nu_stream::{ActionStream, OutputStream};
use nu_value_ext::ValueExt; use nu_value_ext::ValueExt;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::ffi::OsStr; use std::ffi::OsStr;
@ -247,7 +247,7 @@ impl Shell for ValueShell {
_path: &Path, _path: &Path,
_contents: &[u8], _contents: &[u8],
_name: Span, _name: Span,
) -> Result<ActionStream, ShellError> { ) -> Result<OutputStream, ShellError> {
Err(ShellError::unimplemented( Err(ShellError::unimplemented(
"save on help shell is not supported", "save on help shell is not supported",
)) ))

View File

@ -641,7 +641,7 @@ impl ShellError {
} }
pub fn unimplemented(title: impl Into<String>) -> ShellError { pub fn unimplemented(title: impl Into<String>) -> ShellError {
ShellError::unimplemented(&format!("Unimplemented: {}", title.into())) ShellError::untagged_runtime_error(&format!("Unimplemented: {}", title.into()))
} }
pub fn unexpected(title: impl Into<String>) -> ShellError { pub fn unexpected(title: impl Into<String>) -> ShellError {