Move 'nth' into 'select' (#4385)

This commit is contained in:
JT
2022-02-09 09:59:40 -05:00
committed by GitHub
parent 43850bf20e
commit 5a1d81221f
18 changed files with 190 additions and 259 deletions

View File

@ -176,10 +176,10 @@ using Nushell commands.
To get the 3rd row in the table, you can use the `nth` command:
```
ls | nth 2
ls | select 2
```
This will get the 3rd (note that `nth` is zero-based) row in the table created
by the `ls` command. You can use `nth` on any table created by other commands
This will get the 3rd (note that `select` is zero-based) row in the table created
by the `ls` command. You can use `select` on any table created by other commands
as well.
You can also access the column of data in one of two ways. If you want
@ -218,7 +218,7 @@ like lists and tables.
To reach a cell of data from a table, you can combine a row operation and a
column operation.
```
ls | nth 4 | get name
ls | select 4 | get name
```
You can combine these operations into one step using a shortcut.
```

View File

@ -84,7 +84,6 @@ pub fn create_default_context(cwd: impl AsRef<Path>) -> EngineState {
Last,
Length,
Lines,
Nth,
ParEach,
ParEachGroup,
Prepend,

View File

@ -35,7 +35,7 @@ impl Command for Columns {
result: None,
},
Example {
example: "[[name,age,grade]; [bill,20,a]] | columns | nth 1",
example: "[[name,age,grade]; [bill,20,a]] | columns | select 1",
description: "Get the second column from the table",
result: None,
},

View File

@ -22,7 +22,6 @@ mod length;
mod lines;
mod merge;
mod move_;
mod nth;
mod par_each;
mod par_each_group;
mod prepend;
@ -69,7 +68,6 @@ pub use length::Length;
pub use lines::Lines;
pub use merge::Merge;
pub use move_::Move;
pub use nth::Nth;
pub use par_each::ParEach;
pub use par_each_group::ParEachGroup;
pub use prepend::Prepend;

View File

@ -1,152 +0,0 @@
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, PipelineIterator, ShellError,
Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
pub struct Nth;
impl Command for Nth {
fn name(&self) -> &str {
"nth"
}
fn signature(&self) -> Signature {
Signature::build("nth")
.rest("rest", SyntaxShape::Int, "the number of the row to return")
.switch("skip", "Skip the rows instead of selecting them", Some('s'))
.category(Category::Filters)
}
fn usage(&self) -> &str {
"Return or skip only the selected rows."
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "[sam,sarah,2,3,4,5] | nth 0 1 2",
description: "Get the first, second, and third row",
result: Some(Value::List {
vals: vec![
Value::test_string("sam"),
Value::test_string("sarah"),
Value::test_int(2),
],
span: Span::test_data(),
}),
},
Example {
example: "[0,1,2,3,4,5] | nth 0 1 2",
description: "Get the first, second, and third row",
result: Some(Value::List {
vals: vec![Value::test_int(0), Value::test_int(1), Value::test_int(2)],
span: Span::test_data(),
}),
},
Example {
example: "[0,1,2,3,4,5] | nth -s 0 1 2",
description: "Skip the first, second, and third row",
result: Some(Value::List {
vals: vec![Value::test_int(3), Value::test_int(4), Value::test_int(5)],
span: Span::test_data(),
}),
},
Example {
example: "[0,1,2,3,4,5] | nth 0 2 4",
description: "Get the first, third, and fifth row",
result: Some(Value::List {
vals: vec![Value::test_int(0), Value::test_int(2), Value::test_int(4)],
span: Span::test_data(),
}),
},
Example {
example: "[0,1,2,3,4,5] | nth 2 0 4",
description: "Get the first, third, and fifth row",
result: Some(Value::List {
vals: vec![Value::test_int(0), Value::test_int(2), Value::test_int(4)],
span: Span::test_data(),
}),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let mut rows: Vec<usize> = call.rest(engine_state, stack, 0)?;
rows.sort_unstable();
let skip = call.has_flag("skip");
let pipeline_iter: PipelineIterator = input.into_iter();
Ok(NthIterator {
input: pipeline_iter,
rows,
skip,
current: 0,
}
.into_pipeline_data(engine_state.ctrlc.clone()))
}
}
struct NthIterator {
input: PipelineIterator,
rows: Vec<usize>,
skip: bool,
current: usize,
}
impl Iterator for NthIterator {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
loop {
if !self.skip {
if let Some(row) = self.rows.get(0) {
if self.current == *row {
self.rows.remove(0);
self.current += 1;
return self.input.next();
} else {
self.current += 1;
let _ = self.input.next();
continue;
}
} else {
return None;
}
} else if let Some(row) = self.rows.get(0) {
if self.current == *row {
self.rows.remove(0);
self.current += 1;
let _ = self.input.next();
continue;
} else {
self.current += 1;
return self.input.next();
}
} else {
return self.input.next();
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Nth {})
}
}

View File

@ -1,9 +1,9 @@
use nu_engine::CallExt;
use nu_protocol::ast::{Call, CellPath};
use nu_protocol::ast::{Call, CellPath, PathMember};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Span, SyntaxShape, Value,
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
PipelineIterator, ShellError, Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
@ -14,6 +14,7 @@ impl Command for Select {
"select"
}
// FIXME: also add support for --skip
fn signature(&self) -> Signature {
Signature::build("select")
.rest(
@ -63,9 +64,44 @@ fn select(
columns: Vec<CellPath>,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if columns.is_empty() {
return Err(ShellError::CantFindColumn(span, span)); //FIXME?
let mut rows = vec![];
let mut new_columns = vec![];
for column in columns {
let CellPath { ref members } = column;
match members.get(0) {
Some(PathMember::Int { val, span }) => {
if members.len() > 1 {
return Err(ShellError::SpannedLabeledError(
"Select only allows row numbers for rows".into(),
"extra after row number".into(),
*span,
));
}
rows.push(*val);
}
_ => new_columns.push(column),
};
}
let columns = new_columns;
let input = if !rows.is_empty() {
rows.sort_unstable();
// let skip = call.has_flag("skip");
let pipeline_iter: PipelineIterator = input.into_iter();
NthIterator {
input: pipeline_iter,
rows,
skip: false,
current: 0,
}
.into_pipeline_data(engine_state.ctrlc.clone())
} else {
input
};
match input {
PipelineData::Value(
@ -78,17 +114,21 @@ fn select(
let mut output = vec![];
for input_val in input_vals {
let mut cols = vec![];
let mut vals = vec![];
for path in &columns {
//FIXME: improve implementation to not clone
let fetcher = input_val.clone().follow_cell_path(&path.members)?;
if !columns.is_empty() {
let mut cols = vec![];
let mut vals = vec![];
for path in &columns {
//FIXME: improve implementation to not clone
let fetcher = input_val.clone().follow_cell_path(&path.members)?;
cols.push(path.into_string());
vals.push(fetcher);
cols.push(path.into_string());
vals.push(fetcher);
}
output.push(Value::Record { cols, vals, span })
} else {
output.push(input_val)
}
output.push(Value::Record { cols, vals, span })
}
Ok(output
@ -97,39 +137,89 @@ fn select(
}
PipelineData::ListStream(stream, ..) => Ok(stream
.map(move |x| {
let mut cols = vec![];
let mut vals = vec![];
for path in &columns {
//FIXME: improve implementation to not clone
match x.clone().follow_cell_path(&path.members) {
Ok(value) => {
cols.push(path.into_string());
vals.push(value);
}
Err(error) => {
cols.push(path.into_string());
vals.push(Value::Error { error });
if !columns.is_empty() {
let mut cols = vec![];
let mut vals = vec![];
for path in &columns {
//FIXME: improve implementation to not clone
match x.clone().follow_cell_path(&path.members) {
Ok(value) => {
cols.push(path.into_string());
vals.push(value);
}
Err(error) => {
cols.push(path.into_string());
vals.push(Value::Error { error });
}
}
}
Value::Record { cols, vals, span }
} else {
x
}
Value::Record { cols, vals, span }
})
.into_pipeline_data(engine_state.ctrlc.clone())),
PipelineData::Value(v, ..) => {
let mut cols = vec![];
let mut vals = vec![];
if !columns.is_empty() {
let mut cols = vec![];
let mut vals = vec![];
for cell_path in columns {
// FIXME: remove clone
let result = v.clone().follow_cell_path(&cell_path.members)?;
for cell_path in columns {
// FIXME: remove clone
let result = v.clone().follow_cell_path(&cell_path.members)?;
cols.push(cell_path.into_string());
vals.push(result);
cols.push(cell_path.into_string());
vals.push(result);
}
Ok(Value::Record { cols, vals, span }.into_pipeline_data())
} else {
Ok(v.into_pipeline_data())
}
Ok(Value::Record { cols, vals, span }.into_pipeline_data())
}
_ => Ok(PipelineData::new(span)),
}
}
struct NthIterator {
input: PipelineIterator,
rows: Vec<usize>,
skip: bool,
current: usize,
}
impl Iterator for NthIterator {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
loop {
if !self.skip {
if let Some(row) = self.rows.get(0) {
if self.current == *row {
self.rows.remove(0);
self.current += 1;
return self.input.next();
} else {
self.current += 1;
let _ = self.input.next();
continue;
}
} else {
return None;
}
} else if let Some(row) = self.rows.get(0) {
if self.current == *row {
self.rows.remove(0);
self.current += 1;
let _ = self.input.next();
continue;
} else {
self.current += 1;
return self.input.next();
}
} else {
return self.input.next();
}
}
}
}