2021-10-26 20:29:00 +02:00
|
|
|
use nu_engine::CallExt;
|
|
|
|
|
|
|
|
use nu_protocol::ast::Call;
|
|
|
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
2021-10-27 17:07:37 +02:00
|
|
|
use nu_protocol::{
|
2021-11-17 05:22:37 +01:00
|
|
|
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
|
|
|
|
SyntaxShape, Value,
|
2021-10-27 17:07:37 +02:00
|
|
|
};
|
2021-10-27 06:04:48 +02:00
|
|
|
use std::convert::TryInto;
|
2021-10-26 20:29:00 +02:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Last;
|
|
|
|
|
|
|
|
impl Command for Last {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"last"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
2021-11-17 05:22:37 +01:00
|
|
|
Signature::build("last")
|
|
|
|
.optional(
|
|
|
|
"rows",
|
|
|
|
SyntaxShape::Int,
|
|
|
|
"starting from the back, the number of rows to return",
|
|
|
|
)
|
|
|
|
.category(Category::Filters)
|
2021-10-26 20:29:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Show only the last number of rows."
|
|
|
|
}
|
|
|
|
|
2021-10-27 17:07:37 +02:00
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![Example {
|
|
|
|
example: "[1,2,3] | last 2",
|
|
|
|
description: "Get the last 2 items",
|
|
|
|
result: Some(Value::List {
|
|
|
|
vals: vec![Value::test_int(2), Value::test_int(3)],
|
|
|
|
span: Span::unknown(),
|
|
|
|
}),
|
|
|
|
}]
|
|
|
|
}
|
|
|
|
|
2021-10-26 20:29:00 +02:00
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
input: PipelineData,
|
|
|
|
) -> Result<PipelineData, ShellError> {
|
|
|
|
let rows: Option<i64> = call.opt(engine_state, stack, 0)?;
|
2021-10-27 16:19:33 +02:00
|
|
|
let v: Vec<_> = input.into_iter().collect();
|
|
|
|
let vlen: i64 = v.len() as i64;
|
|
|
|
let beginning_rows_to_skip = rows_to_skip(vlen, rows);
|
2021-10-27 05:48:31 +02:00
|
|
|
|
2021-10-27 16:19:33 +02:00
|
|
|
let iter = v
|
|
|
|
.into_iter()
|
|
|
|
.skip(beginning_rows_to_skip.try_into().unwrap());
|
|
|
|
|
2021-10-28 06:13:10 +02:00
|
|
|
Ok(iter.into_pipeline_data(engine_state.ctrlc.clone()))
|
2021-10-26 20:29:00 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-27 05:48:31 +02:00
|
|
|
fn rows_to_skip(count: i64, rows: Option<i64>) -> i64 {
|
|
|
|
let end_rows_desired = if let Some(quantity) = rows {
|
|
|
|
quantity
|
|
|
|
} else {
|
|
|
|
1
|
|
|
|
};
|
|
|
|
|
|
|
|
if end_rows_desired < count {
|
2021-10-27 17:35:42 +02:00
|
|
|
count - end_rows_desired
|
2021-10-27 05:48:31 +02:00
|
|
|
} else {
|
2021-10-27 17:35:42 +02:00
|
|
|
0
|
|
|
|
}
|
2021-10-26 20:29:00 +02:00
|
|
|
}
|
2021-10-27 17:07:37 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_examples() {
|
|
|
|
use crate::test_examples;
|
|
|
|
|
|
|
|
test_examples(Last {})
|
|
|
|
}
|
|
|
|
}
|