nushell/crates/nu-command/src/commands/range.rs
Michael Angerman d06f457b2a
nu-cli refactor moving commands into their own crate nu-command (#2910)
* move commands, futures.rs, script.rs, utils

* move over maybe_print_errors

* add nu_command crate references to nu_cli

* in commands.rs open up to pub mod from pub(crate)

* nu-cli, nu-command, and nu tests are now passing

* cargo fmt

* clean up nu-cli/src/prelude.rs

* code cleanup

* for some reason lex.rs was not formatted, may be causing my error

* remove mod completion from lib.rs which was not being used along with quickcheck macros

* add in allow unused imports

* comment out one failing external test; comment out one failing internal test

* revert commenting out failing tests; something else might be going on; someone with a windows machine should check and see what is going on with these failing windows tests

* Update Cargo.toml

Extend the optional features to nu-command

Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com>
2021-01-12 17:59:53 +13:00

78 lines
1.8 KiB
Rust

use crate::prelude::*;
use nu_engine::deserializer::NumericRange;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{RangeInclusion, ReturnSuccess, Signature, SyntaxShape};
use nu_source::Tagged;
#[derive(Deserialize)]
struct RangeArgs {
area: Tagged<NumericRange>,
}
pub struct Range;
#[async_trait]
impl WholeStreamCommand for Range {
fn name(&self) -> &str {
"range"
}
fn signature(&self) -> Signature {
Signature::build("range").required(
"rows ",
SyntaxShape::Range,
"range of rows to return: Eg) 4..7 (=> from 4 to 7)",
)
}
fn usage(&self) -> &str {
"Return only the selected rows"
}
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
range(args).await
}
}
async fn range(args: CommandArgs) -> Result<OutputStream, ShellError> {
let (RangeArgs { area }, input) = args.process().await?;
let range = area.item;
let (from, left_inclusive) = range.from;
let (to, right_inclusive) = range.to;
let from = from.map(|from| *from as usize).unwrap_or(0).saturating_add(
if left_inclusive == RangeInclusion::Inclusive {
0
} else {
1
},
);
let to = to
.map(|to| *to as usize)
.unwrap_or(usize::MAX)
.saturating_sub(if right_inclusive == RangeInclusion::Inclusive {
0
} else {
1
});
Ok(input
.skip(from)
.take(to - from + 1)
.map(ReturnSuccess::value)
.to_output_stream())
}
#[cfg(test)]
mod tests {
use super::Range;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
Ok(test_examples(Range {})?)
}
}