Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(ls): persist lint ignores (#1250)

Elijah Potter8689146c558e
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index 9bc7d7288..702e5013e 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -10,7 +10,8 @@ use harper_comments::CommentParser;
use harper_core::linting::{LintGroup, LintGroupConfig};
use harper_core::parsers::{CollapseIdentifiers, IsolateEnglish, Markdown, Parser, PlainEnglish};
use harper_core::{
- Dialect, Dictionary, Document, FstDictionary, MergedDictionary, MutableDictionary, WordMetadata,
+ Dialect, Dictionary, Document, FstDictionary, IgnoredLints, MergedDictionary,
+ MutableDictionary, WordMetadata,
};
use harper_html::HtmlParser;
use harper_literate_haskell::LiterateHaskellParser;
@@ -33,9 +34,11 @@ use tower_lsp::{Client, LanguageServer};
use tracing::{error, info, warn};
use crate::config::Config;
-use crate::dictionary_io::{file_dict_name, load_dict, save_dict};
+use crate::dictionary_io::{load_dict, save_dict};
use crate::document_state::DocumentState;
use crate::git_commit_parser::GitCommitParser;
+use crate::ignored_lints_io::{load_ignored_lints, save_ignored_lints};
+use crate::io_utils::fileify_path;
use harper_stats::{Record, Stats};
pub struct Backend {
@@ -73,11 +76,40 @@ impl Backend {
.or(Ok(MutableDictionary::new()))
}
+ /// Compute the location of the ignored lint's store.
+ async fn get_ignored_lints_path(&self, url: &Url) -> anyhow::Result<PathBuf> {
+ let config = self.config.read().await;
+
+ Ok(config.ignored_lints_path.join(fileify_path(url)?))
+ }
+
+ async fn save_ignored_lints(&self, url: &Url, ignored_lints: &IgnoredLints) -> Result<()> {
+ save_ignored_lints(
+ self.get_ignored_lints_path(url)
+ .await
+ .context("Unable to get ignored lints path.")?,
+ ignored_lints,
+ )
+ .await
+ .context("Unable to save ignored lints to path.")
+ }
+
+ async fn load_ignored_lints(&self, url: &Url) -> Result<IgnoredLints> {
+ Ok(load_ignored_lints(
+ self.get_ignored_lints_path(url)
+ .await
+ .context("Unable to get ignored lints path.")?,
+ )
+ .await
+ .map_err(|err| info!("{err}"))
+ .unwrap_or(IgnoredLints::new()))
+ }
+
/// Compute the location of the file's specific dictionary
async fn get_file_dict_path(&self, url: &Url) -> anyhow::Result<PathBuf> {
let config = self.config.read().await;
- Ok(config.file_dict_path.join(file_dict_name(url)?))
+ Ok(config.file_dict_path.join(fileify_path(url)?))
}
async fn save_file_dictionary(&self, url: &Url, dict: impl Dictionary) -> Result<()> {
@@ -188,11 +220,13 @@ impl Backend {
);
let mut doc_lock = self.doc_state.lock().await;
+ let ignored_lints = self.load_ignored_lints(url).await.unwrap_or_default();
let doc_state = doc_lock.entry(url.clone()).or_insert_with(|| {
info!("Constructing new LintGroup for new document.");
DocumentState {
+ ignored_lints,
linter: LintGroup::new_curated(dict.clone(), dialect)
.with_lint_config(lint_config.clone()),
language_id: language_id.map(|v| v.to_string()),
@@ -641,6 +675,13 @@ impl LanguageServer for Backend {
};
doc_state.ignore_lint(&lint);
+ if let Err(_err) = self
+ .save_ignored_lints(&url, &doc_state.ignored_lints)
+ .await
+ {
+ error!("Unable to save ignored lints.");
+ return Ok(None);
+ }
drop(doc_lock);
diff --git a/harper-ls/src/config.rs b/harper-ls/src/config.rs
index 4ebd2d104..83151418b 100644
--- a/harper-ls/src/config.rs
+++ b/harper-ls/src/config.rs
@@ -65,6 +65,7 @@ impl CodeActionConfig {
pub struct Config {
pub user_dict_path: PathBuf,
pub file_dict_path: PathBuf,
+ pub ignored_lints_path: PathBuf,
pub stats_path: PathBuf,
pub lint_config: LintGroupConfig,
pub diagnostic_severity: DiagnosticSeverity,
@@ -108,6 +109,17 @@ impl Config {
}
}
+ if let Some(v) = value.get("ignoredLintsPath") {
+ if !v.is_string() {
+ bail!("ignoredLintsPath path must be a string.");
+ }
+
+ let path = v.as_str().unwrap();
+ if !path.is_empty() {
+ base.ignored_lints_path = path.try_resolve()?.to_path_buf();
+ }
+ }
+
if let Some(v) = value.get("statsPath") {
if let Value::String(path) = v {
base.file_dict_path = path.try_resolve()?.to_path_buf();
@@ -157,6 +169,7 @@ impl Default for Config {
file_dict_path: data_local_dir()
.unwrap()
.join("harper-ls/file_dictionaries/"),
+ ignored_lints_path: data_local_dir().unwrap().join("harper-ls/ignored_lints/"),
stats_path: data_local_dir().unwrap().join("harper-ls/stats.txt"),
lint_config: LintGroupConfig::default(),
diagnostic_severity: DiagnosticSeverity::Hint,
diff --git a/harper-ls/src/dictionary_io.rs b/harper-ls/src/dictionary_io.rs
index eae083274..302c9c5c9 100644
--- a/harper-ls/src/dictionary_io.rs
+++ b/harper-ls/src/dictionary_io.rs
@@ -1,11 +1,9 @@
-use anyhow::anyhow;
use itertools::Itertools;
-use std::path::{Component, Path, PathBuf};
+use std::path::Path;
use harper_core::{Dictionary, MutableDictionary, WordMetadata};
use tokio::fs::{self, File};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter, Result};
-use tower_lsp::lsp_types::Url;
/// Save the contents of a dictionary to a file.
/// Ensures that the path to the destination exists.
@@ -63,26 +61,6 @@ async fn dict_from_word_list(mut r: impl AsyncRead + Unpin) -> Result<MutableDic
Ok(dict)
}
-/// Rewrites a path to a filename using the same conventions as
-/// [Neovim's undo-files](https://neovim.io/doc/user/options.html#'undodir').
-pub fn file_dict_name(url: &Url) -> anyhow::Result<PathBuf> {
- let mut rewritten = String::new();
-
- // We assume all URLs are local files and have a base.
- for seg in url
- .to_file_path()
- .map_err(|_| anyhow!("Unable to convert URL to file path."))?
- .components()
- {
- if !matches!(seg, Component::RootDir) {
- rewritten.push_str(&seg.as_os_str().to_string_lossy());
- rewritten.push('%');
- }
- }
-
- Ok(rewritten.into())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/harper-ls/src/ignored_lints_io.rs b/harper-ls/src/ignored_lints_io.rs
new file mode 100644
index 000000000..90f9c1c17
--- /dev/null
+++ b/harper-ls/src/ignored_lints_io.rs
@@ -0,0 +1,40 @@
+use std::path::Path;
+
+use anyhow::Result;
+use harper_core::IgnoredLints;
+use tokio::{
+ fs::{self, File},
+ io::{AsyncReadExt, AsyncWriteExt, BufReader, BufWriter},
+};
+
+/// Save the contents of a dictionary to a file.
+/// Ensures that the path to the destination exists.
+pub async fn save_ignored_lints(
+ path: impl AsRef<Path>,
+ ignored_lints: &IgnoredLints,
+) -> Result<()> {
+ if let Some(parent) = path.as_ref().parent() {
+ fs::create_dir_all(parent).await?;
+ }
+
+ let file = File::create(path.as_ref()).await?;
+ let mut write = BufWriter::new(file);
+
+ let json = serde_json::to_string_pretty(ignored_lints)?;
+ write.write_all(json.as_bytes()).await?;
+
+ write.flush().await?;
+
+ Ok(())
+}
+
+/// Load ignored lints from a file on disk.
+pub async fn load_ignored_lints(path: impl AsRef<Path>) -> Result<IgnoredLints> {
+ let file = File::open(path.as_ref()).await?;
+ let mut read = BufReader::new(file);
+
+ let mut buf = String::new();
+ read.read_to_string(&mut buf).await?;
+
+ Ok(serde_json::from_str(&buf)?)
+}
diff --git a/harper-ls/src/io_utils.rs b/harper-ls/src/io_utils.rs
new file mode 100644
index 000000000..3ddd1a846
--- /dev/null
+++ b/harper-ls/src/io_utils.rs
@@ -0,0 +1,24 @@
+use anyhow::anyhow;
+use std::path::{Component, PathBuf};
+
+use tower_lsp::lsp_types::Url;
+
+/// Rewrites a path to a filename using the same conventions as
+/// [Neovim's undo-files](https://neovim.io/doc/user/options.html#'undodir').
+pub fn fileify_path(url: &Url) -> anyhow::Result<PathBuf> {
+ let mut rewritten = String::new();
+
+ // We assume all URLs are local files and have a base.
+ for seg in url
+ .to_file_path()
+ .map_err(|_| anyhow!("Unable to convert URL to file path."))?
+ .components()
+ {
+ if !matches!(seg, Component::RootDir) {
+ rewritten.push_str(&seg.as_os_str().to_string_lossy());
+ rewritten.push('%');
+ }
+ }
+
+ Ok(rewritten.into())
+}
diff --git a/harper-ls/src/main.rs b/harper-ls/src/main.rs
index 07b43ac55..7b0fd7b5c 100644
--- a/harper-ls/src/main.rs
+++ b/harper-ls/src/main.rs
@@ -10,6 +10,8 @@ mod diagnostics;
mod dictionary_io;
mod document_state;
mod git_commit_parser;
+mod ignored_lints_io;
+mod io_utils;
mod pos_conv;
use backend::Backend;
diff --git a/packages/web/src/routes/docs/integrations/language-server/+page.md b/packages/web/src/routes/docs/integrations/language-server/+page.md
index 97a68fe0a..b72d3fa6f 100644
--- a/packages/web/src/routes/docs/integrations/language-server/+page.md
+++ b/packages/web/src/routes/docs/integrations/language-server/+page.md
@@ -163,12 +163,13 @@ In the above example, "spellcheckd", "this this", and other spelling or grammar
}
```
-### Dictionaries
+## Directories
| Config | Type | Default Value | Description |
| -------------- | -------- | ------------- | --------------------------------------------------------------- |
| `userDictPath` | `string` | `""` | Set the file path where the user dictionary is located |
| `fileDictPath` | `string` | `""` | Set the directory where the file-local dictionaries are located |
+| `ignoredLintsPath` | `string` | `""` | Set the directory where the ignored lint lists are located |
### Linters