codemp-nvim/src/client/nvim/main.rs

194 lines
4.8 KiB
Rust
Raw Normal View History

2023-04-11 17:12:22 +02:00
use std::{net::TcpStream, sync::Mutex};
2023-04-11 14:01:55 +02:00
use codemp::client::CodempClient;
2023-04-11 06:20:40 +02:00
use codemp::proto::buffer_client::BufferClient;
use rmpv::Value;
2023-04-11 06:20:40 +02:00
use tokio::io::Stdout;
2023-04-11 06:20:40 +02:00
use clap::Parser;
2023-04-11 14:01:55 +02:00
use nvim_rs::{compat::tokio::Compat, create::tokio as create, Handler, Neovim};
use tonic::async_trait;
2023-04-11 06:20:40 +02:00
use tracing::{error, warn, debug};
#[derive(Clone)]
struct NeovimHandler {
2023-04-11 06:20:40 +02:00
client: CodempClient,
}
fn nullable_optional_str(args: &Vec<Value>, index: usize) -> Option<String> {
Some(args.get(index)?.as_str()?.to_string())
}
2023-04-11 17:12:22 +02:00
fn default_empty_str(args: &Vec<Value>, index: usize) -> String {
nullable_optional_str(args, index).unwrap_or("".into())
}
fn nullable_optional_number(args: &Vec<Value>, index: usize) -> Option<u64> {
Some(args.get(index)?.as_u64()?)
}
fn default_zero_number(args: &Vec<Value>, index: usize) -> u64 {
nullable_optional_number(args, index).unwrap_or(0)
}
#[async_trait]
impl Handler for NeovimHandler {
type Writer = Compat<Stdout>;
async fn handle_request(
&self,
name: String,
args: Vec<Value>,
nvim: Neovim<Compat<Stdout>>,
) -> Result<Value, Value> {
2023-04-11 17:12:22 +02:00
debug!("processing '{}' - {:?}", name, args);
match name.as_ref() {
"ping" => Ok(Value::from("pong")),
2023-04-11 06:20:40 +02:00
"dump" => Ok(Value::from(self.client.content())),
"create" => {
if args.len() < 1 {
return Err(Value::from("no path given"));
}
2023-04-11 17:12:22 +02:00
let path = default_empty_str(&args, 0);
2023-04-11 06:20:40 +02:00
let content = nullable_optional_str(&args, 1);
let mut c = self.client.clone();
match c.create(path, content).await {
Ok(r) => match r {
true => Ok(Value::from("accepted")),
false => Err(Value::from("rejected")),
},
Err(e) => Err(Value::from(format!("could not create buffer: {}", e))),
}
},
"insert" => {
if args.len() < 3 {
return Err(Value::from("not enough arguments"));
}
2023-04-11 17:12:22 +02:00
let path = default_empty_str(&args, 0);
let txt = default_empty_str(&args, 1);
let pos = default_zero_number(&args, 2);
2023-04-11 06:20:40 +02:00
let mut c = self.client.clone();
match c.insert(path, txt, pos).await {
Ok(res) => match res {
true => Ok(Value::from("accepted")),
false => Err(Value::from("rejected")),
},
Err(e) => Err(Value::from(format!("could not send insert: {}", e))),
}
},
"delete" => {
if args.len() < 3 {
return Err(Value::from("not enough arguments"));
}
2023-04-11 17:12:22 +02:00
let path = default_empty_str(&args, 0);
let pos = default_zero_number(&args, 1);
let count = default_zero_number(&args, 2);
let mut c = self.client.clone();
match c.delete(path, pos, count).await {
2023-04-11 06:20:40 +02:00
Ok(res) => match res {
true => Ok(Value::from("accepted")),
false => Err(Value::from("rejected")),
},
Err(e) => Err(Value::from(format!("could not send insert: {}", e))),
}
},
"attach" => {
if args.len() < 1 {
return Err(Value::from("no path given"));
}
2023-04-11 17:12:22 +02:00
let path = default_empty_str(&args, 0);
let buf = match nvim.get_current_buf().await {
Ok(b) => b,
Err(e) => return Err(Value::from(format!("could not get current buffer: {}", e))),
};
2023-04-11 06:20:40 +02:00
let mut c = self.client.clone();
match c.attach(path, move |x| {
let lines : Vec<String> = x.split("\n").map(|x| x.to_string()).collect();
let b = buf.clone();
tokio::spawn(async move {
if let Err(e) = b.set_lines(0, lines.len() as i64, false, lines).await {
error!("could not update buffer: {}", e);
}
});
}).await {
Ok(()) => Ok(Value::from("spawned worker")),
Err(e) => Err(Value::from(format!("could not attach to stream: {}", e))),
}
},
_ => Err(Value::from("unimplemented")),
}
}
async fn handle_notify(
&self,
2023-04-11 06:20:40 +02:00
_name: String,
_args: Vec<Value>,
_nvim: Neovim<Compat<Stdout>>,
) {
2023-04-11 06:20:40 +02:00
warn!("notify not handled");
}
}
2023-04-11 06:20:40 +02:00
#[derive(Parser, Debug)]
struct CliArgs {
/// server host to connect to
#[arg(long, default_value = "http://[::1]:50051")]
host: String,
/// show debug level logs
#[arg(long, default_value_t = false)]
debug: bool,
}
#[tokio::main]
2023-04-11 14:01:55 +02:00
async fn main() -> Result<(), Box<dyn std::error::Error>> {
2023-04-11 06:20:40 +02:00
let args = CliArgs::parse();
2023-04-11 17:12:22 +02:00
let sub = tracing_subscriber::fmt()
2023-04-11 06:20:40 +02:00
.compact()
.without_time()
2023-04-11 17:12:22 +02:00
.with_ansi(false);
match TcpStream::connect("127.0.0.1:6969") {
Ok(stream) => {
sub.with_writer(Mutex::new(stream))
.with_max_level(if args.debug { tracing::Level::DEBUG } else { tracing::Level::INFO })
.init();
},
Err(_) => {
sub.with_writer(std::io::stderr)
.with_max_level(if args.debug { tracing::Level::DEBUG } else { tracing::Level::INFO })
.init();
},
}
2023-04-11 06:20:40 +02:00
let client = BufferClient::connect(args.host).await?;
debug!("client connected");
2023-04-11 06:20:40 +02:00
let handler: NeovimHandler = NeovimHandler {
client: client.into(),
};
let (nvim, io_handler) = create::new_parent(handler).await;
2023-04-11 14:01:55 +02:00
nvim.out_write("[*] codemp loaded").await?;
2023-04-11 14:01:55 +02:00
if let Err(e) = io_handler.await? {
error!("[!] worker stopped with error: {}", e);
}
2023-04-11 06:20:40 +02:00
Ok(())
}