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

View file

@ -29,3 +29,15 @@ fn rows() {
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"));
})
}