291 lines
9.0 KiB
Rust
291 lines
9.0 KiB
Rust
//! A very featureless VSG to lsp bridge, allowing to use vsg as a linting lsp
|
|
//! instead of an external diagnostic tool.
|
|
//!
|
|
|
|
#![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::io::Write;
|
|
use std::process::{Command, Stdio};
|
|
use tower_lsp::lsp_types::{
|
|
Diagnostic, DiagnosticSeverity, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
|
|
ExecuteCommandParams, InitializeParams, InitializeResult, InitializedParams, MessageType,
|
|
NumberOrString, Position, Range, SaveOptions, ServerCapabilities, TextDocumentSyncCapability,
|
|
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, Url,
|
|
};
|
|
use tower_lsp::{Client, LanguageServer, LspService, Server};
|
|
|
|
/// A generic macro to avoid recalculating a regex every iteration
|
|
macro_rules! regex {
|
|
($re:literal $(,)?) => {{
|
|
static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
|
|
RE.get_or_init(|| regex::Regex::new($re).unwrap())
|
|
}};
|
|
}
|
|
|
|
#[derive(Parser, Debug)]
|
|
#[command(version, about, long_about = None)]
|
|
#[allow(clippy::missing_docs_in_private_items)]
|
|
struct Args {
|
|
/// List of configuration files to load for vsg
|
|
#[arg(short, long)]
|
|
configuration: Vec<String>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug)]
|
|
struct Backend {
|
|
/// The lsp client caller
|
|
client: Client,
|
|
/// A global config data
|
|
config: Args,
|
|
/// The list of args to pass to the vsg call
|
|
vsg_args: Vec<String>,
|
|
}
|
|
|
|
#[tower_lsp::async_trait]
|
|
impl LanguageServer for Backend {
|
|
async fn initialize(
|
|
&self,
|
|
_: InitializeParams,
|
|
) -> Result<InitializeResult, tower_lsp::jsonrpc::Error> {
|
|
Ok(InitializeResult {
|
|
capabilities: ServerCapabilities {
|
|
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()
|
|
})
|
|
}
|
|
|
|
async fn initialized(&self, _: InitializedParams) {
|
|
self.client
|
|
.log_message(MessageType::INFO, "initialized!")
|
|
.await;
|
|
}
|
|
|
|
async fn shutdown(&self) -> Result<(), tower_lsp::jsonrpc::Error> {
|
|
Ok(())
|
|
}
|
|
|
|
async fn execute_command(
|
|
&self,
|
|
_: ExecuteCommandParams,
|
|
) -> Result<Option<Value>, tower_lsp::jsonrpc::Error> {
|
|
// self.client
|
|
// .log_message(MessageType::INFO, "command executed!")
|
|
// .await;
|
|
|
|
// match self.client.apply_edit(WorkspaceEdit::default()).await {
|
|
// Ok(res) if res.applied => self.client.log_message(MessageType::INFO, "applied").await,
|
|
// Ok(_) => self.client.log_message(MessageType::INFO, "rejected").await,
|
|
// Err(err) => self.client.log_message(MessageType::ERROR, err).await,
|
|
// }
|
|
|
|
Ok(None)
|
|
}
|
|
|
|
async fn did_open(&self, p: DidOpenTextDocumentParams) {
|
|
// // 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) {
|
|
// 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<Vec<Diagnostic>, 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<String>,
|
|
) -> Result<Vec<Diagnostic>, anyhow::Error> {
|
|
let mut vec_diag = Vec::new();
|
|
let reg = regex!(
|
|
r" (?<rule>[^\s]*_\d*)\s*\| (?<severity>[^\s]*)\s*\|\s*(?<line>[^\s]*) \| (?<solution>.*)"
|
|
);
|
|
|
|
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_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
|
|
code: Some(NumberOrString::String(rule.as_str().to_owned())),
|
|
message: solution.as_str().to_owned(),
|
|
..Default::default()
|
|
};
|
|
vec_diag.push(d);
|
|
};
|
|
}
|
|
Ok(vec_diag)
|
|
}
|
|
|
|
/// Load the file and make a diagnostic as a string
|
|
fn file_uri_to_diagnostic_string(uri: &Url, config: &Vec<String>) -> Result<String, anyhow::Error> {
|
|
Ok(String::from_utf8_lossy(
|
|
&Command::new("vsg")
|
|
.arg("-ap")
|
|
.arg("-f")
|
|
.arg(
|
|
uri.to_file_path()
|
|
.map_err(|()| anyhow!("converting uri to file path"))?,
|
|
)
|
|
.args(config)
|
|
.output()
|
|
.context("failed to run vsg linter")?
|
|
.stdout,
|
|
)
|
|
.into_owned())
|
|
}
|
|
|
|
/// Load the file and make a diagnostic as a string
|
|
#[allow(dead_code)]
|
|
fn string_to_diagnostic_string(
|
|
input: String,
|
|
config: &Vec<String>,
|
|
) -> Result<String, anyhow::Error> {
|
|
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<u32>);
|
|
|
|
impl TryFrom<&String> for LineLength {
|
|
fn try_from(value: &String) -> Result<LineLength, anyhow::Error> {
|
|
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
|
|
#[allow(dead_code)]
|
|
fn make_range(pos: u32) -> Range {
|
|
Range::new(
|
|
Position::new(pos.saturating_sub(1), 0),
|
|
Position::new(pos.saturating_sub(1), 1),
|
|
)
|
|
}
|
|
|
|
/// 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();
|
|
|
|
let config = Args::parse();
|
|
let vsg_args = config
|
|
.configuration
|
|
.iter()
|
|
.flat_map(|v| ["-c".to_string(), v.clone()])
|
|
.collect();
|
|
let (stdin, stdout) = (tokio::io::stdin(), tokio::io::stdout());
|
|
let (service, socket) = LspService::new(|client| Backend {
|
|
client,
|
|
config,
|
|
vsg_args,
|
|
});
|
|
Server::new(stdin, stdout, socket).serve(service).await;
|
|
}
|