Skip to content

Commit 74cdb92

Browse files
Copilotcoder3101
andcommitted
Add support for setting include paths via initializationParams
Co-authored-by: coder3101 <[email protected]>
1 parent b7152c8 commit 74cdb92

File tree

5 files changed

+202
-3
lines changed

5 files changed

+202
-3
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ walkdir = "2.5"
2626
hard-xml = "1.41"
2727
tempfile = "3.21"
2828
serde = { version = "1", features = ["derive"] }
29+
serde_json = "1.0"
2930
basic-toml = "0.1"
3031
pkg-config = "0.3"
3132
clap = { version = "4.5", features = ["derive"] }

README.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ Then, configure it in your `init.lua` using [nvim-lspconfig](https://github.com/
5858
require'lspconfig'.protols.setup{}
5959
```
6060

61+
#### Setting Include Paths in Neovim
62+
63+
For dynamic configuration of include paths, you can use the `before_init` callback to set them via `initializationParams`:
64+
65+
```lua
66+
require'lspconfig'.protols.setup{
67+
before_init = function(_, config)
68+
config.init_options = {
69+
include_paths = {
70+
"/usr/local/include/protobuf",
71+
"vendor/protos",
72+
"../shared-protos"
73+
}
74+
}
75+
end
76+
}
77+
```
78+
6179
### Command Line Options
6280

6381
Protols supports various command line options to customize its behavior:
@@ -106,7 +124,12 @@ protoc = "protoc"
106124

107125
The `[config]` section contains stable settings that should generally remain unchanged.
108126

109-
- `include_paths`: These are directories where `.proto` files are searched. Paths can be absolute or relative to the LSP workspace root, which is already included in the `include_paths`. You can also specify this using the `--include-paths` flag in the command line. The include paths from the CLI are combined with those from the configuration. While configuration-based include paths are specific to a workspace, the CLI-specified paths apply to all workspaces on the server.
127+
- `include_paths`: These are directories where `.proto` files are searched. Paths can be absolute or relative to the LSP workspace root, which is already included in the `include_paths`. You can also specify include paths using:
128+
- **Configuration file**: Workspace-specific paths defined in `protols.toml`
129+
- **Command line**: Global paths using `--include-paths` flag that apply to all workspaces
130+
- **Initialization parameters**: Dynamic paths set via LSP `initializationParams` (useful for editors like Neovim)
131+
132+
All include paths from these sources are combined when resolving proto imports.
110133

111134
#### Path Configuration
112135

src/config/workspace.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub struct WorkspaceProtoConfigs {
1919
formatters: HashMap<Url, ClangFormatter>,
2020
protoc_include_prefix: Vec<PathBuf>,
2121
cli_include_paths: Vec<PathBuf>,
22+
init_include_paths: Vec<PathBuf>,
2223
}
2324

2425
impl WorkspaceProtoConfigs {
@@ -40,6 +41,7 @@ impl WorkspaceProtoConfigs {
4041
configs: HashMap::new(),
4142
protoc_include_prefix,
4243
cli_include_paths,
44+
init_include_paths: Vec::new(),
4345
}
4446
}
4547

@@ -90,6 +92,10 @@ impl WorkspaceProtoConfigs {
9092
.find(|&k| upath.starts_with(k.to_file_path().unwrap()))
9193
}
9294

95+
pub fn set_init_include_paths(&mut self, paths: Vec<PathBuf>) {
96+
self.init_include_paths = paths;
97+
}
98+
9399
pub fn get_include_paths(&self, uri: &Url) -> Option<Vec<PathBuf>> {
94100
let cfg = self.get_config_for_uri(uri)?;
95101
let w = self.get_workspace_for_uri(uri)?.to_file_path().ok()?;
@@ -111,6 +117,15 @@ impl WorkspaceProtoConfigs {
111117
}
112118
}
113119

120+
// Add initialization include paths
121+
for path in &self.init_include_paths {
122+
if path.is_relative() {
123+
ipath.push(w.join(path));
124+
} else {
125+
ipath.push(path.clone());
126+
}
127+
}
128+
114129
ipath.push(w.to_path_buf());
115130
ipath.extend_from_slice(&self.protoc_include_prefix);
116131
Some(ipath)
@@ -276,4 +291,38 @@ mod test {
276291
// The absolute path should be included as is
277292
assert!(include_paths.contains(&PathBuf::from("/path/to/protos")));
278293
}
294+
295+
#[test]
296+
fn test_init_include_paths() {
297+
let tmpdir = tempdir().expect("failed to create temp directory");
298+
let f = tmpdir.path().join("protols.toml");
299+
std::fs::write(f, include_str!("input/protols-valid.toml")).unwrap();
300+
301+
// Set both CLI and initialization include paths
302+
let cli_paths = vec![PathBuf::from("/cli/path")];
303+
let init_paths = vec![
304+
PathBuf::from("/init/path1"),
305+
PathBuf::from("relative/init/path"),
306+
];
307+
308+
let mut ws = WorkspaceProtoConfigs::new(cli_paths);
309+
ws.set_init_include_paths(init_paths);
310+
ws.add_workspace(&WorkspaceFolder {
311+
uri: Url::from_directory_path(tmpdir.path()).unwrap(),
312+
name: "Test".to_string(),
313+
});
314+
315+
let inworkspace = Url::from_file_path(tmpdir.path().join("foobar.proto")).unwrap();
316+
let include_paths = ws.get_include_paths(&inworkspace).unwrap();
317+
318+
// Check that initialization paths are included
319+
assert!(include_paths.contains(&PathBuf::from("/init/path1")));
320+
321+
// The relative path should be resolved relative to the workspace
322+
let resolved_relative_path = tmpdir.path().join("relative/init/path");
323+
assert!(include_paths.contains(&resolved_relative_path));
324+
325+
// CLI paths should still be included
326+
assert!(include_paths.contains(&PathBuf::from("/cli/path")));
327+
}
279328
}

src/lsp.rs

Lines changed: 127 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::ops::ControlFlow;
2-
use std::{collections::HashMap, fs::read_to_string};
3-
use tracing::{error, info};
2+
use std::{collections::HashMap, fs::read_to_string, path::PathBuf};
3+
use tracing::{error, info, warn};
44

55
use async_lsp::lsp_types::{
66
CompletionItem, CompletionItemKind, CompletionOptions, CompletionParams, CompletionResponse,
@@ -18,6 +18,7 @@ use async_lsp::lsp_types::{
1818
};
1919
use async_lsp::{LanguageClient, ResponseError};
2020
use futures::future::BoxFuture;
21+
use serde_json::Value;
2122

2223
use crate::docs;
2324
use crate::formatter::ProtoFormatter;
@@ -38,6 +39,14 @@ impl ProtoLanguageServer {
3839

3940
info!("Connected with client {cname} {cversion}");
4041

42+
// Parse initialization options for include paths
43+
if let Some(init_options) = &params.initialization_options {
44+
if let Some(include_paths) = parse_init_include_paths(init_options) {
45+
info!("Setting include paths from initialization options: {:?}", include_paths);
46+
self.configs.set_init_include_paths(include_paths);
47+
}
48+
}
49+
4150
let file_operation_filers = vec![FileOperationFilter {
4251
scheme: Some(String::from("file")),
4352
pattern: FileOperationPattern {
@@ -523,3 +532,119 @@ impl ProtoLanguageServer {
523532
ControlFlow::Continue(())
524533
}
525534
}
535+
536+
/// Parse include_paths from initialization options
537+
fn parse_init_include_paths(init_options: &Value) -> Option<Vec<PathBuf>> {
538+
match init_options {
539+
Value::Object(obj) => {
540+
if let Some(Value::Array(paths)) = obj.get("include_paths") {
541+
let mut result = Vec::new();
542+
for path_value in paths {
543+
if let Value::String(path) = path_value {
544+
result.push(PathBuf::from(path));
545+
} else {
546+
warn!("Invalid include path in initialization options: {:?}", path_value);
547+
}
548+
}
549+
if !result.is_empty() {
550+
return Some(result);
551+
}
552+
} else if let Some(Value::String(paths_str)) = obj.get("include_paths") {
553+
// Support comma-separated string format like CLI
554+
let result: Vec<PathBuf> = paths_str
555+
.split(',')
556+
.map(|s| PathBuf::from(s.trim()))
557+
.collect();
558+
if !result.is_empty() {
559+
return Some(result);
560+
}
561+
}
562+
}
563+
_ => {
564+
warn!("initialization_options is not an object: {:?}", init_options);
565+
}
566+
}
567+
None
568+
}
569+
570+
#[cfg(test)]
571+
mod tests {
572+
use super::*;
573+
use serde_json::json;
574+
575+
#[test]
576+
fn test_parse_init_include_paths_array() {
577+
let init_options = json!({
578+
"include_paths": ["/path/to/protos", "relative/path"]
579+
});
580+
581+
let result = parse_init_include_paths(&init_options).unwrap();
582+
assert_eq!(result.len(), 2);
583+
assert_eq!(result[0], PathBuf::from("/path/to/protos"));
584+
assert_eq!(result[1], PathBuf::from("relative/path"));
585+
}
586+
587+
#[test]
588+
fn test_parse_init_include_paths_string() {
589+
let init_options = json!({
590+
"include_paths": "/path1,/path2,relative/path"
591+
});
592+
593+
let result = parse_init_include_paths(&init_options).unwrap();
594+
assert_eq!(result.len(), 3);
595+
assert_eq!(result[0], PathBuf::from("/path1"));
596+
assert_eq!(result[1], PathBuf::from("/path2"));
597+
assert_eq!(result[2], PathBuf::from("relative/path"));
598+
}
599+
600+
#[test]
601+
fn test_parse_init_include_paths_missing() {
602+
let init_options = json!({
603+
"other_option": "value"
604+
});
605+
606+
let result = parse_init_include_paths(&init_options);
607+
assert!(result.is_none());
608+
}
609+
610+
#[test]
611+
fn test_parse_init_include_paths_invalid_format() {
612+
let init_options = json!({
613+
"include_paths": 123
614+
});
615+
616+
let result = parse_init_include_paths(&init_options);
617+
assert!(result.is_none());
618+
}
619+
620+
#[test]
621+
fn test_parse_init_include_paths_mixed_array() {
622+
let init_options = json!({
623+
"include_paths": ["/valid/path", 123, "another/valid/path"]
624+
});
625+
626+
let result = parse_init_include_paths(&init_options).unwrap();
627+
assert_eq!(result.len(), 2); // Only valid strings should be included
628+
assert_eq!(result[0], PathBuf::from("/valid/path"));
629+
assert_eq!(result[1], PathBuf::from("another/valid/path"));
630+
}
631+
632+
#[test]
633+
fn test_initialization_options_integration() {
634+
// Test what a real client would send
635+
let neovim_style_init_options = json!({
636+
"include_paths": [
637+
"/usr/local/include/protobuf",
638+
"vendor/protos",
639+
"../shared-protos"
640+
]
641+
});
642+
643+
let include_paths = parse_init_include_paths(&neovim_style_init_options).unwrap();
644+
645+
assert_eq!(include_paths.len(), 3);
646+
assert_eq!(include_paths[0], PathBuf::from("/usr/local/include/protobuf"));
647+
assert_eq!(include_paths[1], PathBuf::from("vendor/protos"));
648+
assert_eq!(include_paths[2], PathBuf::from("../shared-protos"));
649+
}
650+
}

0 commit comments

Comments
 (0)