mirror of
https://github.com/nushell/nushell.git
synced 2025-08-19 10:52:54 +02:00
Merge branch 'master' into surf
This commit is contained in:
59
src/commands/last.rs
Normal file
59
src/commands/last.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use crate::commands::WholeStreamCommand;
|
||||
use crate::errors::ShellError;
|
||||
use crate::parser::CommandRegistry;
|
||||
use crate::prelude::*;
|
||||
|
||||
pub struct Last;
|
||||
|
||||
impl WholeStreamCommand for Last {
|
||||
fn run(
|
||||
&self,
|
||||
args: CommandArgs,
|
||||
registry: &CommandRegistry,
|
||||
) -> Result<OutputStream, ShellError> {
|
||||
last(args, registry)
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"last"
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("last").required("amount", SyntaxType::Literal)
|
||||
}
|
||||
}
|
||||
|
||||
fn last(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
|
||||
let args = args.evaluate_once(registry)?;
|
||||
|
||||
let amount = args.expect_nth(0)?.as_i64();
|
||||
|
||||
let amount = match amount {
|
||||
Ok(o) => o,
|
||||
Err(_) => {
|
||||
return Err(ShellError::labeled_error(
|
||||
"Value is not a number",
|
||||
"expected integer",
|
||||
args.expect_nth(0)?.span(),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
if amount <= 0 {
|
||||
return Err(ShellError::labeled_error(
|
||||
"Value is too low",
|
||||
"expected a positive integer",
|
||||
args.expect_nth(0)?.span(),
|
||||
))
|
||||
}
|
||||
|
||||
let stream = async_stream_block! {
|
||||
let v: Vec<_> = args.input.into_vec().await;
|
||||
let k = v.len() - (amount as usize);
|
||||
for x in v[k..].iter() {
|
||||
let y: Tagged<Value> = x.clone();
|
||||
yield ReturnSuccess::value(y)
|
||||
}
|
||||
};
|
||||
Ok(stream.to_output_stream())
|
||||
}
|
@@ -18,7 +18,7 @@ impl WholeStreamCommand for SortBy {
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("sort-by")
|
||||
Signature::build("sort-by").switch("reverse")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,13 +37,21 @@ fn sort_by(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream
|
||||
|
||||
let output = input.values.collect::<Vec<_>>();
|
||||
|
||||
let reverse = args.has("reverse");
|
||||
let output = output.map(move |mut vec| {
|
||||
vec.sort_by_key(|item| {
|
||||
let calc_key = |item: &Tagged<Value>| {
|
||||
fields
|
||||
.iter()
|
||||
.map(|f| item.get_data_by_key(f).map(|i| i.clone()))
|
||||
.collect::<Vec<Option<Tagged<Value>>>>()
|
||||
});
|
||||
};
|
||||
if reverse {
|
||||
vec.sort_by_cached_key(|item| {
|
||||
std::cmp::Reverse(calc_key(item))
|
||||
});
|
||||
} else {
|
||||
vec.sort_by_cached_key(calc_key);
|
||||
}
|
||||
|
||||
vec.into_iter().collect::<VecDeque<_>>()
|
||||
});
|
||||
|
Reference in New Issue
Block a user