Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat: user dictionary path configuration
Elijah Potter6288b18ba08b
diff --git a/Cargo.lock b/Cargo.lockindex 6168b6dc5..9d2bc9f36 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -323,13 +323,33 @@ dependencies = ["parking_lot_core",]+[[package]]+name = "dirs"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"+dependencies = [+ "dirs-sys 0.3.7",+]+[[package]]name = "dirs"version = "5.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"dependencies = [- "dirs-sys",+ "dirs-sys 0.4.1",+]++[[package]]+name = "dirs-sys"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"+dependencies = [+ "libc",+ "redox_users",+ "winapi",][[package]]@@ -526,10 +546,11 @@ version = "0.7.4"dependencies = ["anyhow","clap",- "dirs",+ "dirs 5.0.1","harper-core","itertools 0.12.1","once_cell",+ "resolve-path","serde_json","tokio","tower-lsp",@@ -1021,6 +1042,15 @@ version = "0.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"+[[package]]+name = "resolve-path"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "321e5e41b3b192dab6f1e75b9deacb6688b4b8c5e68906a78e8f43e7c2887bb5"+dependencies = [+ "dirs 4.0.0",+]+[[package]]name = "rustc-demangle"version = "0.1.23"diff --git a/harper-ls/Cargo.toml b/harper-ls/Cargo.tomlindex cfb42ecf6..597218b42 100644--- a/harper-ls/Cargo.toml+++ b/harper-ls/Cargo.toml@@ -32,3 +32,4 @@ serde_json = "1.0.114"itertools = "0.12.1"tracing = "0.1.40"tracing-subscriber = "0.3.18"+resolve-path = "0.1.0"diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rsindex e52cfff9a..ee0879ab1 100644--- a/harper-ls/src/backend.rs+++ b/harper-ls/src/backend.rs@@ -15,6 +15,7 @@ use tower_lsp::lsp_types::{CodeActionProviderCapability,CodeActionResponse,Diagnostic,+ DidChangeConfigurationParams,DidChangeTextDocumentParams,DidCloseTextDocumentParams,DidOpenTextDocumentParams,@@ -35,7 +36,7 @@ use tower_lsp::lsp_types::{Url};use tower_lsp::{Client, LanguageServer};-use tracing::error;+use tracing::{error, info};use crate::config::Config;use crate::diagnostics::{lint_to_code_actions, lints_to_diagnostics};@@ -54,7 +55,7 @@ struct DocumentState {pub struct Backend {client: Client,static_dictionary: Arc<FullDictionary>,- config: Config,+ config: Mutex<Config>,doc_state: Mutex<HashMap<Url, DocumentState>>}@@ -66,7 +67,7 @@ impl Backend {client,static_dictionary: dictionary.into(),doc_state: Mutex::new(HashMap::new()),- config+ config: Mutex::new(config)}}@@ -84,12 +85,14 @@ impl Backend {rewritten.into()}- fn get_file_dict_path(&self, url: &Url) -> PathBuf {- self.config.file_dict_path.join(Self::file_dict_name(url))+ async fn get_file_dict_path(&self, url: &Url) -> PathBuf {+ let config = self.config.lock().await;++ config.file_dict_path.join(Self::file_dict_name(url))}async fn load_file_dictionary(&self, url: &Url) -> FullDictionary {- match load_dict(self.get_file_dict_path(url)).await {+ match load_dict(self.get_file_dict_path(url).await).await {Ok(dict) => dict,Err(err) => {error!("Problem loading file dictionary: {}", err);@@ -100,11 +103,22 @@ impl Backend {}async fn save_file_dictionary(&self, url: &Url, dict: impl Dictionary) -> anyhow::Result<()> {- Ok(save_dict(self.get_file_dict_path(url), dict).await?)+ Ok(save_dict(self.get_file_dict_path(url).await, dict).await?)}async fn load_user_dictionary(&self) -> FullDictionary {- match load_dict(&self.config.user_dict_path).await {+ let config = self.config.lock().await;++ info!(+ "Loading user dictionary from `{}`",+ config+ .user_dict_path+ .clone()+ .into_os_string()+ .to_string_lossy()+ );++ match load_dict(&config.user_dict_path).await {Ok(dict) => dict,Err(err) => {error!("Problem loading user dictionary: {}", err);@@ -115,7 +129,18 @@ impl Backend {}async fn save_user_dictionary(&self, dict: impl Dictionary) -> anyhow::Result<()> {- Ok(save_dict(&self.config.user_dict_path, dict).await?)+ let config = self.config.lock().await;++ info!(+ "Saving user dictionary to `{}`",+ config+ .user_dict_path+ .clone()+ .into_os_string()+ .to_string_lossy()+ );++ Ok(save_dict(&config.user_dict_path, dict).await?)}async fn generate_global_dictionary(&self) -> anyhow::Result<MergedDictionary<FullDictionary>> {@@ -351,12 +376,17 @@ impl LanguageServer for Backend {"AddToUserDict" => {let mut dict = self.load_user_dictionary().await;dict.append_word(word);- self.save_user_dictionary(dict).await.unwrap();+ if let Err(err) = self.save_user_dictionary(dict).await {+ error!("Unable to save user dictionary: {}", err);+ }}"AddToFileDict" => {let mut dict = self.load_file_dictionary(&file_url).await;dict.append_word(word);- self.save_file_dictionary(&file_url, dict).await.unwrap();++ if let Err(err) = self.save_file_dictionary(&file_url, dict).await {+ error!("Unable to save file dictionary: {}", err);+ }}_ => ()}@@ -367,6 +397,21 @@ impl LanguageServer for Backend {Ok(None)}+ async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {+ info!("Changing user configuration.");++ let new_config = match Config::from_json_value(params.settings) {+ Ok(new_config) => new_config,+ Err(err) => {+ error!("Unable to change config: {}", err);+ return;+ }+ };++ let mut config = self.config.lock().await;+ *config = new_config;+ }+async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {let actions = self.generate_code_actions(¶ms.text_document.uri, params.range)diff --git a/harper-ls/src/config.rs b/harper-ls/src/config.rsindex 18e47516c..4d4421b5a 100644--- a/harper-ls/src/config.rs+++ b/harper-ls/src/config.rs@@ -1,6 +1,8 @@use std::path::PathBuf;use dirs::{config_dir, data_local_dir};+use resolve_path::PathResolveExt;+use serde_json::Value;#[derive(Debug, Clone)]pub struct Config {@@ -8,6 +10,26 @@ pub struct Config {pub file_dict_path: PathBuf}+impl Config {+ pub fn from_json_value(value: Value) -> anyhow::Result<Self> {+ let mut base = Config::default();++ let Value::Object(value) = value else {+ return Err(anyhow::format_err!("Settings must be an object."));+ };++ if let Some(v) = value.get("userDictPath") {+ if let Value::String(path) = v {+ base.user_dict_path = path.try_resolve()?.to_path_buf();+ } else {+ return Err(anyhow::format_err!("userDict path must be a string."));+ }+ }++ Ok(base)+ }+}+impl Default for Config {fn default() -> Self {Self {diff --git a/harper-ls/src/dictionary_io.rs b/harper-ls/src/dictionary_io.rsindex 5861b8ccb..98b34b75b 100644--- a/harper-ls/src/dictionary_io.rs+++ b/harper-ls/src/dictionary_io.rs@@ -1,13 +1,19 @@use std::path::Path;use harper_core::{Dictionary, FullDictionary};-use tokio::fs::File;+use tokio::fs::{self, File};use tokio::io::{self, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};+/// Save the contents of a dictionary to a file.+/// Ensures that the path to the destination exists.pub async fn save_dict(path: impl AsRef<Path>, dict: impl Dictionary) -> io::Result<()> {let file = File::create(path.as_ref()).await?;let write = BufReader::new(file);+ if let Some(parent) = path.as_ref().parent() {+ fs::create_dir_all(parent).await?;+ }+write_word_list(dict, write).await?;Ok(())diff --git a/harper-ls/src/main.rs b/harper-ls/src/main.rsindex 3821ff815..5bb9bd0ad 100644--- a/harper-ls/src/main.rs+++ b/harper-ls/src/main.rs@@ -1,7 +1,6 @@use std::io::stderr;use config::Config;-use tokio::fs;use tokio::net::TcpListener;mod backend;mod config;@@ -26,7 +25,7 @@ struct Args {async fn main() -> anyhow::Result<()> {let subscriber = FmtSubscriber::builder().map_writer(move |_| stderr)- .with_max_level(Level::TRACE)+ .with_max_level(Level::INFO).finish();tracing::subscriber::set_global_default(subscriber)?;@@ -34,10 +33,6 @@ async fn main() -> anyhow::Result<()> {let args = Args::parse();let config = Config::default();- // Make sure these are available.- fs::create_dir_all(config.user_dict_path.parent().unwrap()).await?;- fs::create_dir_all(&config.file_dict_path).await?;-let (service, socket) = LspService::new(|client| Backend::new(client, config));if args.stdio {