2021-10-09 04:45:25 +02:00
|
|
|
use nu_engine::CallExt;
|
|
|
|
use nu_protocol::{
|
|
|
|
ast::Call,
|
|
|
|
engine::{Command, EvaluationContext},
|
2021-10-25 06:01:02 +02:00
|
|
|
IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
|
2021-10-09 04:45:25 +02:00
|
|
|
};
|
|
|
|
|
2021-10-25 06:01:02 +02:00
|
|
|
#[derive(Clone)]
|
2021-10-09 04:45:25 +02:00
|
|
|
pub struct SubCommand;
|
|
|
|
|
|
|
|
impl Command for SubCommand {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"split row"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("split row").required(
|
|
|
|
"separator",
|
|
|
|
SyntaxShape::String,
|
|
|
|
"the character that denotes what separates rows",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"splits contents over multiple rows via the separator."
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
context: &EvaluationContext,
|
|
|
|
call: &Call,
|
2021-10-25 06:01:02 +02:00
|
|
|
input: PipelineData,
|
|
|
|
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
2021-10-09 04:45:25 +02:00
|
|
|
split_row(context, call, input)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn split_row(
|
|
|
|
context: &EvaluationContext,
|
|
|
|
call: &Call,
|
2021-10-25 06:01:02 +02:00
|
|
|
input: PipelineData,
|
|
|
|
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
2021-10-09 04:45:25 +02:00
|
|
|
let name_span = call.head;
|
|
|
|
let separator: Spanned<String> = call.req(context, 0)?;
|
|
|
|
|
2021-10-25 06:01:02 +02:00
|
|
|
Ok(input
|
|
|
|
.flat_map(move |x| split_row_helper(&x, &separator, name_span))
|
|
|
|
.into_pipeline_data())
|
2021-10-09 04:45:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn split_row_helper(v: &Value, separator: &Spanned<String>, name: Span) -> Vec<Value> {
|
2021-10-11 20:45:31 +02:00
|
|
|
match v.span() {
|
|
|
|
Ok(v_span) => {
|
|
|
|
if let Ok(s) = v.as_string() {
|
|
|
|
let splitter = separator.item.replace("\\n", "\n");
|
|
|
|
s.split(&splitter)
|
|
|
|
.filter_map(|s| {
|
|
|
|
if s.trim() != "" {
|
2021-10-20 07:58:25 +02:00
|
|
|
Some(Value::string(s, v_span))
|
2021-10-11 20:45:31 +02:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2021-10-09 04:45:25 +02:00
|
|
|
})
|
2021-10-11 20:45:31 +02:00
|
|
|
.collect()
|
|
|
|
} else {
|
|
|
|
vec![Value::Error {
|
|
|
|
error: ShellError::PipelineMismatch {
|
|
|
|
expected: Type::String,
|
|
|
|
expected_span: name,
|
|
|
|
origin: v_span,
|
|
|
|
},
|
|
|
|
}]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(error) => vec![Value::Error { error }],
|
2021-10-09 04:45:25 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// #[cfg(test)]
|
|
|
|
// mod tests {
|
|
|
|
// use super::ShellError;
|
|
|
|
// use super::SubCommand;
|
|
|
|
|
|
|
|
// #[test]
|
|
|
|
// fn examples_work_as_expected() -> Result<(), ShellError> {
|
|
|
|
// use crate::examples::test as test_examples;
|
|
|
|
|
|
|
|
// test_examples(SubCommand {})
|
|
|
|
// }
|
|
|
|
// }
|