nushell/src/plugins/inc.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

2019-07-03 19:37:09 +02:00
use indexmap::IndexMap;
use nu::{
2019-07-13 04:07:06 +02:00
serve_plugin, Args, CommandConfig, Plugin, PositionalType, Primitive, ReturnSuccess,
ReturnValue, ShellError, Spanned, SpannedItem, Value,
2019-07-03 19:37:09 +02:00
};
2019-06-27 06:56:48 +02:00
2019-07-02 09:56:20 +02:00
struct Inc {
inc_by: i64,
2019-06-27 06:56:48 +02:00
}
2019-07-02 09:56:20 +02:00
impl Inc {
fn new() -> Inc {
Inc { inc_by: 1 }
2019-06-27 06:56:48 +02:00
}
}
2019-07-13 04:07:06 +02:00
impl Plugin for Inc {
fn config(&mut self) -> Result<CommandConfig, ShellError> {
Ok(CommandConfig {
name: "inc".to_string(),
2019-07-15 23:16:27 +02:00
positional: vec![PositionalType::mandatory_any("Increment")],
2019-07-13 04:07:06 +02:00
is_filter: true,
is_sink: false,
named: IndexMap::new(),
rest_positional: true,
})
}
fn begin_filter(&mut self, args: Args) -> Result<(), ShellError> {
if let Some(args) = args.positional {
for arg in args {
match arg {
Spanned {
item: Value::Primitive(Primitive::Int(i)),
..
} => {
self.inc_by = i;
2019-06-27 06:56:48 +02:00
}
2019-07-02 09:56:20 +02:00
_ => return Err(ShellError::string("Unrecognized type in params")),
2019-06-27 06:56:48 +02:00
}
}
2019-07-13 04:07:06 +02:00
}
Ok(())
}
fn filter(&mut self, input: Spanned<Value>) -> Result<Vec<ReturnValue>, ShellError> {
let span = input.span;
match input.item {
Value::Primitive(Primitive::Int(i)) => Ok(vec![ReturnSuccess::value(
Value::int(i + self.inc_by).spanned(span),
)]),
Value::Primitive(Primitive::Bytes(b)) => Ok(vec![ReturnSuccess::value(
Value::bytes(b + self.inc_by as u64).spanned(span),
)]),
2019-07-02 09:56:20 +02:00
x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}",
x
))),
2019-06-27 06:56:48 +02:00
}
}
2019-07-02 09:56:20 +02:00
}
2019-06-27 06:56:48 +02:00
2019-07-02 09:56:20 +02:00
fn main() {
serve_plugin(&mut Inc::new());
2019-06-27 06:56:48 +02:00
}