2019-12-02 20:15:14 +01:00
|
|
|
use crate::commands::WholeStreamCommand;
|
|
|
|
use crate::context::CommandRegistry;
|
|
|
|
use crate::prelude::*;
|
2019-12-03 20:56:39 +01:00
|
|
|
use nu_errors::ShellError;
|
|
|
|
use nu_protocol::{Signature, SyntaxShape};
|
2019-12-02 20:15:14 +01:00
|
|
|
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,
|
2019-12-03 08:24:49 +01:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2019-12-02 20:15:14 +01:00
|
|
|
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,
|
|
|
|
));
|
|
|
|
}
|
2019-12-03 08:24:49 +01:00
|
|
|
}
|
2019-12-02 20:15:14 +01:00
|
|
|
};
|
|
|
|
let last = match last.trim_start_matches(".").parse::<u64>() {
|
|
|
|
Ok(postion) => postion,
|
|
|
|
Err(_) => {
|
|
|
|
if last == ".." {
|
2019-12-03 08:24:49 +01:00
|
|
|
std::u64::MAX - 1
|
2019-12-02 20:15:14 +01:00
|
|
|
} else {
|
|
|
|
return Err(ShellError::labeled_error(
|
|
|
|
"no correct end of range",
|
|
|
|
"'to' needs to be an Integer or empty",
|
|
|
|
name,
|
|
|
|
));
|
|
|
|
}
|
2019-12-03 08:24:49 +01:00
|
|
|
}
|
2019-12-02 20:15:14 +01:00
|
|
|
};
|
|
|
|
return Ok(OutputStream::from_input(
|
2019-12-03 08:24:49 +01:00
|
|
|
input.values.skip(first).take(last - first + 1),
|
2019-12-02 20:15:14 +01:00
|
|
|
));
|
2019-12-03 08:24:49 +01:00
|
|
|
}
|
2019-12-02 20:15:14 +01:00
|
|
|
None => {
|
|
|
|
return Err(ShellError::labeled_error(
|
2019-12-03 08:24:49 +01:00
|
|
|
"No correct formatted range found",
|
2019-12-02 20:15:14 +01:00
|
|
|
"format: <from>..<to>",
|
|
|
|
name,
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|
2019-12-03 08:24:49 +01:00
|
|
|
}
|