make take behave like first (#6893)

* fix take_1 behavior

* fix test case

* simplify code

* reverse back for first command

* fix example

* make arg required

* add test

* fix test message
This commit is contained in:
WindSoilder 2022-11-09 18:32:16 +08:00 committed by GitHub
parent 6cc4ef6c70
commit 85587c0c2a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 22 deletions

View file

@ -16,7 +16,7 @@ impl Command for Take {
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("take") Signature::build("take")
.optional( .required(
"n", "n",
SyntaxShape::Int, SyntaxShape::Int,
"starting from the front, the number of elements to return", "starting from the front, the number of elements to return",
@ -42,8 +42,11 @@ impl Command for Take {
vec![ vec![
Example { Example {
description: "Return the first item of a list/table", description: "Return the first item of a list/table",
example: "[1 2 3] | take", example: "[1 2 3] | take 1",
result: Some(Value::test_int(1)), result: Some(Value::List {
vals: vec![Value::test_int(1)],
span: Span::test_data(),
}),
}, },
Example { Example {
description: "Return the first 2 items of a list/table", description: "Return the first 2 items of a list/table",
@ -64,11 +67,7 @@ fn first_helper(
input: PipelineData, input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let head = call.head; let head = call.head;
let rows: Option<i64> = call.opt(engine_state, stack, 0)?; let mut rows_desired: usize = call.req(engine_state, stack, 0)?;
let mut rows_desired: usize = match rows {
Some(x) => x as usize,
None => 1,
};
let ctrlc = engine_state.ctrlc.clone(); let ctrlc = engine_state.ctrlc.clone();
let metadata = input.metadata(); let metadata = input.metadata();
@ -137,20 +136,11 @@ fn first_helper(
.set_metadata(metadata)), .set_metadata(metadata)),
} }
} }
_ => { _ => Ok(input_peek
if rows_desired == 1 { .into_iter()
match input_peek.next() { .take(rows_desired)
Some(val) => Ok(val.into_pipeline_data()), .into_pipeline_data(ctrlc)
None => Err(ShellError::AccessBeyondEndOfStream(head)), .set_metadata(metadata)),
}
} else {
Ok(input_peek
.into_iter()
.take(rows_desired)
.into_pipeline_data(ctrlc)
.set_metadata(metadata))
}
}
} }
} else { } else {
Err(ShellError::UnsupportedInput( Err(ShellError::UnsupportedInput(

View file

@ -29,3 +29,15 @@ fn rows() {
assert_eq!(actual.out, "4"); assert_eq!(actual.out, "4");
}) })
} }
#[test]
fn rows_with_no_arguments_should_lead_to_error() {
Playground::setup("take_test_2", |dirs, _sandbox| {
let actual = nu!(
cwd: dirs.test(), pipeline(
r#"[1 2 3] | take"#
));
assert!(actual.err.contains("missing_positional"));
})
}