Skip to content

Commit c8737c8

Browse files
authored
refactor(lsp-engine): 索引排除改由语言服务器声明 indexingExclusions,Core 不再识别 rust-analyzer 和 gopls (#68)
LSP 引擎原来按 provider 是 rust 还是 go 决定把排除目录写进 rust-analyzer.files.exclude 还是 gopls.directoryFilters,以及怎样写。 现在语言服务器在清单里声明 indexingExclusions(section、entry、rootEntry、 default、pathSyntax),启动计划的 sessionPolicy 带上它,引擎只按声明把 排除目录追加进服务器读到的配置;没有声明的服务器配置不变。 - plugin-language-servers:新增 IndexingExclusions 及校验,挂在会话字段上 - plugin-server-policy:SessionPolicy 接受并复核 indexingExclusions - lsp-engine:scan_settings 去掉按语言的分支,改为按声明填充 - 契约:README、schema、fixture、invalid-manifests、languages 参考页、 能力对照和协议更新记录 Refs 1lck/Lithe-IDEA#1856
1 parent a204691 commit c8737c8

17 files changed

Lines changed: 522 additions & 80 deletions

File tree

‎rust/crates/lsp-engine/src/configuration.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,12 @@ impl RuntimeSession {
155155
.lock()
156156
.map(|configuration| configuration.clone())
157157
.unwrap_or_else(|poisoned| poisoned.into_inner().clone());
158-
crate::scan_settings::configuration(&self.provider_id, &self.root_uri, base.as_deref())
159-
.map(Arc::new)
158+
crate::scan_settings::configuration(
159+
self.indexing_exclusions.as_ref(),
160+
&self.root_uri,
161+
base.as_deref(),
162+
)
163+
.map(Arc::new)
160164
}
161165

162166
pub(crate) fn update_plugin_configuration(

‎rust/crates/lsp-engine/src/engine.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,10 @@ impl LspEngine {
177177
let request_id = (initialize.state.next_request_id - 1).to_string();
178178
let now = Instant::now();
179179
let process_id = process.handle.process_id();
180+
let indexing_exclusions = request
181+
.session_policy
182+
.as_ref()
183+
.and_then(|policy| policy.indexing_exclusions.clone());
180184
let plugin_server = request.session_policy.map(PluginServerState::new);
181185
let session = Arc::new(RuntimeSession {
182186
startup_attempt: Arc::clone(attempt),
@@ -191,6 +195,7 @@ impl LspEngine {
191195
plugin_id: request.plugin_id,
192196
workspace_host: lithe_workspace::current(),
193197
plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)),
198+
indexing_exclusions,
194199
root_uri: request.root_uri,
195200
indexing_roots: Mutex::default(),
196201
indexing_revision: std::sync::atomic::AtomicU64::new(0),

‎rust/crates/lsp-engine/src/scan_settings.rs‎

Lines changed: 60 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
1-
//! Provider-owned native scan settings. These are not build-system exclusions.
1+
//! A server's declared indexing exclusions, written into the workspace
2+
//! configuration it reads. These are not build-system exclusions.
3+
use lithe_plugin_language_servers::IndexingExclusions;
24
use serde_json::{json, Value};
35

46
/// Overlay the current policy without mutating the user's stored configuration.
5-
/// Removing exclusions therefore restores the original settings exactly.
6-
pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value>) -> Option<Value> {
7-
if !matches!(provider, "rust" | "go") {
7+
/// Removing exclusions therefore restores the original settings exactly. A
8+
/// server that declares no `indexingExclusions` sees its configuration
9+
/// unchanged; Core never guesses the setting from the server or language.
10+
pub(crate) fn configuration(
11+
exclusions: Option<&IndexingExclusions>,
12+
root_uri: &str,
13+
base: Option<&Value>,
14+
) -> Option<Value> {
15+
let Some(exclusions) = exclusions else {
816
return base.cloned();
9-
}
17+
};
1018
let Some(root) = url::Url::parse(root_uri)
1119
.ok()
1220
.and_then(|uri| uri.to_file_path().ok())
@@ -18,48 +26,25 @@ pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value>
1826
return base.cloned();
1927
}
2028
Some(with_roots(
21-
provider,
29+
exclusions,
2230
base,
2331
&lithe_project::indexing::excluded_roots(&root),
2432
))
2533
}
2634

27-
fn with_roots(provider: &str, base: Option<&Value>, roots: &[String]) -> Value {
35+
fn with_roots(exclusions: &IndexingExclusions, base: Option<&Value>, roots: &[String]) -> Value {
2836
let mut configuration = base.cloned().unwrap_or_else(|| json!({}));
29-
match provider {
30-
// rust-analyzer.files.exclude takes literal workspace-relative paths, not globs.
31-
// https://rust-analyzer.github.io/book/configuration#rust-analyzerfilesexclude
32-
"rust" => append_array(
33-
&mut configuration,
34-
&["rust-analyzer", "files", "exclude"],
35-
roots.to_vec(),
36-
&[],
37-
),
38-
// https://go.dev/gopls/settings#directoryFilters: ordered filters, last match wins.
39-
// Preserve its documented default when the user did not configure this array.
40-
"go" => append_array(
41-
&mut configuration,
42-
&["gopls", "directoryFilters"],
43-
roots
44-
.iter()
45-
.filter(|path| !path.contains(['*', '?', '[', ']', '{', '}']))
46-
.map(|path| {
47-
if path == "." {
48-
"-".into()
49-
} else {
50-
format!("-{path}")
51-
}
52-
})
53-
.collect(),
54-
&["-**/node_modules"],
55-
),
56-
_ => {}
57-
}
37+
append_array(
38+
&mut configuration,
39+
&exclusions.section_keys(),
40+
exclusions.entries(roots),
41+
exclusions.default_entries(),
42+
);
5843
configuration
5944
}
6045

6146
/// Normalize owned dotted prefixes, so a request for the provider section sees them too.
62-
fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaults: &[&str]) {
47+
fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaults: &[String]) {
6348
for length in 2..=path.len() {
6449
let dotted = path[..length].join(".");
6550
let previous = value
@@ -80,8 +65,9 @@ fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaul
8065
if let Some(array) = slot.as_array_mut() {
8166
for addition in additions {
8267
let value = Value::String(addition);
83-
// Go filters are ordered: an existing exclusion before a later inclusion
84-
// must move to the end rather than being treated as a harmless duplicate.
68+
// Filters may be ordered with the last match winning: an existing
69+
// exclusion before a later inclusion must move to the end rather
70+
// than being treated as a harmless duplicate.
8571
array.retain(|item| item != &value);
8672
array.push(value);
8773
}
@@ -124,7 +110,7 @@ mod tests {
124110
"rust-analyzer.files.exclude":["leaf"]
125111
});
126112
let original = base.clone();
127-
let configured = with_roots("rust", Some(&base), &["vendor".into()]);
113+
let configured = with_roots(&literal(), Some(&base), &["vendor".into()]);
128114
assert_eq!(
129115
configured["rust-analyzer"]["files"],
130116
json!({
@@ -143,7 +129,11 @@ mod tests {
143129
#[test]
144130
fn native_exclusions_preserve_settings_and_restore_them_on_undo() {
145131
let base = json!({"rust-analyzer":{"files":{"exclude":["existing"]},"cargo":{"allFeatures":true}}});
146-
let excluded = with_roots("rust", Some(&base), &["vendor".into(), "带 空格".into()]);
132+
let excluded = with_roots(
133+
&literal(),
134+
Some(&base),
135+
&["vendor".into(), "带 空格".into()],
136+
);
147137
assert_eq!(
148138
excluded["rust-analyzer"]["files"]["exclude"],
149139
json!(["existing", "vendor", "带 空格"])
@@ -152,34 +142,56 @@ mod tests {
152142
excluded["rust-analyzer"]["cargo"],
153143
base["rust-analyzer"]["cargo"]
154144
);
155-
assert_eq!(with_roots("rust", Some(&base), &[]), base);
145+
assert_eq!(with_roots(&literal(), Some(&base), &[]), base);
156146
let go = json!({"gopls.directoryFilters":["+vendor","-cache"]});
157147
assert_eq!(
158-
with_roots("go", Some(&go), &["vendor".into()])["gopls"]["directoryFilters"],
148+
with_roots(&glob(), Some(&go), &["vendor".into()])["gopls"]["directoryFilters"],
159149
json!(["+vendor", "-cache", "-vendor"])
160150
);
161151
assert_eq!(
162152
with_roots(
163-
"go",
153+
&glob(),
164154
Some(&json!({"gopls":{"directoryFilters":["-vendor","+vendor"]}})),
165155
&["vendor".into()]
166156
)["gopls"]["directoryFilters"],
167157
json!(["+vendor", "-vendor"])
168158
);
169159
assert_eq!(
170-
with_roots("go", None, &["vendor".into()])["gopls"]["directoryFilters"],
171-
json!(["-**/node_modules", "-vendor"])
160+
with_roots(&glob(), None, &[".".into(), "vendor".into()])["gopls"]["directoryFilters"],
161+
json!(["-**/node_modules", "-", "-vendor"])
172162
);
173163
}
174164
#[test]
175165
fn native_patterns_do_not_accidentally_exclude_literal_metacharacter_siblings() {
176166
assert_eq!(
177-
with_roots("go", None, &["literal*".into()])["gopls"]["directoryFilters"],
167+
with_roots(&glob(), None, &["literal*".into()])["gopls"]["directoryFilters"],
178168
json!(["-**/node_modules"])
179169
);
180170
assert_eq!(
181-
with_roots("rust", None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"],
171+
with_roots(&literal(), None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"],
182172
json!(["literal*"])
183173
);
184174
}
175+
176+
/// A server whose setting takes literal paths, as rust-analyzer's
177+
/// `files.exclude` does.
178+
fn literal() -> IndexingExclusions {
179+
serde_json::from_value(
180+
json!({"section": "rust-analyzer.files.exclude", "entry": "${path}"}),
181+
)
182+
.unwrap()
183+
}
184+
185+
/// A server whose setting takes ordered glob filters with a default, as
186+
/// gopls's `directoryFilters` does.
187+
fn glob() -> IndexingExclusions {
188+
serde_json::from_value(json!({
189+
"section": "gopls.directoryFilters",
190+
"entry": "-${path}",
191+
"rootEntry": "-",
192+
"default": ["-**/node_modules"],
193+
"pathSyntax": "glob"
194+
}))
195+
.unwrap()
196+
}
185197
}

‎rust/crates/lsp-engine/src/state.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ pub(crate) struct RuntimeSession {
118118
/// Replaced as a whole by `lsp.updateWorkspaceConfiguration`; never held
119119
/// across another lock.
120120
pub(crate) plugin_configuration: Mutex<Option<Arc<Value>>>,
121+
/// The setting of `plugin_configuration` that lists the workspace's
122+
/// excluded directories, as the session policy declares it. Without one
123+
/// the configuration is answered unchanged.
124+
pub(crate) indexing_exclusions: Option<lithe_plugin_language_servers::IndexingExclusions>,
121125
/// Workspace URI the server was initialized with; scopes indexing
122126
/// exclusions and other workspace-wide checks to this session's root.
123127
pub(crate) root_uri: String,

‎rust/crates/lsp-engine/src/tests.rs‎

Lines changed: 39 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1759,31 +1759,53 @@ fn indexing_cold_start_resolves_git_before_provider_initialization() {
17591759
let status = lithe_project::indexing::configure(serde_json::from_value(json!({
17601760
"root": root, "manualExcludedDirectories": [], "includedDirectories": [], "gitIgnoreEnabled": true
17611761
})).unwrap(), crate::indexing_changed).unwrap();
1762-
let harness = Harness::start(|request| {
1763-
workspace.configure(request);
1764-
request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string();
1765-
});
1766-
assert!(notifications(&harness, "initialize").pop().is_some());
1767-
for (provider, pointer) in [
1768-
("go", "/gopls/directoryFilters"),
1769-
("rust", "/rust-analyzer/files/exclude"),
1762+
let start = |exclusions: Option<Value>| {
1763+
Harness::start(|request| {
1764+
workspace.configure(request);
1765+
request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string();
1766+
request.plugin_id = Some("io.example.server".into());
1767+
request.workspace_configuration = Some(json!({"server": {"mode": "full"}}));
1768+
request.session_policy = Some(
1769+
serde_json::from_value(
1770+
json!({"serverID": "server", "indexingExclusions": exclusions}),
1771+
)
1772+
.unwrap(),
1773+
);
1774+
})
1775+
};
1776+
// The server's declaration alone decides where the exclusions go and how
1777+
// one is written; its provider ID plays no part.
1778+
for (declaration, pointer, entry) in [
1779+
(
1780+
json!({"section": "server.filters", "entry": "-${path}", "pathSyntax": "glob"}),
1781+
"/server/filters",
1782+
"-ignored",
1783+
),
1784+
(
1785+
json!({"section": "server.files.exclude", "entry": "${path}"}),
1786+
"/server/files/exclude",
1787+
"ignored",
1788+
),
17701789
] {
1771-
let value =
1772-
crate::scan_settings::configuration(provider, &harness.session().root_uri, None)
1773-
.unwrap();
1790+
let harness = start(Some(declaration));
1791+
assert!(notifications(&harness, "initialize").pop().is_some());
1792+
let value = harness.session().plugin_configuration().unwrap();
1793+
assert_eq!(value["server"]["mode"], "full");
17741794
assert!(value
17751795
.pointer(pointer)
17761796
.unwrap()
17771797
.as_array()
17781798
.unwrap()
17791799
.iter()
1780-
.any(|item| item
1781-
== if provider == "go" {
1782-
"-ignored"
1783-
} else {
1784-
"ignored"
1785-
}));
1800+
.any(|item| item == entry));
17861801
}
1802+
let undeclared = start(None);
1803+
assert_eq!(
1804+
*undeclared.session().plugin_configuration().unwrap(),
1805+
json!({"server": {"mode": "full"}}),
1806+
"a server without indexingExclusions keeps its configuration"
1807+
);
1808+
drop(undeclared);
17871809
lithe_project::indexing::release(lithe_project::indexing::ReleaseIndexingRequest {
17881810
root: root.to_string_lossy().into_owned(),
17891811
revision: status.revision,

0 commit comments

Comments
 (0)