From 526ca5edefd06efa441838b7056bf839ae0719bc Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 23 Nov 2024 04:53:06 -0600 Subject: [PATCH] Adds a line calculation and the beggining of string diff and parsing --- src/main.rs | 154 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 122 insertions(+), 32 deletions(-) diff --git a/src/main.rs b/src/main.rs index b04a6e4..64155bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,18 +2,19 @@ //! instead of an external diagnostic tool. //! -#![deny(clippy::missing_docs_in_private_items)] +#![warn(clippy::missing_docs_in_private_items)] // #![warn(clippy::pedantic, clippy::correctness)] use anyhow::{anyhow, Context}; use clap::Parser; use serde_json::Value; -use std::process::Command; +use std::io::Write; +use std::process::{Command, Stdio}; use tower_lsp::lsp_types::{ Diagnostic, DiagnosticSeverity, DidOpenTextDocumentParams, DidSaveTextDocumentParams, ExecuteCommandParams, InitializeParams, InitializeResult, InitializedParams, MessageType, - NumberOrString, Position, Range, ServerCapabilities, TextDocumentSyncCapability, - TextDocumentSyncKind, Url, + NumberOrString, Position, Range, SaveOptions, ServerCapabilities, TextDocumentSyncCapability, + TextDocumentSyncOptions, TextDocumentSyncSaveOptions, Url, }; use tower_lsp::{Client, LanguageServer, LspService, Server}; @@ -53,9 +54,17 @@ impl LanguageServer for Backend { ) -> Result { Ok(InitializeResult { capabilities: ServerCapabilities { - text_document_sync: Some(TextDocumentSyncCapability::Kind( - TextDocumentSyncKind::NONE, + text_document_sync: Some(TextDocumentSyncCapability::Options( + TextDocumentSyncOptions { + save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions { + include_text: Some(true), + })), + ..Default::default() + }, )), + // text_document_sync: Some(TextDocumentSyncCapability::Kind( + // TextDocumentSyncKind::FULL, + // )), ..ServerCapabilities::default() }, ..Default::default() @@ -90,39 +99,57 @@ impl LanguageServer for Backend { } async fn did_open(&self, p: DidOpenTextDocumentParams) { - match find_diagnostics_for_file(&p.text_document.uri, &self.vsg_args) { - Ok(diags) => { - self.client - .publish_diagnostics(p.text_document.uri, diags, None) - .await; - } - Err(e) => { - self.client - .show_message(MessageType::ERROR, e.to_string()) - .await; - } - }; + // // let mut f = fs::File::create("bob2").unwrap(); + // // f.write_all(format!("{:?}", p.text_document.text).as_bytes()) + // .unwrap(); + publish_diagnostics( + &self.client, + &p.text_document.uri, + find_diagnostics_for_file( + &p.text_document.uri, + &LineLength::try_from(&p.text_document.text).unwrap(), + &self.vsg_args, + ), + ) + .await; } async fn did_save(&self, p: DidSaveTextDocumentParams) { - match find_diagnostics_for_file(&p.text_document.uri, &self.vsg_args) { - Ok(diags) => { - self.client - .publish_diagnostics(p.text_document.uri, diags, None) - .await; - } - Err(e) => { - self.client - .show_message(MessageType::ERROR, e.to_string()) - .await; - } - }; + // let mut f = fs::File::create("bob").unwrap(); + // f.write_all(format!("{:?}", p.text).as_bytes()).unwrap(); + publish_diagnostics( + &self.client, + &p.text_document.uri, + find_diagnostics_for_file( + &p.text_document.uri, + &LineLength::try_from(&p.text.unwrap_or("".to_owned())).unwrap(), + &self.vsg_args, + ), + ) + .await; } } +/// Punlish the diagnostic or log an error +async fn publish_diagnostics( + client: &Client, + uri: &Url, + diagnostics: Result, anyhow::Error>, +) { + match diagnostics { + Ok(diags) => { + client.publish_diagnostics(uri.clone(), diags, None).await; + } + Err(e) => { + client.show_message(MessageType::ERROR, e.to_string()).await; + } + }; +} + /// Find all diagnostics for a file fn find_diagnostics_for_file( uri: &Url, + line_length: &LineLength, config: &Vec, ) -> Result, anyhow::Error> { let mut vec_diag = Vec::new(); @@ -132,14 +159,20 @@ fn find_diagnostics_for_file( let output = file_uri_to_diagnostic_string(uri, config)?; let matches = reg.captures_iter(&output); + // TODO: Avoid doing this if there are no matches + for m in matches { if let (Some(rule), Some(line), Some(solution)) = (m.name("rule"), m.name("line"), m.name("solution")) { let range = match line.as_str().parse() { - Ok(pos) => make_range(pos), + Ok(pos) => make_real_range(pos, line_length), Err(_) => continue, }; + // let range = match line.as_str().parse() { + // Ok(pos) => make_range(pos), + // Err(_) => continue, + // }; let d = Diagnostic { range, // TODO: Should find the true range severity: Some(DiagnosticSeverity::WARNING), // Everything is a warning @@ -171,8 +204,56 @@ fn file_uri_to_diagnostic_string(uri: &Url, config: &Vec) -> Result, +) -> Result { + let mut child = Command::new("vsg") + .arg("-ap") + .arg("--stdin") + .args(config) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("Failed to spawn child process"); + + let mut stdin = child.stdin.take().expect("Failed to open stdin"); + std::thread::spawn(move || { + stdin + .write_all(input.as_bytes()) + .expect("Failed to write to stdin"); + }); + + let output = child.wait_with_output().expect("Failed to read stdout"); + Ok(String::from_utf8_lossy(output.stdout.as_slice()).into_owned()) +} + +/// Hold the line length of a parsed string +struct LineLength(Vec); + +impl TryFrom<&String> for LineLength { + fn try_from(value: &String) -> Result { + let mut v = Vec::with_capacity(1000); // Educated guess for a reasonable file size + for line in value.lines() { + v.push(line.len().try_into().unwrap()) + } + Ok(Self(v)) + } + + type Error = anyhow::Error; +} + +impl LineLength { + /// Get the line size at a specific position + fn get_line_size(&self, idx: usize) -> u32 { + *self.0.get(idx).unwrap_or(&1u32) + } +} + /// Make a range with a line position -// TODO: Find the actual range +#[allow(dead_code)] fn make_range(pos: u32) -> Range { Range::new( Position::new(pos.saturating_sub(1), 0), @@ -180,6 +261,15 @@ fn make_range(pos: u32) -> Range { ) } +/// Make a real range from a line number +fn make_real_range(pos: u32, line_length: &LineLength) -> Range { + let pos = pos.saturating_sub(1); + Range::new( + Position::new(pos, 0), + Position::new(pos, line_length.get_line_size(pos.try_into().unwrap_or(1))), + ) +} + #[tokio::main] async fn main() { tracing_subscriber::fmt().init();