2019-11-11 11:54:58 +00:00
|
|
|
use crate::commands::from_structured_data::from_structured_data;
|
2019-08-19 05:16:39 +00:00
|
|
|
use crate::commands::WholeStreamCommand;
|
2019-11-11 11:54:58 +00:00
|
|
|
use crate::data::{Primitive, Value};
|
2019-07-19 20:11:49 +00:00
|
|
|
use crate::prelude::*;
|
|
|
|
|
2019-08-19 05:16:39 +00:00
|
|
|
pub struct FromCSV;
|
|
|
|
|
2019-08-25 12:59:46 +00:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct FromCSVArgs {
|
|
|
|
headerless: bool,
|
2019-11-08 13:11:04 +00:00
|
|
|
separator: Option<Tagged<Value>>,
|
2019-08-25 12:59:46 +00:00
|
|
|
}
|
2019-08-19 05:16:39 +00:00
|
|
|
|
2019-08-25 12:59:46 +00:00
|
|
|
impl WholeStreamCommand for FromCSV {
|
2019-08-19 05:16:39 +00:00
|
|
|
fn name(&self) -> &str {
|
|
|
|
"from-csv"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
2019-10-28 05:15:35 +00:00
|
|
|
Signature::build("from-csv")
|
2019-11-08 15:27:29 +00:00
|
|
|
.named(
|
|
|
|
"separator",
|
|
|
|
SyntaxShape::String,
|
|
|
|
"a character to separate columns, defaults to ','",
|
|
|
|
)
|
2019-10-28 05:15:35 +00:00
|
|
|
.switch("headerless", "don't treat the first row as column names")
|
2019-08-29 22:52:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
2019-11-11 11:01:21 +00:00
|
|
|
"Parse text as .csv and create table."
|
2019-08-25 12:59:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
args.process(registry, from_csv)?.run()
|
2019-08-19 05:16:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-25 12:59:46 +00:00
|
|
|
fn from_csv(
|
|
|
|
FromCSVArgs {
|
2019-11-11 11:01:21 +00:00
|
|
|
headerless,
|
2019-11-08 13:11:04 +00:00
|
|
|
separator,
|
2019-08-25 12:59:46 +00:00
|
|
|
}: FromCSVArgs,
|
2019-11-11 11:54:58 +00:00
|
|
|
runnable_context: RunnableContext,
|
2019-08-25 12:59:46 +00:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2019-11-08 13:11:04 +00:00
|
|
|
let sep = match separator {
|
2019-11-08 15:27:29 +00:00
|
|
|
Some(Tagged {
|
|
|
|
item: Value::Primitive(Primitive::String(s)),
|
|
|
|
tag,
|
|
|
|
..
|
|
|
|
}) => {
|
2019-11-08 13:11:04 +00:00
|
|
|
let vec_s: Vec<char> = s.chars().collect();
|
|
|
|
if vec_s.len() != 1 {
|
|
|
|
return Err(ShellError::labeled_error(
|
|
|
|
"Expected a single separator char from --separator",
|
|
|
|
"requires a single character string input",
|
|
|
|
tag,
|
2019-11-08 15:27:29 +00:00
|
|
|
));
|
2019-11-08 13:11:04 +00:00
|
|
|
};
|
|
|
|
vec_s[0]
|
|
|
|
}
|
2019-11-08 15:27:29 +00:00
|
|
|
_ => ',',
|
2019-11-08 13:11:04 +00:00
|
|
|
};
|
2019-07-19 20:11:49 +00:00
|
|
|
|
2019-11-11 11:54:58 +00:00
|
|
|
from_structured_data(headerless, sep, "CSV", runnable_context)
|
2019-07-19 20:11:49 +00:00
|
|
|
}
|