Merge pull request #69 from zaytsev/config-file

Add support for external JSON config file
This commit is contained in:
Silas Marvin
2024-09-05 07:35:26 -07:00
committed by GitHub
2 changed files with 45 additions and 3 deletions

View File

@@ -11,7 +11,7 @@ use std::sync::Mutex;
use std::{ use std::{
collections::HashMap, collections::HashMap,
fs, fs,
path::Path, path::{Path, PathBuf},
sync::{mpsc, Arc}, sync::{mpsc, Arc},
thread, thread,
}; };
@@ -68,6 +68,9 @@ struct Args {
// A dummy argument for now // A dummy argument for now
#[arg(long, default_value_t = true)] #[arg(long, default_value_t = true)]
stdio: bool, stdio: bool,
// JSON configuration file location
#[arg(long, value_parser = utils::validate_file_exists, required = false)]
config: Option<PathBuf>,
} }
fn create_log_file(base_path: &Path) -> anyhow::Result<fs::File> { fn create_log_file(base_path: &Path) -> anyhow::Result<fs::File> {
@@ -109,6 +112,17 @@ fn init_logger(args: &Args) {
} }
} }
fn load_config(args: &Args, init_args: serde_json::Value) -> anyhow::Result<serde_json::Value> {
if let Some(config_path) = &args.config {
let config_data = fs::read_to_string(config_path)?;
let mut config = serde_json::from_str(&config_data)?;
utils::merge_json(&mut config, &init_args);
Ok(config)
} else {
Ok(init_args)
}
}
fn main() -> Result<()> { fn main() -> Result<()> {
let args = Args::parse(); let args = Args::parse();
init_logger(&args); init_logger(&args);
@@ -130,7 +144,7 @@ fn main() -> Result<()> {
})?; })?;
let initialization_args = connection.initialize(server_capabilities)?; let initialization_args = connection.initialize(server_capabilities)?;
if let Err(e) = main_loop(connection, initialization_args) { if let Err(e) = main_loop(connection, load_config(&args, initialization_args)?) {
error!("{e:?}"); error!("{e:?}");
} }

View File

@@ -1,6 +1,9 @@
use anyhow::Context; use std::path::PathBuf;
use anyhow::{anyhow, Context};
use lsp_server::ResponseError; use lsp_server::ResponseError;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde_json::Value;
use tokio::runtime; use tokio::runtime;
use tree_sitter::Tree; use tree_sitter::Tree;
@@ -93,3 +96,28 @@ pub(crate) fn format_file_chunk(uri: &str, excerpt: &str, root_uri: Option<&str>
{excerpt}"#, {excerpt}"#,
) )
} }
pub(crate) fn validate_file_exists(path: &str) -> anyhow::Result<PathBuf> {
let path = PathBuf::from(path);
if path.is_file() {
Ok(path)
} else {
Err(anyhow!("File doesn't exist: {}", path.display()))
}
}
pub(crate) fn merge_json(a: &mut Value, b: &Value) {
match (a, b) {
(&mut Value::Object(ref mut a), &Value::Object(ref b)) => {
for (k, v) in b {
merge_json(a.entry(k.clone()).or_insert(Value::Null), v);
}
}
(&mut Value::Array(ref mut a), &Value::Array(ref b)) => {
a.extend(b.clone());
}
(a, b) => {
*a = b.clone();
}
}
}