2020-04-26 08:34:45 +02:00
|
|
|
use crate::commands::WholeStreamCommand;
|
|
|
|
use crate::context::CommandRegistry;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use nu_errors::ShellError;
|
|
|
|
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, Value};
|
|
|
|
use nu_source::Tagged;
|
|
|
|
|
|
|
|
pub struct Drop;
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct DropArgs {
|
|
|
|
rows: Option<Tagged<u64>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WholeStreamCommand for Drop {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"drop"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("drop").optional(
|
|
|
|
"rows",
|
|
|
|
SyntaxShape::Number,
|
|
|
|
"starting from the back, the number of rows to drop",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Drop the last number of rows."
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
2020-05-16 05:18:24 +02:00
|
|
|
drop(args, registry)
|
2020-04-26 08:34:45 +02:00
|
|
|
}
|
2020-05-12 07:17:17 +02:00
|
|
|
|
|
|
|
fn examples(&self) -> &[Example] {
|
|
|
|
&[
|
|
|
|
Example {
|
|
|
|
description: "Remove the last item of a list/table",
|
|
|
|
example: "echo [1 2 3] | drop",
|
|
|
|
},
|
|
|
|
Example {
|
|
|
|
description: "Remove the last 2 items of a list/table",
|
|
|
|
example: "echo [1 2 3] | drop 2",
|
|
|
|
},
|
|
|
|
]
|
|
|
|
}
|
2020-04-26 08:34:45 +02:00
|
|
|
}
|
|
|
|
|
2020-05-16 05:18:24 +02:00
|
|
|
fn drop(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
|
|
|
|
let registry = registry.clone();
|
2020-04-26 08:34:45 +02:00
|
|
|
let stream = async_stream! {
|
2020-05-16 05:18:24 +02:00
|
|
|
let (DropArgs { rows }, mut input) = args.process(®istry).await?;
|
|
|
|
let v: Vec<_> = input.into_vec().await;
|
2020-04-26 08:34:45 +02:00
|
|
|
|
|
|
|
let rows_to_drop = if let Some(quantity) = rows {
|
|
|
|
*quantity as usize
|
|
|
|
} else {
|
|
|
|
1
|
|
|
|
};
|
|
|
|
|
|
|
|
if rows_to_drop < v.len() {
|
|
|
|
let k = v.len() - rows_to_drop;
|
|
|
|
for x in v[0..k].iter() {
|
|
|
|
let y: Value = x.clone();
|
|
|
|
yield ReturnSuccess::value(y)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(stream.to_output_stream())
|
|
|
|
}
|