Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions rust/crates/lsp-engine/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,12 @@ impl RuntimeSession {
.lock()
.map(|configuration| configuration.clone())
.unwrap_or_else(|poisoned| poisoned.into_inner().clone());
crate::scan_settings::configuration(&self.provider_id, &self.root_uri, base.as_deref())
.map(Arc::new)
crate::scan_settings::configuration(
self.indexing_exclusions.as_ref(),
&self.root_uri,
base.as_deref(),
)
.map(Arc::new)
}

pub(crate) fn update_plugin_configuration(
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/lsp-engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ impl LspEngine {
let request_id = (initialize.state.next_request_id - 1).to_string();
let now = Instant::now();
let process_id = process.handle.process_id();
let indexing_exclusions = request
.session_policy
.as_ref()
.and_then(|policy| policy.indexing_exclusions.clone());
let plugin_server = request.session_policy.map(PluginServerState::new);
let session = Arc::new(RuntimeSession {
startup_attempt: Arc::clone(attempt),
Expand All @@ -191,6 +195,7 @@ impl LspEngine {
plugin_id: request.plugin_id,
workspace_host: lithe_workspace::current(),
plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)),
indexing_exclusions,
root_uri: request.root_uri,
indexing_roots: Mutex::default(),
indexing_revision: std::sync::atomic::AtomicU64::new(0),
Expand Down
108 changes: 60 additions & 48 deletions rust/crates/lsp-engine/src/scan_settings.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
//! Provider-owned native scan settings. These are not build-system exclusions.
//! A server's declared indexing exclusions, written into the workspace
//! configuration it reads. These are not build-system exclusions.
use lithe_plugin_language_servers::IndexingExclusions;
use serde_json::{json, Value};

/// Overlay the current policy without mutating the user's stored configuration.
/// Removing exclusions therefore restores the original settings exactly.
pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value>) -> Option<Value> {
if !matches!(provider, "rust" | "go") {
/// Removing exclusions therefore restores the original settings exactly. A
/// server that declares no `indexingExclusions` sees its configuration
/// unchanged; Core never guesses the setting from the server or language.
pub(crate) fn configuration(
exclusions: Option<&IndexingExclusions>,
root_uri: &str,
base: Option<&Value>,
) -> Option<Value> {
let Some(exclusions) = exclusions else {
return base.cloned();
}
};
let Some(root) = url::Url::parse(root_uri)
.ok()
.and_then(|uri| uri.to_file_path().ok())
Expand All @@ -18,48 +26,25 @@ pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value>
return base.cloned();
}
Some(with_roots(
provider,
exclusions,
base,
&lithe_project::indexing::excluded_roots(&root),
))
}

fn with_roots(provider: &str, base: Option<&Value>, roots: &[String]) -> Value {
fn with_roots(exclusions: &IndexingExclusions, base: Option<&Value>, roots: &[String]) -> Value {
let mut configuration = base.cloned().unwrap_or_else(|| json!({}));
match provider {
// rust-analyzer.files.exclude takes literal workspace-relative paths, not globs.
// https://rust-analyzer.github.io/book/configuration#rust-analyzerfilesexclude
"rust" => append_array(
&mut configuration,
&["rust-analyzer", "files", "exclude"],
roots.to_vec(),
&[],
),
// https://go.dev/gopls/settings#directoryFilters: ordered filters, last match wins.
// Preserve its documented default when the user did not configure this array.
"go" => append_array(
&mut configuration,
&["gopls", "directoryFilters"],
roots
.iter()
.filter(|path| !path.contains(['*', '?', '[', ']', '{', '}']))
.map(|path| {
if path == "." {
"-".into()
} else {
format!("-{path}")
}
})
.collect(),
&["-**/node_modules"],
),
_ => {}
}
append_array(
&mut configuration,
&exclusions.section_keys(),
exclusions.entries(roots),
exclusions.default_entries(),
);
configuration
}

/// Normalize owned dotted prefixes, so a request for the provider section sees them too.
fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaults: &[&str]) {
fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaults: &[String]) {
for length in 2..=path.len() {
let dotted = path[..length].join(".");
let previous = value
Expand All @@ -80,8 +65,9 @@ fn append_array(value: &mut Value, path: &[&str], additions: Vec<String>, defaul
if let Some(array) = slot.as_array_mut() {
for addition in additions {
let value = Value::String(addition);
// Go filters are ordered: an existing exclusion before a later inclusion
// must move to the end rather than being treated as a harmless duplicate.
// Filters may be ordered with the last match winning: an existing
// exclusion before a later inclusion must move to the end rather
// than being treated as a harmless duplicate.
array.retain(|item| item != &value);
array.push(value);
}
Expand Down Expand Up @@ -124,7 +110,7 @@ mod tests {
"rust-analyzer.files.exclude":["leaf"]
});
let original = base.clone();
let configured = with_roots("rust", Some(&base), &["vendor".into()]);
let configured = with_roots(&literal(), Some(&base), &["vendor".into()]);
assert_eq!(
configured["rust-analyzer"]["files"],
json!({
Expand All @@ -143,7 +129,11 @@ mod tests {
#[test]
fn native_exclusions_preserve_settings_and_restore_them_on_undo() {
let base = json!({"rust-analyzer":{"files":{"exclude":["existing"]},"cargo":{"allFeatures":true}}});
let excluded = with_roots("rust", Some(&base), &["vendor".into(), "带 空格".into()]);
let excluded = with_roots(
&literal(),
Some(&base),
&["vendor".into(), "带 空格".into()],
);
assert_eq!(
excluded["rust-analyzer"]["files"]["exclude"],
json!(["existing", "vendor", "带 空格"])
Expand All @@ -152,34 +142,56 @@ mod tests {
excluded["rust-analyzer"]["cargo"],
base["rust-analyzer"]["cargo"]
);
assert_eq!(with_roots("rust", Some(&base), &[]), base);
assert_eq!(with_roots(&literal(), Some(&base), &[]), base);
let go = json!({"gopls.directoryFilters":["+vendor","-cache"]});
assert_eq!(
with_roots("go", Some(&go), &["vendor".into()])["gopls"]["directoryFilters"],
with_roots(&glob(), Some(&go), &["vendor".into()])["gopls"]["directoryFilters"],
json!(["+vendor", "-cache", "-vendor"])
);
assert_eq!(
with_roots(
"go",
&glob(),
Some(&json!({"gopls":{"directoryFilters":["-vendor","+vendor"]}})),
&["vendor".into()]
)["gopls"]["directoryFilters"],
json!(["+vendor", "-vendor"])
);
assert_eq!(
with_roots("go", None, &["vendor".into()])["gopls"]["directoryFilters"],
json!(["-**/node_modules", "-vendor"])
with_roots(&glob(), None, &[".".into(), "vendor".into()])["gopls"]["directoryFilters"],
json!(["-**/node_modules", "-", "-vendor"])
);
}
#[test]
fn native_patterns_do_not_accidentally_exclude_literal_metacharacter_siblings() {
assert_eq!(
with_roots("go", None, &["literal*".into()])["gopls"]["directoryFilters"],
with_roots(&glob(), None, &["literal*".into()])["gopls"]["directoryFilters"],
json!(["-**/node_modules"])
);
assert_eq!(
with_roots("rust", None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"],
with_roots(&literal(), None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"],
json!(["literal*"])
);
}

/// A server whose setting takes literal paths, as rust-analyzer's
/// `files.exclude` does.
fn literal() -> IndexingExclusions {
serde_json::from_value(
json!({"section": "rust-analyzer.files.exclude", "entry": "${path}"}),
)
.unwrap()
}

/// A server whose setting takes ordered glob filters with a default, as
/// gopls's `directoryFilters` does.
fn glob() -> IndexingExclusions {
serde_json::from_value(json!({
"section": "gopls.directoryFilters",
"entry": "-${path}",
"rootEntry": "-",
"default": ["-**/node_modules"],
"pathSyntax": "glob"
}))
.unwrap()
}
}
4 changes: 4 additions & 0 deletions rust/crates/lsp-engine/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ pub(crate) struct RuntimeSession {
/// Replaced as a whole by `lsp.updateWorkspaceConfiguration`; never held
/// across another lock.
pub(crate) plugin_configuration: Mutex<Option<Arc<Value>>>,
/// The setting of `plugin_configuration` that lists the workspace's
/// excluded directories, as the session policy declares it. Without one
/// the configuration is answered unchanged.
pub(crate) indexing_exclusions: Option<lithe_plugin_language_servers::IndexingExclusions>,
/// Workspace URI the server was initialized with; scopes indexing
/// exclusions and other workspace-wide checks to this session's root.
pub(crate) root_uri: String,
Expand Down
56 changes: 39 additions & 17 deletions rust/crates/lsp-engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1759,31 +1759,53 @@ fn indexing_cold_start_resolves_git_before_provider_initialization() {
let status = lithe_project::indexing::configure(serde_json::from_value(json!({
"root": root, "manualExcludedDirectories": [], "includedDirectories": [], "gitIgnoreEnabled": true
})).unwrap(), crate::indexing_changed).unwrap();
let harness = Harness::start(|request| {
workspace.configure(request);
request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string();
});
assert!(notifications(&harness, "initialize").pop().is_some());
for (provider, pointer) in [
("go", "/gopls/directoryFilters"),
("rust", "/rust-analyzer/files/exclude"),
let start = |exclusions: Option<Value>| {
Harness::start(|request| {
workspace.configure(request);
request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string();
request.plugin_id = Some("io.example.server".into());
request.workspace_configuration = Some(json!({"server": {"mode": "full"}}));
request.session_policy = Some(
serde_json::from_value(
json!({"serverID": "server", "indexingExclusions": exclusions}),
)
.unwrap(),
);
})
};
// The server's declaration alone decides where the exclusions go and how
// one is written; its provider ID plays no part.
for (declaration, pointer, entry) in [
(
json!({"section": "server.filters", "entry": "-${path}", "pathSyntax": "glob"}),
"/server/filters",
"-ignored",
),
(
json!({"section": "server.files.exclude", "entry": "${path}"}),
"/server/files/exclude",
"ignored",
),
] {
let value =
crate::scan_settings::configuration(provider, &harness.session().root_uri, None)
.unwrap();
let harness = start(Some(declaration));
assert!(notifications(&harness, "initialize").pop().is_some());
let value = harness.session().plugin_configuration().unwrap();
assert_eq!(value["server"]["mode"], "full");
assert!(value
.pointer(pointer)
.unwrap()
.as_array()
.unwrap()
.iter()
.any(|item| item
== if provider == "go" {
"-ignored"
} else {
"ignored"
}));
.any(|item| item == entry));
}
let undeclared = start(None);
assert_eq!(
*undeclared.session().plugin_configuration().unwrap(),
json!({"server": {"mode": "full"}}),
"a server without indexingExclusions keeps its configuration"
);
drop(undeclared);
lithe_project::indexing::release(lithe_project::indexing::ReleaseIndexingRequest {
root: root.to_string_lossy().into_owned(),
revision: status.revision,
Expand Down
Loading
Loading