nushell/crates/nu-cli/src/commands/t_sort_by.rs

92 lines
2.5 KiB
Rust
Raw Normal View History

2019-11-12 08:07:43 +01:00
use crate::commands::WholeStreamCommand;
use crate::data::TaggedListBuilder;
2019-11-12 08:07:43 +01:00
use crate::prelude::*;
use crate::utils::data_processing::{columns_sorted, t_sort};
2019-11-12 08:07:43 +01:00
use chrono::{DateTime, NaiveDate, Utc};
use nu_errors::ShellError;
use nu_protocol::{
Primitive, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value,
};
use nu_source::Tagged;
2019-12-09 19:52:01 +01:00
use nu_value_ext::get_data_by_key;
2019-11-12 08:07:43 +01:00
pub struct TSortBy;
#[derive(Deserialize)]
pub struct TSortByArgs {
#[serde(rename(deserialize = "show-columns"))]
show_columns: bool,
group_by: Option<Tagged<String>>,
#[allow(unused)]
split_by: Option<String>,
}
impl WholeStreamCommand for TSortBy {
fn name(&self) -> &str {
"t-sort-by"
}
fn signature(&self) -> Signature {
Signature::build("t-sort-by")
.switch(
"show-columns",
"Displays the column names sorted",
Some('c'),
)
2019-11-12 08:07:43 +01:00
.named(
"group_by",
SyntaxShape::String,
"the name of the column to group by",
Some('g'),
2019-11-12 08:07:43 +01:00
)
.named(
"split_by",
SyntaxShape::String,
"the name of the column within the grouped by table to split by",
Some('s'),
2019-11-12 08:07:43 +01:00
)
}
fn usage(&self) -> &str {
"Sort by the given columns."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, t_sort_by)?.run()
}
}
fn t_sort_by(
TSortByArgs {
show_columns,
group_by,
..
}: TSortByArgs,
RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
Ok(OutputStream::new(async_stream! {
let values: Vec<Value> = input.values.collect().await;
2019-11-12 08:07:43 +01:00
let column_grouped_by_name = if let Some(grouped_by) = group_by {
Some(grouped_by.item().clone())
} else {
None
};
2019-11-12 08:07:43 +01:00
if show_columns {
2019-11-04 16:47:03 +01:00
for label in columns_sorted(column_grouped_by_name, &values[0], &name).into_iter() {
yield ReturnSuccess::value(UntaggedValue::string(label.item).into_value(label.tag));
}
} else {
match t_sort(column_grouped_by_name, None, &values[0], name) {
Ok(sorted) => yield ReturnSuccess::value(sorted),
Err(err) => yield Err(err)
2019-11-12 08:07:43 +01:00
}
}
}))
2019-11-12 08:07:43 +01:00
}