add range command

This commit is contained in:
Sebastian Jung 2019-12-02 20:15:14 +01:00
parent c199a84dbb
commit 8390cc97e1
3 changed files with 90 additions and 0 deletions

View File

@ -332,6 +332,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
whole_stream_command(What),
whole_stream_command(Which),
whole_stream_command(Debug),
whole_stream_command(Range),
]);
cfg_if::cfg_if! {

View File

@ -61,6 +61,7 @@ pub(crate) mod prepend;
pub(crate) mod prev;
pub(crate) mod pwd;
#[allow(unused)]
pub(crate) mod range;
pub(crate) mod reduce_by;
pub(crate) mod reject;
pub(crate) mod reverse;
@ -151,6 +152,7 @@ pub(crate) use prepend::Prepend;
pub(crate) use prev::Previous;
pub(crate) use pwd::PWD;
#[allow(unused)]
pub(crate) use range::Range;
pub(crate) use reduce_by::ReduceBy;
pub(crate) use reject::Reject;
pub(crate) use reverse::Reverse;

87
src/commands/range.rs Normal file
View File

@ -0,0 +1,87 @@
use crate::commands::WholeStreamCommand;
use crate::errors::ShellError;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_source::Tagged;
#[derive(Deserialize)]
struct RangeArgs {
area: Tagged<String>,
}
pub struct Range;
impl WholeStreamCommand for Range {
fn name(&self) -> &str {
"range"
}
fn signature(&self) -> Signature {
Signature::build("range").required(
"rows ",
SyntaxShape::Any,
"range of rows to return: Eg) 4..7 (=> from 4 to 7)",
)
}
fn usage(&self) -> &str {
"Return only the selected rows"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, range)?.run()
}
}
fn range(
RangeArgs { area: rows }: RangeArgs,
RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
match rows.item.find(".") {
Some(value) => {
let (first, last) = rows.item.split_at(value);
let first = match first.parse::<u64>() {
Ok(postion) => postion,
Err(_) => {
if first == "" {
0
} else {
return Err(ShellError::labeled_error(
"no correct start of range",
"'from' needs to be an Integer or empty",
name,
));
}
},
};
let last = match last.trim_start_matches(".").parse::<u64>() {
Ok(postion) => postion,
Err(_) => {
if last == ".." {
std::u64::MAX
} else {
return Err(ShellError::labeled_error(
"no correct end of range",
"'to' needs to be an Integer or empty",
name,
));
}
},
};
return Ok(OutputStream::from_input(
input.values.skip(first).take(last-first+1),
));
},
None => {
return Err(ShellError::labeled_error(
"No correct formated range found",
"format: <from>..<to>",
name,
));
}
}
}