nushell/src/plugins/inc.rs

67 lines
1.8 KiB
Rust
Raw Normal View History

2019-07-03 19:37:09 +02:00
use indexmap::IndexMap;
use nu::{
serve_plugin, Args, CommandConfig, Plugin, PositionalType, Primitive, ReturnValue, ShellError,
Spanned, Value,
};
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-02 09:56:20 +02:00
impl Plugin for Inc {
2019-07-03 19:37:09 +02:00
fn config(&mut self) -> Result<CommandConfig, ShellError> {
Ok(CommandConfig {
name: "inc".to_string(),
mandatory_positional: vec![],
optional_positional: vec![PositionalType::Value("Increment".into())],
can_load: vec![],
can_save: vec![],
is_filter: true,
is_sink: false,
named: IndexMap::new(),
rest_positional: true,
})
}
2019-07-02 09:56:20 +02:00
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-02 09:56:20 +02:00
}
Ok(())
}
fn filter(&mut self, input: Value) -> Result<Vec<ReturnValue>, ShellError> {
match input {
Value::Primitive(Primitive::Int(i)) => {
Ok(vec![ReturnValue::Value(Value::int(i + self.inc_by))])
2019-06-27 06:56:48 +02:00
}
2019-07-02 09:56:20 +02:00
Value::Primitive(Primitive::Bytes(b)) => Ok(vec![ReturnValue::Value(Value::bytes(
b + self.inc_by as u64,
))]),
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
}