Add filter and sink plugins

This commit is contained in:
Jonathan Turner
2019-07-02 19:56:20 +12:00
parent ea18583e30
commit 75ddfe9f5a
12 changed files with 268 additions and 194 deletions

View File

@ -1,83 +1,33 @@
use nu::{Primitive, ReturnValue, ShellError, Spanned, Value};
use serde::{Deserialize, Serialize};
use std::io;
use nu::{serve_plugin, Args, Plugin, Primitive, Value};
/// A wrapper for proactive notifications to the IDE (eg. diagnostics). These must
/// follow the JSON 2.0 RPC spec
struct Sum;
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpc<T> {
jsonrpc: String,
pub method: String,
pub params: Vec<T>,
}
impl<T> JsonRpc<T> {
pub fn new<U: Into<String>>(method: U, params: Vec<T>) -> Self {
JsonRpc {
jsonrpc: "2.0".into(),
method: method.into(),
params,
}
impl Sum {
fn new() -> Sum {
Sum
}
}
fn send_response<T: Serialize>(result: Vec<T>) {
let response = JsonRpc::new("response", result);
let response_raw = serde_json::to_string(&response).unwrap();
println!("{}", response_raw);
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "method")]
#[allow(non_camel_case_types)]
pub enum NuCommand {
init { params: Vec<Spanned<Value>> },
filter { params: Value },
quit,
}
impl Plugin for Sum {
fn sink(&mut self, _args: Args, input: Vec<Value>) {
let mut total = 0i64;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut total = 0i64;
loop {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => {
let command = serde_json::from_str::<NuCommand>(&input);
match command {
Ok(NuCommand::init { .. }) => {}
Ok(NuCommand::filter { params }) => match params {
Value::Primitive(Primitive::Int(i)) => {
total += i as i64;
send_response(vec![ReturnValue::Value(Value::int(total))]);
}
Value::Primitive(Primitive::Bytes(b)) => {
total += b as i64;
send_response(vec![ReturnValue::Value(Value::bytes(total as u64))]);
}
_ => {
send_response(vec![ReturnValue::Value(Value::Error(Box::new(
ShellError::string("Unrecognized type in stream"),
)))]);
}
},
Ok(NuCommand::quit) => {
break;
}
Err(_) => {
send_response(vec![ReturnValue::Value(Value::Error(Box::new(
ShellError::string("Unrecognized type in stream"),
)))]);
}
for v in input {
match v {
Value::Primitive(Primitive::Int(i)) => {
total += i;
}
}
Err(_) => {
send_response(vec![ReturnValue::Value(Value::Error(Box::new(
ShellError::string("Unrecognized type in stream"),
)))]);
Value::Primitive(Primitive::Bytes(i)) => {
total += i as i64;
}
_ => {}
}
}
}
Ok(())
println!("Result: {}", total);
}
}
fn main() {
serve_plugin(&mut Sum::new());
}