Skip to content

Commit

Permalink
Merge pull request #69 from zaytsev/config-file
Browse files Browse the repository at this point in the history
Add support for external JSON config file
  • Loading branch information
SilasMarvin authored Sep 5, 2024
2 parents bf4309a + b6908ea commit a4aff6f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
18 changes: 16 additions & 2 deletions crates/lsp-ai/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::sync::Mutex;
use std::{
collections::HashMap,
fs,
path::Path,
path::{Path, PathBuf},
sync::{mpsc, Arc},
thread,
};
Expand Down Expand Up @@ -68,6 +68,9 @@ struct Args {
// A dummy argument for now
#[arg(long, default_value_t = true)]
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> {
Expand Down Expand Up @@ -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<()> {
let args = Args::parse();
init_logger(&args);
Expand All @@ -130,7 +144,7 @@ fn main() -> Result<()> {
})?;
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:?}");
}

Expand Down
30 changes: 29 additions & 1 deletion crates/lsp-ai/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use anyhow::Context;
use std::path::PathBuf;

use anyhow::{anyhow, Context};
use lsp_server::ResponseError;
use once_cell::sync::Lazy;
use serde_json::Value;
use tokio::runtime;
use tree_sitter::Tree;

Expand Down Expand Up @@ -93,3 +96,28 @@ pub(crate) fn format_file_chunk(uri: &str, excerpt: &str, root_uri: Option<&str>
{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();
}
}
}

0 comments on commit a4aff6f

Please sign in to comment.