Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 37735eab14 fix(app): Load the splash CSS from a file so release editors keep their styles
Release builds hash inline <style> blocks from index.html into the CSP.
With a hash present, style-src 'unsafe-inline' is ignored, so CodeMirror's
runtime-injected styles were blocked and the editor rendered blank (bare
line numbers, no text). Dev builds don't rewrite the CSP, so it only
showed in v0.1.3 release bundles.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-23 18:37:47 +08:00
1083 змінених файлів з 8991 додано та 151875 видалено

No files matched your search

Створено
+26 -110
Переглянути файл
@@ -3960,27 +3960,9 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.16"
dependencies = [
"ide-core",
"ide-jsonrpc",
"ide-vcs",
"parking_lot",
"serde",
"serde_json",
"specta",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"tracing",
"uuid",
]
[[package]]
name = "ide-analysis"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3994,7 +3976,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4007,13 +3989,9 @@ dependencies = [
"tracing",
]
[[package]]
name = "ide-clipboard"
version = "0.1.16"
[[package]]
name = "ide-core"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dunce",
"serde",
@@ -4025,7 +4003,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-run",
@@ -4039,7 +4017,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4056,7 +4034,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4076,21 +4054,20 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"libc",
"serde",
"serde_json",
"specta",
"tempfile",
"tracing",
"which",
]
[[package]]
name = "ide-github"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4104,7 +4081,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"parking_lot",
@@ -4122,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"blake3",
"criterion",
@@ -4144,7 +4121,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"futures",
"ide-core",
@@ -4159,7 +4136,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"blake3",
"criterion",
@@ -4180,7 +4157,6 @@ dependencies = [
"tree-sitter-css",
"tree-sitter-dart",
"tree-sitter-elixir",
"tree-sitter-gdscript",
"tree-sitter-go",
"tree-sitter-graphql",
"tree-sitter-haskell",
@@ -4212,7 +4188,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"futures",
"globset",
@@ -4235,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-language",
@@ -4253,7 +4229,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-run",
@@ -4266,13 +4242,12 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"encoding_rs",
"ide-core",
"libc",
"parking_lot",
"portable-pty",
"serde",
"serde_json",
"specta",
@@ -4281,19 +4256,16 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"zip 2.4.2",
]
[[package]]
name = "ide-sdk"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dunce",
"ide-core",
"ide-language",
"ide-run",
"ide-vfs",
"ignore",
"serde",
"serde_json",
"specta",
@@ -4305,7 +4277,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"criterion",
"globset",
@@ -4313,7 +4285,6 @@ dependencies = [
"grep-regex",
"grep-searcher",
"ide-core",
"ide-vfs",
"ignore",
"insta",
"memchr",
@@ -4323,22 +4294,9 @@ dependencies = [
"tracing",
]
[[package]]
name = "ide-spell"
version = "0.1.16"
dependencies = [
"ide-core",
"parking_lot",
"serde",
"serde_json",
"specta",
"spellbook",
"tracing",
]
[[package]]
name = "ide-syntax"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"ide-language",
@@ -4353,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"ide-core",
"libc",
@@ -4366,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"criterion",
"ide-core",
@@ -4378,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"flate2",
"hex",
@@ -4398,7 +4356,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dunce",
"gix",
@@ -4415,7 +4373,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"chardetng",
"dunce",
@@ -4431,28 +4389,11 @@ dependencies = [
"tempfile",
"tracing",
"trash",
"zip 2.4.2",
]
[[package]]
name = "ide-web"
version = "0.1.16"
dependencies = [
"ide-core",
"open",
"parking_lot",
"percent-encoding",
"serde",
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-workspace"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"blake3",
"dunce",
@@ -4469,7 +4410,6 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"zip 2.4.2",
]
[[package]]
@@ -5877,14 +5817,12 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.16"
version = "0.1.3"
dependencies = [
"dirs 6.0.0",
"dunce",
"ide-agent",
"ide-analysis",
"ide-build",
"ide-clipboard",
"ide-core",
"ide-coverage",
"ide-dap",
@@ -5900,14 +5838,12 @@ dependencies = [
"ide-run",
"ide-sdk",
"ide-search",
"ide-spell",
"ide-syntax",
"ide-terminal",
"ide-text",
"ide-tools",
"ide-vcs",
"ide-vfs",
"ide-web",
"ide-workspace",
"parking_lot",
"serde",
@@ -7766,16 +7702,6 @@ dependencies = [
"specta",
]
[[package]]
name = "spellbook"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d204abcbdf8e88729306a8d0ca01a79d8a49969fe1f84696909d6dbc4321c1a"
dependencies = [
"foldhash",
"hashbrown 0.17.1",
]
[[package]]
name = "spin"
version = "0.9.9"
@@ -9296,16 +9222,6 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-gdscript"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7a37fe8c0a10c0c39ecd5b2f7db53933f691488f5572409a4d3c0dfeb3f6108"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-go"
version = "0.25.0"
+1 -5
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.16"
version = "0.1.3"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -32,10 +32,6 @@ ide-coverage = { path = "crates/ide-coverage" }
ide-profiler = { path = "crates/ide-profiler" }
ide-http = { path = "crates/ide-http" }
ide-db = { path = "crates/ide-db" }
ide-web = { path = "crates/ide-web" }
ide-spell = { path = "crates/ide-spell" }
ide-agent = { path = "crates/ide-agent" }
ide-clipboard = { path = "crates/ide-clipboard" }
# serialization & IPC typing
serde = { version = "1", features = ["derive"] }
+1 -9
Переглянути файл
@@ -9,21 +9,13 @@
The IDE you know, rebuilt in Rust.
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
&nbsp;·&nbsp;
<a href="#benchmark">Benchmark</a>
&nbsp;·&nbsp;
<a href="#build">Build</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool windows,
its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages. Builds for macOS, Windows and Linux.
for 60+ languages.
## Benchmark
-9
Переглянути файл
@@ -79,15 +79,6 @@ user's app-data directory only when the user asks; none of them ships with OpenI
unmodified, and its source is available from the repository above.
- **Eclipse JDT Language Server** (jdtls): EPL-2.0, from download.eclipse.org.
## en_US Hunspell dictionary
`crates/ide-spell/src/dict/en_US.{aff,dic}` (the spell checker's bundled dictionary) is the
SCOWL-derived en_US Hunspell dictionary (version 2020.12.07, from the `dictionary-en` npm
package 4.0.0), copied unmodified. Copyright Kevin Atkinson and the SCOWL / Hunspell
dictionary contributors; MIT- and BSD-style licences, full text in
`crates/ide-spell/src/dict/LICENSE-en_US`. It is checked with the
[spellbook](https://github.com/helix-editor/spellbook) crate (MPL-2.0).
## nvim-treesitter queries
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
-22
Переглянути файл
@@ -1,22 +0,0 @@
[package]
name = "ide-agent"
description = "Coding agents over the Agent Client Protocol: tasks, sessions, worktrees and their timelines"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
ide-jsonrpc.workspace = true
ide-vcs.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tokio.workspace = true
toml.workspace = true
tracing.workspace = true
parking_lot.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
-224
Переглянути файл
@@ -1,224 +0,0 @@
//! Session settings (model, mode, thinking effort…), slash commands and context use, as
//! the agent reports them over ACP.
use crate::model::{AgentCommand, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentUsage};
use serde_json::{Value, json};
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
/// plus the older `modes` / `models` fields for what those don't cover.
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
let mut out = result.get("configOptions").map(parse_options).unwrap_or_default();
let has = |out: &[AgentConfigOption], category: &str| out.iter().any(|o| o.category.as_deref() == Some(category));
if !has(&out, "mode")
&& let Some(modes) = result.get("modes")
{
out.push(legacy(modes, "mode", "Mode", "availableModes", "id", "currentModeId", AgentConfigVia::Mode));
}
if !has(&out, "model")
&& let Some(models) = result.get("models")
{
out.push(legacy(
models,
"model",
"Model",
"availableModels",
"modelId",
"currentModelId",
AgentConfigVia::Model,
));
}
out.retain(|o| !o.values.is_empty());
out
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
let Some(list) = options.as_array() else { return Vec::new() };
list.iter()
.filter(|o| o.get("type").and_then(Value::as_str).is_none_or(|t| t == "select"))
.filter_map(|o| {
let id = o.get("id").or_else(|| o.get("configId")).and_then(Value::as_str)?.to_owned();
let mut values = Vec::new();
for v in o.get("options").and_then(Value::as_array).into_iter().flatten() {
// Grouped options: `{ group, name, options: [...] }`.
match v.get("options").and_then(Value::as_array) {
Some(group) => values.extend(group.iter().filter_map(value_of)),
None => values.extend(value_of(v)),
}
}
Some(AgentConfigOption {
name: str_of(o, "name").unwrap_or_else(|| id.clone()),
description: str_of(o, "description"),
category: str_of(o, "category").or_else(|| matches!(id.as_str(), "model" | "mode").then(|| id.clone())),
current: str_of(o, "currentValue"),
values,
via: AgentConfigVia::Option,
id,
})
})
.collect()
}
/// A `config_option_update`: its options replace the config-option ones; `modes` / `models`
/// stand-ins stay.
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let fresh = parse_options(options);
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.via != AgentConfigVia::Option && !covered(o));
let legacy = std::mem::take(config);
config.extend(fresh);
config.extend(legacy);
config.retain(|o| !o.values.is_empty());
}
/// `current_mode_update`.
pub(crate) fn set_mode(config: &mut [AgentConfigOption], mode: &str) {
if let Some(o) = config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
o.current = Some(mode.to_owned());
}
}
/// The request (method, params without the session id) that sets `option` to `value`.
pub(crate) fn set_request(option: &AgentConfigOption, value: &str) -> (&'static str, Value) {
match option.via {
AgentConfigVia::Option => ("session/set_config_option", json!({ "configId": option.id, "value": value })),
AgentConfigVia::Mode => ("session/set_mode", json!({ "modeId": value })),
AgentConfigVia::Model => ("session/set_model", json!({ "modelId": value })),
}
}
/// `available_commands_update`.
pub(crate) fn commands_of(update: &Value) -> Vec<AgentCommand> {
update
.get("availableCommands")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|c| {
Some(AgentCommand {
name: c.get("name")?.as_str()?.trim_start_matches('/').to_owned(),
description: str_of(c, "description").unwrap_or_default(),
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
})
})
.collect()
}
/// `usage_update`: `{ used, size, cost?: { amount, currency } }`.
pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
let tokens = |key: &str| update.get(key)?.as_f64().map(|n| n.clamp(0.0, f64::from(u32::MAX)) as u32);
let used = tokens("used")?;
let size = tokens("size").filter(|s| *s > 0)?;
Some(AgentUsage {
used,
size,
cost: update.pointer("/cost/amount").and_then(Value::as_f64),
currency: update.pointer("/cost/currency").and_then(Value::as_str).map(str::to_owned),
})
}
fn legacy(
v: &Value,
id: &str,
name: &str,
list: &str,
key: &str,
current: &str,
via: AgentConfigVia,
) -> AgentConfigOption {
let values = v
.get(list)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|m| {
let value = m.get(key)?.as_str()?.to_owned();
Some(AgentConfigValue {
name: str_of(m, "name").unwrap_or_else(|| value.clone()),
description: str_of(m, "description"),
value,
})
})
.collect();
AgentConfigOption {
id: id.to_owned(),
name: name.to_owned(),
description: None,
category: Some(id.to_owned()),
current: str_of(v, current),
values,
via,
}
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
value,
})
}
fn str_of(v: &Value, key: &str) -> Option<String> {
v.get(key).and_then(Value::as_str).map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(c: &[AgentConfigOption]) -> Vec<(&str, Option<&str>)> {
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
}
#[test]
fn config_options_win_over_the_older_fields() {
let r = json!({
"modes": {"currentModeId": "default", "availableModes": [{"id": "default", "name": "Manual"}]},
"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "plan",
"options": [{"value": "default", "name": "Manual"}, {"value": "plan", "name": "Plan"}]},
{"id": "effort", "category": "thought_level", "type": "select", "currentValue": "medium",
"options": [{"group": "g", "name": "G", "options": [{"value": "low"}, {"value": "medium", "name": "Medium"}]}]},
{"id": "fast", "type": "boolean", "currentValue": false}
],
"models": {"currentModelId": "m1", "availableModels": [{"modelId": "m1", "name": "One"}]}
});
let c = options_of(&r);
assert_eq!(ids(&c), [("mode", Some("plan")), ("effort", Some("medium")), ("model", Some("m1"))]);
assert_eq!(c[1].values.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["low", "Medium"]);
assert_eq!(set_request(&c[0], "default").0, "session/set_config_option");
assert_eq!(set_request(&c[2], "m1"), ("session/set_model", json!({"modelId": "m1"})));
}
#[test]
fn updates_replace_options_and_track_the_mode() {
let mut c = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask"}, {"id": "code"}]},
"configOptions": [{"id": "model", "type": "select", "currentValue": "a", "options": [{"value": "a"}]}]
}));
assert_eq!(c[0].category.as_deref(), Some("model"), "the category defaults from the id");
set_mode(&mut c, "code");
assert_eq!(c[1].current.as_deref(), Some("code"));
assert_eq!(set_request(&c[1], "ask").0, "session/set_mode");
merge_update(
&mut c,
&json!([{"id": "model", "type": "select", "currentValue": "b", "options": [{"value": "b"}]}]),
);
assert_eq!(ids(&c), [("model", Some("b")), ("mode", Some("code"))]);
}
#[test]
fn commands_and_usage() {
let cmds = commands_of(&json!({"availableCommands": [
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
]}));
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
assert_eq!((u.used, u.cost, u.currency.as_deref()), (1200, Some(0.42), Some("USD")));
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
}
}
File diff suppressed because it is too large. Load diff
-285
Переглянути файл
@@ -1,285 +0,0 @@
//! IPC types: tasks, their timeline entries and the events streamed to the UI.
use ide_core::IpcPath;
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentStatus {
/// Creating the worktree / starting the agent.
Starting,
Running,
/// Waiting for a permission answer.
NeedsInput,
/// The turn ended; the result can be reviewed or the conversation continued.
Ready,
Failed,
Archived,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Isolation {
/// A new git worktree on its own branch.
Worktree,
/// The project's own checkout.
Local,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentTask {
pub id: String,
pub title: String,
/// [`AgentProvider::id`].
pub provider: String,
/// Model the task runs on (its `model` setting), when known.
pub model: Option<String>,
pub status: AgentStatus,
pub isolation: Isolation,
/// Directory the agent works in (the worktree, or the project root).
pub cwd: IpcPath,
/// Branch of the task's worktree.
pub branch: Option<String>,
/// Branch (or revision) the worktree was created from.
pub base: Option<String>,
/// Commit the task's changes are compared against.
pub base_commit: Option<String>,
/// Why the task failed, when it did.
pub error: Option<String>,
pub created_ms: f64,
pub updated_ms: f64,
/// The session's settings (model, mode, thinking effort…) as last reported, with the
/// user's choices applied.
pub config: Vec<AgentConfigOption>,
/// Slash commands the agent offers.
pub commands: Vec<AgentCommand>,
/// Context window use, when the agent reports it.
pub usage: Option<AgentUsage>,
/// Messages waiting for the current turn to end, oldest first.
pub queue: Vec<AgentQueued>,
}
/// One value of a select-type session setting.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigValue {
pub value: String,
pub name: String,
pub description: Option<String>,
}
/// How a setting is changed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentConfigVia {
/// `session/set_config_option`.
#[default]
Option,
/// `session/set_mode` (agents that report `modes` instead of a mode config option).
Mode,
/// `session/set_model` (agents that report `models` instead of a model config option).
Model,
}
/// A session setting: an ACP select config option, or the older `modes` / `models`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigOption {
pub id: String,
pub name: String,
pub description: Option<String>,
/// ACP category: `model`, `mode`, `thought_level`, or agent-specific.
pub category: Option<String>,
pub current: Option<String>,
pub values: Vec<AgentConfigValue>,
pub via: AgentConfigVia,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
/// Without the leading `/`.
pub name: String,
pub description: String,
/// What to type after the command, when it takes input.
pub hint: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentUsage {
/// Tokens in the context window.
pub used: u32,
/// Size of the context window.
pub size: u32,
/// Session cost so far.
pub cost: Option<f64>,
pub currency: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentImage {
pub mime_type: String,
/// Base64, without a `data:` prefix.
pub data: String,
pub name: Option<String>,
}
/// A message to the agent: text, plus files to look at and images.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPrompt {
pub text: String,
pub files: Vec<IpcPath>,
pub images: Vec<AgentImage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentConfigChoice {
pub id: String,
pub value: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentToolStatus {
Pending,
Running,
Completed,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentToolDiff {
pub path: IpcPath,
pub added: u32,
pub removed: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlanItem {
pub content: String,
/// `pending`, `in_progress` or `completed`.
pub status: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPermissionOption {
pub id: String,
pub name: String,
/// `allow_once`, `allow_always`, `reject_once` or `reject_always`.
pub kind: String,
}
/// One item of a task's conversation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEntry {
User {
text: String,
/// Names of the files and images sent with it.
attachments: Vec<String>,
},
Agent {
text: String,
},
Thought {
text: String,
},
Tool {
id: String,
title: String,
/// ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`…
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
},
Plan {
items: Vec<AgentPlanItem>,
},
Permission {
id: u32,
title: String,
options: Vec<AgentPermissionOption>,
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
chosen: Option<String>,
},
Error {
message: String,
},
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentProvider {
pub id: String,
pub name: String,
/// The command line that starts its ACP server.
pub command: String,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
pub config: Vec<AgentConfigOption>,
/// Slash commands it offered last time.
pub commands: Vec<AgentCommand>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NewAgentTask {
pub prompt: AgentPrompt,
pub provider: String,
/// Settings for the new session (model, mode…).
pub config: Vec<AgentConfigChoice>,
pub isolation: Isolation,
/// Branch to start the worktree from; the current branch when `None`.
pub base: Option<String>,
}
/// A file the task changed, relative to [`AgentTask::base_commit`].
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentChange {
pub path: IpcPath,
pub rel_path: String,
pub kind: ide_vcs::ChangeKind,
pub added: u32,
pub removed: u32,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
Task {
task: AgentTask,
},
Removed {
id: String,
},
/// Entry `index` of `task` was added or replaced.
Entry {
task: String,
index: u32,
entry: AgentEntry,
},
}
-158
Переглянути файл
@@ -1,158 +0,0 @@
//! Agents and how to launch their ACP servers: the built-in ones, plus user-defined
//! agents from `<config>/agents/<id>.toml`.
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ProviderSpec {
pub id: String,
pub name: String,
pub command: String,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
/// How to sign in when the agent reports it needs authentication.
pub login_hint: String,
}
/// `(id, name, command line, sign-in hint)`. npm adapters are pinned so a session's
/// protocol does not change under the user.
const BUILTIN: &[(&str, &str, &[&str], &str)] = &[
(
"claude",
"Claude Code",
&["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `claude` in a terminal and sign in.",
),
("codex", "Codex", &["npx", "-y", "@agentclientprotocol/[email protected]"], "Run `codex login` in a terminal."),
("gemini", "Gemini CLI", &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
("copilot", "GitHub Copilot", &["copilot", "--acp"], "Run `copilot` in a terminal and sign in."),
("cursor", "Cursor", &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
("qwen", "Qwen Code", &["qwen", "--experimental-acp"], "Run `qwen` in a terminal and sign in."),
("kimi", "Kimi CLI", &["kimi", "acp"], "Run `kimi` in a terminal and sign in."),
("goose", "Goose", &["goose", "acp"], "Run `goose configure` in a terminal."),
("auggie", "Auggie", &["auggie", "--acp"], "Run `auggie login` in a terminal."),
("kiro", "Kiro", &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
("vibe", "Mistral Vibe", &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
];
fn builtins() -> Vec<ProviderSpec> {
BUILTIN
.iter()
.map(|(id, name, cmd, hint)| ProviderSpec {
id: (*id).into(),
name: (*name).into(),
command: cmd[0].into(),
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
env: Vec::new(),
login_hint: (*hint).into(),
})
.collect()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CustomAgent {
name: Option<String>,
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: HashMap<String, String>,
}
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
/// built-in id replaces it.
pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
let mut specs = builtins();
let mut files: Vec<PathBuf> = custom_dir
.and_then(|d| std::fs::read_dir(d).ok())
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
.collect();
files.sort();
for path in files {
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
let parsed = std::fs::read_to_string(&path)
.map_err(|e| e.to_string())
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()));
let agent = match parsed {
Ok(a) => a,
Err(e) => {
tracing::warn!("skipping agent {}: {e}", path.display());
continue;
}
};
let mut env: Vec<(String, String)> = agent.env.into_iter().collect();
env.sort();
let spec = ProviderSpec {
name: agent.name.unwrap_or_else(|| id.clone()),
command: agent.command,
args: agent.args,
env,
login_hint: "Sign in with the agent's own command line first.".into(),
id,
};
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => *existing = spec,
None => specs.push(spec),
}
}
specs
}
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
pub(crate) fn installed(command: &str) -> bool {
let p = Path::new(command);
if p.components().count() > 1 {
return is_executable(p);
}
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
}
fn is_executable(p: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
p.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
p.is_file()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn custom_agents_extend_and_override_the_builtins() {
let dir = tempfile::tempdir().unwrap();
let write = |name: &str, text: &str| std::fs::write(dir.path().join(name), text).unwrap();
write("mine.toml", "name = \"Mine\"\ncommand = \"/opt/mine\"\nargs = [\"acp\"]\n[env]\nK = \"v\"\n");
write("gemini.toml", "command = \"gemini\"\nargs = [\"--acp\"]\n");
write("broken.toml", "nope = 1\n");
let specs = load(Some(dir.path()));
let mine = specs.iter().find(|s| s.id == "mine").unwrap();
assert_eq!((mine.name.as_str(), mine.command.as_str()), ("Mine", "/opt/mine"));
assert_eq!(mine.env, vec![("K".to_owned(), "v".to_owned())]);
let gemini = specs.iter().find(|s| s.id == "gemini").unwrap();
assert_eq!((gemini.name.as_str(), gemini.args.as_slice()), ("gemini", &["--acp".to_owned()][..]));
assert!(!specs.iter().any(|s| s.id == "broken"));
assert_eq!(specs.iter().filter(|s| s.id == "claude").count(), 1);
assert!(!installed("/definitely/not/here"));
assert!(installed("sh"));
}
}
-423
Переглянути файл
@@ -1,423 +0,0 @@
//! End-to-end task flow against an in-memory ACP agent.
use super::*;
use std::sync::OnceLock;
use tokio::io::duplex;
/// Says "Hi", edits a file, asks to run a command and reports what it was allowed.
#[derive(Default)]
struct FakeAgent {
peer: OnceLock<Peer>,
calls: Mutex<Vec<String>>,
}
impl FakeAgent {
fn update(&self, session: &str, update: Value) {
let peer = self.peer.get().unwrap();
peer.notify("session/update", json!({ "sessionId": session, "update": update })).unwrap();
}
fn say(&self, session: &str, text: &str) {
self.update(
session,
json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}),
);
}
}
impl Handler for FakeAgent {
fn on_notification(&self, method: &str, _: Value) {
self.calls.lock().push(method.to_owned());
}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push(method.to_owned());
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
"initialize" => Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}})),
"session/new" => Ok(json!({"sessionId": "s1",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]}]})),
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
}
"session/set_config_option" | "session/set_mode" => {
self.calls.lock().push(format!("{method} {}", params.get("value").or(params.get("modeId")).unwrap()));
Ok(json!({}))
}
"session/prompt" => {
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
if text == "again" {
self.say(&session, "second turn");
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "wait" {
// Works until cancelled.
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
std::thread::sleep(Duration::from_millis(5));
}
return Ok(json!({"stopReason": "cancelled"}));
}
self.update(
&session,
json!({"sessionUpdate": "available_commands_update",
"availableCommands": [{"name": "review", "description": "Review", "input": {"hint": "focus"}}]}),
);
self.update(&session, json!({"sessionUpdate": "usage_update", "used": 50, "size": 1000}));
self.say(&session, "Hi");
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Edit a.rs",
"kind": "edit", "status": "completed",
"content": [{"type": "diff", "path": "/p/a.rs", "oldText": "a\n", "newText": "b\n"}]}),
);
let peer = self.peer.get().unwrap().clone();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"session/request_permission",
json!({"sessionId": session, "toolCall": {"toolCallId": "t1", "title": "Run cargo test"},
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
{"optionId": "no", "name": "Reject", "kind": "reject_once"}]}),
None,
))
.unwrap();
let chosen = answer.pointer("/outcome/optionId").and_then(Value::as_str).unwrap_or("none");
self.say(&session, &format!("chose {chosen}"));
Ok(json!({"stopReason": "end_turn"}))
}
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
let connector: Connector = Arc::new(move |_spec, _cwd, client, _stderr| {
let (a, b) = duplex(1 << 20);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let server = Peer::connect_framed(br, bw, agent.clone(), Framing::Lines);
// Keep the latest connection: a restarted manager connects again.
let _ = agent.peer.set(server);
Ok(Peer::connect_framed(ar, aw, client, Framing::Lines))
});
AgentManager::with_connector(
AgentPaths {
project_root: dir.to_path_buf(),
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
custom_agents_dir: None,
},
tokio::runtime::Handle::current(),
connector,
)
}
async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
for _ in 0..500 {
if mgr.task(id).unwrap().state.lock().task.status == status {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("task never reached {status:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
prompt: text("Fix the lexer\nmore detail"),
provider: "claude".into(),
config: vec![AgentConfigChoice { id: "model".into(), value: "small".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
assert_eq!(task.title, "Fix the lexer");
assert_ne!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready, "a new task is not settled");
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let permission = mgr
.entries(&task.id)
.unwrap()
.iter()
.find_map(|e| match e {
AgentEntry::Permission { id, .. } => Some(*id),
_ => None,
})
.unwrap();
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
let kinds: Vec<String> = entries
.iter()
.map(|e| match e {
AgentEntry::User { text, .. } | AgentEntry::Agent { text } => text.clone(),
AgentEntry::Tool { title, .. } => title.clone(),
AgentEntry::Permission { chosen, .. } => format!("permission: {}", chosen.clone().unwrap_or_default()),
other => format!("{other:?}"),
})
.collect();
assert_eq!(kinds, ["Fix the lexer\nmore detail", "Hi", "Edit a.rs", "permission: Allow", "chose yes"]);
assert!(
agent.calls.lock().contains(&"session/set_config_option \"small\"".to_owned()),
"switched to the chosen model"
);
{
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
assert_eq!(t.model.as_deref(), Some("small"));
let modes = t.config.iter().find(|o| o.id == "mode").unwrap();
assert_eq!((modes.via, modes.current.as_deref()), (AgentConfigVia::Mode, Some("ask")));
assert_eq!(t.commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["review"]);
assert_eq!(t.usage.as_ref().map(|u| (u.used, u.size)), Some((50, 1000)));
}
mgr.set_config(&task.id, "mode", "code".into()).await.unwrap();
assert!(agent.calls.lock().contains(&"session/set_mode \"code\"".to_owned()));
assert!(mgr.set_config(&task.id, "mode", "nope".into()).await.is_err());
tokio::time::sleep(FLUSH_DELAY * 3).await;
{
let events = events.lock();
assert!(
events.iter().any(|e| matches!(e, AgentEvent::Task { task } if task.status == AgentStatus::NeedsInput))
);
let last_entry = events.iter().rev().find_map(|e| match e {
AgentEvent::Entry { index, entry, .. } => Some((*index, entry.clone())),
_ => None,
});
assert_eq!(last_entry, Some((4, AgentEntry::Agent { text: "chose yes".into() })));
}
let providers = mgr.providers();
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
assert_eq!(claude.commands.len(), 1);
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
mgr.shutdown();
let agent2 = Arc::new(FakeAgent::default());
let mgr2 = manager(tmp.path(), agent2.clone());
assert_eq!(mgr2.entries(&task.id).unwrap().len(), 5);
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id).unwrap();
assert_eq!(entries.len(), 7);
assert_eq!(entries[6], AgentEntry::Agent { text: "second turn".into() });
assert!(agent2.calls.lock().contains(&"session/load".to_owned()));
// The chosen settings are re-applied to the reloaded session.
let calls = agent2.calls.lock().clone();
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
mgr.prompt(&task.id, text("again"), false).await.unwrap();
let queue = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
assert_eq!(queue.iter().map(|q| q.prompt.text.as_str()).collect::<Vec<_>>(), ["again"]);
assert!(mgr.prompt(&task.id, text(" "), false).await.is_err());
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
for _ in 0..500 {
if mgr.entries(&task.id).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let users: Vec<String> = mgr
.entries(&task.id)
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEntry::User { text, .. } => Some(text),
_ => None,
})
.collect();
assert_eq!(users, ["wait", "again"]);
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
// Stopping a turn keeps the queue for later.
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
agent.calls.lock().retain(|c| c != "session/cancel");
mgr.prompt(&task.id, text("later"), false).await.unwrap();
mgr.cancel(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
assert_eq!(queued.len(), 1);
assert_eq!(mgr.unqueue(&task.id, &queued[0].id).unwrap().prompt.text, "later");
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
}
#[test]
fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
};
assert_eq!(
blocks(&p, &[]),
[
json!({"type": "text", "text": "look"}),
json!({"type": "resource_link", "uri": "file:///p/my%20file.rs", "name": "my file.rs"}),
json!({"type": "image", "mimeType": "image/png", "data": "AAA"}),
]
);
assert_eq!(
blocks(&p, &[Some("fn a() {}".into())])[1],
json!({"type": "resource", "resource": {"uri": "file:///p/my%20file.rs", "text": "fn a() {}"}})
);
let old = upgrade(
json!({"task": {"id": "t"}, "entries": [{"type": "user", "text": "hi"}, {"type": "agent", "text": "a"}]}),
);
assert_eq!(old["task"]["queue"], json!([]));
assert_eq!(old["entries"][0]["attachments"], json!([]));
assert!(old["entries"][1].get("attachments").is_none());
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
assert!(clean(text(" ")).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("do it"),
provider: "codex".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")));
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "chose none".into() }));
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.model.as_deref(), Some("big"), "the agent's default");
mgr.delete(&task.id, false).await.unwrap();
assert!(mgr.entries(&task.id).is_err());
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
assert!(
mgr.create(NewAgentTask {
prompt: text(" "),
provider: "codex".into(),
config: vec![],
isolation: Isolation::Local,
base: None
})
.await
.is_err()
);
}
/// Drives the real Claude Code adapter (needs `npx`, network and a signed-in `claude`):
/// `OPENIDEA_AGENT_E2E=1 cargo test -p ide-agent real_claude -- --ignored --nocapture`.
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn real_claude_task_in_a_worktree() {
if std::env::var_os("OPENIDEA_AGENT_E2E").is_none() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
for args in [&["init", "-q", "-b", "main"][..], &["commit", "-q", "--allow-empty", "-m", "init"]] {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(&repo)
.status()
.unwrap()
.success();
assert!(ok);
}
let mgr = AgentManager::new(
AgentPaths {
project_root: repo.clone(),
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("wt"),
models_file: tmp.path().join("models.json"),
custom_agents_dir: None,
},
tokio::runtime::Handle::current(),
);
let task = mgr
.create(NewAgentTask {
prompt: text("Create a file named hello.txt containing the single word hi. Do nothing else."),
provider: "claude".into(),
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
isolation: Isolation::Worktree,
base: None,
})
.await
.unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(240);
loop {
assert!(std::time::Instant::now() < deadline, "timed out");
let status = mgr.task(&task.id).unwrap().state.lock().task.status;
match status {
AgentStatus::NeedsInput => {
let pending = mgr.entries(&task.id).unwrap().into_iter().rev().find_map(|e| match e {
AgentEntry::Permission { id, options, chosen: None, .. } => Some((id, options)),
_ => None,
});
if let Some((id, options)) = pending {
let allow = options.iter().find(|o| o.kind == "allow_once").or(options.first()).unwrap();
eprintln!("allowing: {}", allow.name);
let _ = mgr.respond(&task.id, id, Some(allow.id.clone()));
}
}
AgentStatus::Ready | AgentStatus::Failed => break,
_ => {}
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
for e in mgr.entries(&task.id).unwrap() {
eprintln!("{e:?}");
}
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
assert_eq!(t.status, AgentStatus::Ready, "{:?}", t.error);
assert_eq!(t.model.as_deref(), Some("haiku"));
let changes = mgr.changes(&task.id).await.unwrap();
assert!(changes.iter().any(|c| c.rel_path == "hello.txt"), "{changes:?}");
assert!(!repo.join("hello.txt").exists(), "the project checkout is untouched");
assert!(!mgr.providers().iter().find(|p| p.id == "claude").unwrap().config.is_empty());
mgr.shutdown();
}
-304
Переглянути файл
@@ -1,304 +0,0 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
tools: HashMap<String, usize>,
plan: Option<usize>,
}
/// What a `session/update` changed in the timeline.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Applied {
/// Indices of the entries added or changed.
pub changed: Vec<usize>,
}
impl Timeline {
pub fn from_entries(entries: Vec<AgentEntry>) -> Self {
let mut t = Self { entries, ..Self::default() };
for (i, e) in t.entries.iter().enumerate() {
match e {
AgentEntry::Tool { id, .. } => {
t.tools.insert(id.clone(), i);
}
AgentEntry::Plan { .. } => t.plan = Some(i),
_ => {}
}
}
t
}
pub fn has_tool(&self, id: &str) -> bool {
self.tools.contains_key(id)
}
pub fn push(&mut self, entry: AgentEntry) -> usize {
self.entries.push(entry);
self.entries.len() - 1
}
/// Applies one `session/update` `update` object.
pub fn apply(&mut self, update: &Value) -> Applied {
let mut out = Applied::default();
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
match kind {
"agent_message_chunk" | "agent_thought_chunk" => {
let Some(text) = content_text(update.get("content")) else { return out };
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
}
"tool_call" => {
let id = str_field(update, "toolCallId");
let entry = AgentEntry::Tool {
id: id.clone(),
title: str_field(update, "title"),
kind: update.get("kind").and_then(Value::as_str).unwrap_or("other").to_owned(),
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
diffs: Vec::new(),
};
let index = match self.tools.get(&id) {
Some(&i) => {
self.entries[i] = entry;
i
}
None => {
let i = self.push(entry);
self.tools.insert(id, i);
i
}
};
self.merge_tool(index, update);
out.changed.push(index);
}
"tool_call_update" => {
let Some(&index) = self.tools.get(&str_field(update, "toolCallId")) else { return out };
self.merge_tool(index, update);
out.changed.push(index);
}
"plan" => {
let items = update
.get("entries")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|e| AgentPlanItem { content: str_field(e, "content"), status: str_field(e, "status") })
.collect()
})
.unwrap_or_default();
let entry = AgentEntry::Plan { items };
let index = match self.plan {
Some(i) => {
self.entries[i] = entry;
i
}
None => self.push(entry),
};
self.plan = Some(index);
out.changed.push(index);
}
_ => {}
}
out
}
fn append_text(&mut self, thought: bool, text: &str) -> usize {
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
}
}
self.entries.len() - 1
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
else {
return;
};
if let Some(t) = update.get("title").and_then(Value::as_str) {
*title = t.to_owned();
}
if let Some(k) = update.get("kind").and_then(Value::as_str) {
*kind = k.to_owned();
}
if let Some(s) = tool_status(update.get("status")) {
*status = s;
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("content")) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
if !text.is_empty() {
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
}
/// Settles what an ended turn left open: running tools and pending permissions.
pub fn end_turn(&mut self) -> Vec<usize> {
let mut changed = Vec::new();
for (i, e) in self.entries.iter_mut().enumerate() {
match e {
AgentEntry::Tool { status, .. }
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) =>
{
*status = AgentToolStatus::Failed;
changed.push(i);
}
AgentEntry::Permission { chosen, .. } if chosen.is_none() => {
*chosen = Some("Cancelled".into());
changed.push(i);
}
_ => {}
}
}
changed
}
}
fn str_field(v: &Value, key: &str) -> String {
v.get(key).and_then(Value::as_str).unwrap_or_default().to_owned()
}
fn content_text(content: Option<&Value>) -> Option<String> {
let c = content?;
match c.get("type").and_then(Value::as_str) {
Some("text") => c.get("text").and_then(Value::as_str).map(str::to_owned),
Some("resource_link") => c.get("uri").and_then(Value::as_str).map(str::to_owned),
Some("resource") => c.pointer("/resource/text").and_then(Value::as_str).map(str::to_owned),
_ => None,
}
}
fn tool_status(v: Option<&Value>) -> Option<AgentToolStatus> {
Some(match v?.as_str()? {
"pending" => AgentToolStatus::Pending,
"in_progress" => AgentToolStatus::Running,
"completed" => AgentToolStatus::Completed,
"failed" => AgentToolStatus::Failed,
_ => return None,
})
}
fn locations(v: Option<&Value>) -> Vec<IpcPath> {
v.and_then(Value::as_array)
.map(|a| a.iter().filter_map(|l| l.get("path")?.as_str()).map(|p| IpcPath(p.into())).collect())
.unwrap_or_default()
}
fn line_stats(old: &str, new: &str) -> (u32, u32) {
ide_vcs::diff_hunks(old, new).iter().fold((0, 0), |(a, r), h| (a + h.lines, r + h.old_lines))
}
fn tail(mut text: String) -> String {
if text.len() > MAX_OUTPUT {
let mut cut = text.len() - MAX_OUTPUT;
while !text.is_char_boundary(cut) {
cut += 1;
}
text.replace_range(..cut, "…");
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
let chunk = |s: &str| json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": s}});
assert_eq!(t.apply(&chunk("Hel")).changed, vec![0]);
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
t.apply(&chunk("again"));
assert_eq!(
t.entries,
vec![
AgentEntry::Agent { text: "Hello".into() },
AgentEntry::Thought { text: "hmm".into() },
AgentEntry::Agent { text: "again".into() },
]
);
}
#[test]
fn tool_calls_update_in_place() {
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Edit a.rs", "kind": "edit",
"status": "pending", "locations": [{"path": "/p/a.rs", "line": 3}]}));
let applied = t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed",
"content": [
{"type": "diff", "path": "/p/a.rs", "oldText": "a\nb\n", "newText": "a\nB\nc\n"},
{"type": "content", "content": {"type": "text", "text": "done"}}
]}));
assert_eq!(applied.changed, vec![0]);
let AgentEntry::Tool { status, diffs, output, locations, .. } = &t.entries[0] else { panic!() };
assert_eq!(*status, AgentToolStatus::Completed);
assert_eq!(diffs, &vec![AgentToolDiff { path: IpcPath("/p/a.rs".into()), added: 2, removed: 1 }]);
assert_eq!(output.as_deref(), Some("done"));
assert_eq!(locations, &vec![IpcPath("/p/a.rs".into())]);
// Unknown calls are ignored.
assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty());
}
#[test]
fn plan_is_one_entry_and_end_turn_settles_open_items() {
let mut t = Timeline::default();
let plan =
|s: &str| json!({"sessionUpdate": "plan", "entries": [{"content": "x", "priority": "high", "status": s}]});
t.apply(&plan("pending"));
t.push(AgentEntry::Agent { text: "between".into() });
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
t.push(AgentEntry::Permission { id: 1, title: "Run?".into(), options: vec![], chosen: None });
assert_eq!(t.end_turn(), vec![2, 3]);
let again = Timeline::from_entries(t.entries.clone());
assert_eq!(again.plan, Some(0));
assert_eq!(again.tools.get("c"), Some(&2));
}
#[test]
fn long_output_keeps_its_tail() {
let s = tail("é".repeat(MAX_OUTPUT));
assert!(s.starts_with('…') && s.len() <= MAX_OUTPUT + 3);
}
}
-156
Переглянути файл
@@ -1,156 +0,0 @@
//! Task worktrees and the changes made in them.
use crate::model::AgentChange;
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, Repo};
use std::path::{Path, PathBuf};
pub(crate) struct Created {
pub path: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
fn repo_at(path: &Path) -> IdeResult<Repo> {
Repo::discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
}
/// The current branch (or commit when detached) and its commit.
pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
let info = repo_at(path)?.branch_info()?;
let commit = info.head_commit.ok_or_else(|| IdeError::unavailable("the repository has no commits yet"))?;
Ok((info.head.unwrap_or_else(|| commit.clone()), commit))
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
repo.merge_base(b, b)?.ok_or_else(|| IdeError::not_found(format!("no branch or revision {b}")))?;
(b.to_owned(), commit)
}
None => head_of(project_root)?,
};
std::fs::create_dir_all(worktrees_dir).map_err(|e| IdeError::internal(e.to_string()))?;
let branch_exists = |s: &str| {
let r = format!("refs/heads/agent/{s}");
repo.merge_base(&r, &r).ok().flatten().is_some()
};
let slug = unique_slug(&slugify(title), |s| worktrees_dir.join(s).exists() || branch_exists(s));
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
}
pub(crate) fn remove(project_root: &Path, path: &Path) -> IdeResult<()> {
repo_at(project_root)?.remove_worktree(path, true)
}
/// Files under `cwd` that differ from `base` (untracked files included), with line counts.
pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
let repo = repo_at(cwd)?;
let root = repo.root().to_path_buf();
let stats = repo.numstat_with_worktree(base)?;
let stat = |rel: &str| stats.iter().find(|(p, ..)| p == rel).map_or((0, 0), |&(_, a, r)| (a, r));
let mut out: Vec<AgentChange> = repo
.diff_with_worktree(base)?
.into_iter()
.map(|f| {
let (added, removed) = stat(&f.path);
AgentChange { path: IpcPath(root.join(&f.path)), rel_path: f.path, kind: f.kind, added, removed }
})
.collect();
for s in repo.status()? {
if s.unstaged == Some(ChangeKind::Untracked) && !out.iter().any(|c| c.rel_path == s.rel_path) {
let added = std::fs::read_to_string(&*s.path).map_or(0, |t| t.lines().count() as u32);
out.push(AgentChange { path: s.path, rel_path: s.rel_path, kind: ChangeKind::Added, added, removed: 0 });
}
}
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
Ok(out)
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
repo_at(cwd)?.file_at(path, Some(rev))
}
/// A short ASCII branch-safe name from the task title.
pub(crate) fn slugify(title: &str) -> String {
let mut out = String::new();
for c in title.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
if out.len() >= 32 {
break;
}
}
let out = out.trim_matches('-');
if out.is_empty() { "task".to_owned() } else { out.to_owned() }
}
fn unique_slug(base: &str, taken: impl Fn(&str) -> bool) -> String {
if !taken(base) {
return base.to_owned();
}
(2..).map(|n| format!("{base}-{n}")).find(|s| !taken(s)).expect("unbounded")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs_are_branch_safe() {
assert_eq!(slugify("Fix lexer UTF-16 columns!"), "fix-lexer-utf-16-columns");
assert_eq!(slugify("修复 lexer 越界"), "lexer");
assert_eq!(slugify("修复越界"), "task");
assert_eq!(slugify(&"a".repeat(50)).len(), 32);
assert_eq!(unique_slug("x", |s| s == "x" || s == "x-2"), "x-3");
}
fn git(dir: &Path, args: &[&str]) {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(dir)
.status()
.unwrap()
.success();
assert!(ok, "git {args:?}");
}
#[test]
fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let created = create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap();
assert_eq!(created.branch, "agent/edit-a");
assert_eq!(created.base, "main");
std::fs::write(created.path.join("a.txt"), "one\nTWO\nthree\n").unwrap();
std::fs::write(created.path.join("new.txt"), "x\ny\n").unwrap();
let got = changes(&created.path, &created.base_commit).unwrap();
let summary: Vec<_> = got.iter().map(|c| (c.rel_path.as_str(), c.kind, c.added, c.removed)).collect();
assert_eq!(summary, [("a.txt", ChangeKind::Modified, 2, 1), ("new.txt", ChangeKind::Added, 2, 0)]);
let base_text = file_at(&created.path, &created.path.join("a.txt"), &created.base_commit).unwrap();
assert_eq!(base_text.as_deref(), Some("one\ntwo\n"));
// A second task with the same title gets its own worktree.
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
remove(&repo, &created.path).unwrap();
assert!(!created.path.exists());
}
}
+1 -1
Переглянути файл
@@ -19,7 +19,7 @@ fn main() {
eprintln!("synced in {:?}: {r:?}", started.elapsed());
}
let started = std::time::Instant::now();
let model = ide_build::load(&root, &cache, None);
let model = ide_build::load(&root, &cache);
println!("{}", serde_json::to_string_pretty(&model).unwrap());
eprintln!("loaded in {:?}", started.elapsed());
}
+2 -4
Переглянути файл
@@ -225,7 +225,6 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
}
let step = |p: &maven::MavenProject, extra: &[String]| {
let mut s = BuildStep::new(&p.command, &["-B", "-Dstyle.color=never"], &subdir(root, &p.dir), Format::Maven);
s.args.extend(p.options.iter().cloned());
s.args.extend(extra.iter().cloned());
s.args.extend(goals.iter().map(|g| (*g).to_owned()));
s.env = p.env.clone();
@@ -584,7 +583,6 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
code: m.code.clone(),
unnecessary: false,
deprecated: false,
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
});
}
out
@@ -673,7 +671,7 @@ mod tests {
);
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&root, "core/src/main/java/A.java", "class A {}");
let model = crate::load(&root, &tmp.path().join("cache"), None);
let model = crate::load(&root, &tmp.path().join("cache"));
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
assert_eq!(p.system, BuildSystem::Maven);
assert_eq!(p.title, "demo");
@@ -687,7 +685,7 @@ mod tests {
let g = tmp.path().join("g");
write(&g, "settings.gradle", "include 'app'");
write(&g, "app/build.gradle", "apply plugin: 'java'");
let model = crate::load(&g, &tmp.path().join("cache2"), None);
let model = crate::load(&g, &tmp.path().join("cache2"));
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java"))).unwrap();
assert_eq!(p.system, BuildSystem::Gradle);
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
-100
Переглянути файл
@@ -285,74 +285,6 @@ pub fn script_java_version(text: &str) -> Option<u32> {
None
}
/// Configurations whose dependencies are libraries (`testFixturesImplementation` ends in one).
const DEPENDENCY_CONFIGURATIONS: &[&str] = &[
"implementation",
"api",
"compileOnly",
"runtimeOnly",
"compileOnlyApi",
"annotationProcessor",
"kapt",
"ksp",
"compile",
"runtime",
"testCompile",
"testRuntime",
"developmentOnly",
];
fn is_dependency_configuration(name: &str) -> bool {
DEPENDENCY_CONFIGURATIONS.iter().any(|c| {
name == *c || {
let mut cap = c.chars();
let first = cap.next().map(|f| f.to_ascii_uppercase()).into_iter();
let capitalised: String = first.chain(cap).collect();
name.len() > c.len() && name.ends_with(&capitalised)
}
})
}
/// `(group, artifact, version)` of the external dependencies a build script declares:
/// `implementation 'g:a:v'`, `api("g:a:v:classifier@jar")`, and the map notation
/// `implementation group: 'g', name: 'a', version: 'v'` (Groovy) / `group = "g", …` (Kotlin).
/// Versions with interpolations, ranges and catalog aliases (`libs.x`) are skipped.
pub fn script_dependencies(text: &str) -> Vec<(String, String, String)> {
let text = strip_comments(text);
let mut out = Vec::new();
for line in text.lines().flat_map(|l| l.split(['{', ';'])) {
let line = line.trim_start();
let name: String = line.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if name.is_empty() || !is_dependency_configuration(&name) {
continue;
}
let rest = &line[name.len()..];
let lits = literals(rest);
let map_value = |key: &str| -> Option<String> {
let i = rest.find(key)?;
let after = rest[i + key.len()..].trim_start().strip_prefix([':', '='])?;
literals(after).into_iter().next()
};
let coordinate = match (map_value("group"), map_value("name"), map_value("version")) {
(Some(g), Some(a), Some(v)) => Some((g, a, v)),
_ => lits.first().and_then(|l| {
let l = l.split('@').next().unwrap_or(l);
let mut parts = l.split(':');
Some((parts.next()?.to_owned(), parts.next()?.to_owned(), parts.next()?.to_owned()))
}),
};
if let Some((g, a, v)) = coordinate {
let plain = |s: &str| {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
};
if plain(&g) && plain(&a) && plain(&v) && !v.contains('+') {
out.push((g, a, v));
}
}
}
out
}
/// Every settings and build script of the model (for change detection).
pub fn build_files(root: &Path, model: &GradleModel) -> Vec<PathBuf> {
let dir = root.join(&model.dir);
@@ -401,38 +333,6 @@ pub fn parse_tasks(output: &str) -> Vec<(String, GradleTask)> {
#[cfg(test)]
mod tests {
#[test]
fn script_dependencies_read_string_and_map_notations() {
let script = r#"
plugins { id 'java' }
dependencies {
implementation 'com.google.guava:guava:33.0.0-jre'
api("org.slf4j:slf4j-api:2.0.9")
testImplementation "junit:junit:4.13.2@jar"
// implementation 'commented:out:1.0'
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.30'
runtimeOnly(group = "com.h2database", name = "h2", version = "2.2.224")
implementation "org.x:dyn:${ver}"
implementation 'org.x:range:1.+'
implementation libs.okhttp
implementation project(':core')
classpath 'not:a:library'
}
"#;
let deps = script_dependencies(script);
let names: Vec<String> = deps.iter().map(|(g, a, v)| format!("{g}:{a}:{v}")).collect();
assert_eq!(
names,
[
"com.google.guava:guava:33.0.0-jre",
"org.slf4j:slf4j-api:2.0.9",
"junit:junit:4.13.2",
"org.projectlombok:lombok:1.18.30",
"com.h2database:h2:2.2.224",
]
);
}
use super::*;
#[test]
+5 -95
Переглянути файл
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::path::Path;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -36,10 +36,9 @@ pub struct BuildModel {
}
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
let maven = maven::is_maven_project(root).then(|| {
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
let mut m = maven::load(root);
sync::apply_maven_cache(root, cache_dir, &mut m);
m
});
@@ -50,56 +49,6 @@ pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> Build
BuildModel { maven, gradle }
}
/// A library the project depends on, as `groupId:artifactId:version`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DependencyCoordinate {
/// Gradle builds resolve into the Gradle cache, Maven ones into the local repository.
pub gradle: bool,
pub group_id: String,
pub artifact_id: String,
pub version: String,
}
/// The external libraries of `model`, sorted and deduplicated: Maven dependencies
/// (with the transitive ones the last sync read), except the build's own modules,
/// `pom` imports and `system` scope; dependencies declared in the Gradle build scripts.
pub fn dependency_coordinates(root: &Path, model: &BuildModel) -> Vec<DependencyCoordinate> {
let mut out = Vec::new();
if let Some(m) = &model.maven {
let modules: std::collections::HashSet<String> = m.projects.iter().map(MavenProject::key).collect();
let mut stack: Vec<&MavenDependency> = m.projects.iter().flat_map(|p| &p.dependencies).collect();
while let Some(d) = stack.pop() {
stack.extend(&d.children);
let Some(version) = d.version.as_deref().filter(|v| !v.is_empty() && !v.contains("${")) else {
continue;
};
if d.kind == "pom" || matches!(d.scope.as_str(), "import" | "system") {
continue;
}
if modules.contains(&format!("{}:{}", d.group_id, d.artifact_id)) {
continue;
}
out.push(DependencyCoordinate {
gradle: false,
group_id: d.group_id.clone(),
artifact_id: d.artifact_id.clone(),
version: version.to_owned(),
});
}
}
if let Some(g) = &model.gradle {
for script in g.projects.iter().filter_map(|p| p.build_file.as_ref()) {
let Ok(text) = std::fs::read_to_string(root.join(script)) else { continue };
out.extend(gradle::script_dependencies(&text).into_iter().map(|(group_id, artifact_id, version)| {
DependencyCoordinate { gradle: true, group_id, artifact_id, version }
}));
}
}
out.sort();
out.dedup();
out
}
/// Whether a created / changed / removed project-relative path can change the build model.
pub fn affects_build(rel: &Path) -> bool {
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
@@ -119,52 +68,13 @@ mod tests {
let cache = tmp.path().join("cache");
let root = tmp.path().join("p");
std::fs::create_dir_all(root.join("svc")).unwrap();
assert_eq!(load(&root, &cache, None), BuildModel::default());
assert_eq!(load(&root, &cache), BuildModel::default());
std::fs::write(root.join("svc/pom.xml"), "<project><artifactId>svc</artifactId></project>").unwrap();
std::fs::write(root.join("build.gradle"), "").unwrap();
let m = load(&root, &cache, None);
let m = load(&root, &cache);
assert_eq!(m.maven.unwrap().projects[0].pom, "svc/pom.xml");
assert_eq!(m.gradle.unwrap().projects[0].path, ":");
assert!(affects_build(Path::new("a/pom.xml")) && affects_build(Path::new("settings.gradle.kts")));
assert!(!affects_build(Path::new("src/Main.java")));
}
#[test]
fn dependency_coordinates_flatten_maven_trees_and_read_gradle_scripts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("build.gradle"), "dependencies { implementation 'org.a:x:1.0' }\n").unwrap();
let dep = |g: &str, a: &str, v: Option<&str>, children: Vec<MavenDependency>| MavenDependency {
group_id: g.into(),
artifact_id: a.into(),
version: v.map(Into::into),
kind: "jar".into(),
scope: "compile".into(),
children,
..Default::default()
};
let maven = MavenModel {
projects: vec![
MavenProject {
group_id: "me".into(),
artifact_id: "app".into(),
dependencies: vec![
dep("me", "core", Some("1"), vec![]),
dep("org.b", "y", Some("2"), vec![dep("org.c", "z", Some("3"), vec![])]),
dep("org.d", "unresolved", Some("${v}"), vec![]),
],
..Default::default()
},
MavenProject { group_id: "me".into(), artifact_id: "core".into(), ..Default::default() },
],
..Default::default()
};
let gradle = gradle::load(root);
let model = BuildModel { maven: Some(maven), gradle };
let names: Vec<String> = dependency_coordinates(root, &model)
.into_iter()
.map(|c| format!("{}{}:{}:{}", if c.gradle { "G " } else { "M " }, c.group_id, c.artifact_id, c.version))
.collect();
assert_eq!(names, ["M org.b:y:2", "M org.c:z:3", "G org.a:x:1.0"]);
}
}
+1 -4
Переглянути файл
@@ -92,8 +92,6 @@ pub struct MavenProject {
pub java_version: Option<u32>,
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
pub command: String,
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
pub options: Vec<String>,
/// Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell.
pub env: BTreeMap<String, String>,
}
@@ -412,7 +410,7 @@ struct Resolver {
}
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
pub(crate) fn default_local_repo() -> Option<PathBuf> {
fn default_local_repo() -> Option<PathBuf> {
let m2 = dirs::home_dir()?.join(".m2");
if let Some(settings) = std::fs::read_to_string(m2.join("settings.xml")).ok().and_then(|t| xml::parse(&t))
&& let Some(repo) = settings.text_of("localRepository")
@@ -926,7 +924,6 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
java_version: jv,
command: wrapper(root, &dir),
options: Vec::new(),
env: BTreeMap::new(),
});
for m in modules.into_iter().rev() {
+6 -1
Переглянути файл
@@ -52,7 +52,12 @@ pub(crate) fn run(
use std::os::unix::process::CommandExt;
command.process_group(0);
}
ide_core::process::no_window(&mut command);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
+1 -7
Переглянути файл
@@ -29,10 +29,6 @@ pub struct SyncOptions {
pub profiles: Vec<String>,
/// Extra environment (`JAVA_HOME`).
pub env: BTreeMap<String, String>,
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
pub maven_command: Option<String>,
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
pub maven_options: Vec<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -188,7 +184,6 @@ pub fn sync_maven(
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
let _ = std::fs::remove_file(&effective);
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into()];
args.extend(options.maven_options.iter().cloned());
if options.offline {
args.push("-o".into());
}
@@ -199,8 +194,7 @@ pub fn sync_maven(
args.push(format!("-Doutput={}", effective.to_string_lossy()));
args.push("dependency:tree".into());
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
let out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
if let Some((name, i, total)) = maven_building(line) {
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
progress(SyncProgress { message: format!("Building model of {name}"), fraction: Some(fraction) });
-8
Переглянути файл
@@ -1,8 +0,0 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP read/write, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
-293
Переглянути файл
@@ -1,293 +0,0 @@
//! The file list on the OS clipboard: what Explorer copies when the user
//! copies files, so the project view can paste them, and what the project view
//! writes so Explorer can paste the files it copied (IDEA does both).
//!
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
//! in full rather than rendered on demand, so no window or message loop is
//! needed and the list survives after `CloseClipboard`.
//!
//! Other platforms keep file lists elsewhere (`public.file-url` on macOS,
//! `text/uri-list` on X11) and are not wired up: [`files`] is empty and
//! [`set_files`] fails there.
use std::path::PathBuf;
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
pub fn files() -> Vec<PathBuf> {
imp::files()
}
/// Whether the clipboard holds a file list, without reading it.
pub fn has_files() -> bool {
imp::has_files()
}
/// Replaces the clipboard with `paths`. False when it is busy or holds nothing
/// to write; the clipboard is a shared resource, so callers treat this as
/// best-effort.
pub fn set_files(paths: &[PathBuf]) -> bool {
if paths.is_empty() {
return false;
}
imp::set_files(paths)
}
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
/// page survive. Empty paths are skipped.
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
let mut units: Vec<u16> = Vec::new();
for path in paths {
let path = path.to_string_lossy();
if path.is_empty() {
continue;
}
units.extend(path.encode_utf16());
units.push(0);
}
// The list ends with an empty string: with one path, two NULs in a row.
units.push(0);
let mut out = Vec::with_capacity(HEADER + units.len() * 2);
out.extend_from_slice(&(HEADER as u32).to_le_bytes()); // pFiles: list starts after the header
out.extend_from_slice(&[0u8; 8]); // pt: the drop point, unused
out.extend_from_slice(&0u32.to_le_bytes()); // fNC: not a file manager drop
out.extend_from_slice(&1u32.to_le_bytes()); // fWide: UTF-16 paths
for unit in units {
out.extend_from_slice(&unit.to_le_bytes());
}
out
}
/// The paths of a `DROPFILES` block, stopping at the empty string that ends the
/// list. An ANSI list (pre-Unicode writers) is decoded as UTF-8, lossily.
pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
if bytes.len() < HEADER {
return Vec::new();
}
let offset = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
let wide = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]) != 0;
if offset >= bytes.len() {
return Vec::new();
}
let body = &bytes[offset..];
let mut out = Vec::new();
if wide {
let mut current: Vec<u16> = Vec::new();
for chunk in body.as_chunks::<2>().0 {
let unit = u16::from_le_bytes(*chunk);
if unit != 0 {
current.push(unit);
} else if current.is_empty() {
break;
} else {
out.push(PathBuf::from(String::from_utf16_lossy(&current)));
current.clear();
}
}
} else {
for part in body.split(|b| *b == 0) {
if part.is_empty() {
break;
}
out.push(PathBuf::from(String::from_utf8_lossy(part).into_owned()));
}
}
out
}
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, encode};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
use std::time::Duration;
/// `CF_HDROP`, the clipboard format holding a file list.
const CF_HDROP: u32 = 15;
/// An `HGLOBAL` or a `HANDLE`: both are opaque pointers here.
type Handle = *mut c_void;
const GMEM_MOVEABLE: u32 = 0x0002;
/// Another process holds the clipboard only while it copies; retrying beats
/// reporting "no files" for a paste the user just made.
const OPEN_ATTEMPTS: usize = 10;
const OPEN_RETRY: Duration = Duration::from_millis(20);
#[link(name = "user32")]
unsafe extern "system" {
fn OpenClipboard(owner: Handle) -> i32;
fn CloseClipboard() -> i32;
fn EmptyClipboard() -> i32;
fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32;
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
fn GlobalLock(memory: Handle) -> *mut c_void;
fn GlobalUnlock(memory: Handle) -> i32;
fn GlobalFree(memory: Handle) -> Handle;
fn GlobalSize(memory: Handle) -> usize;
}
/// Opens the clipboard as its owner: the list is written in full, so no
/// owning window is needed.
fn open() -> bool {
for _ in 0..OPEN_ATTEMPTS {
if unsafe { OpenClipboard(ptr::null_mut()) } != 0 {
return true;
}
std::thread::sleep(OPEN_RETRY);
}
false
}
pub fn has_files() -> bool {
(unsafe { IsClipboardFormatAvailable(CF_HDROP) }) != 0
}
pub fn files() -> Vec<PathBuf> {
if !has_files() || !open() {
return Vec::new();
}
let memory = unsafe { GetClipboardData(CF_HDROP) };
let paths = if memory.is_null() {
Vec::new()
} else {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let data = GlobalLock(memory);
if data.is_null() {
Vec::new()
} else {
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory));
let paths = decode(bytes);
GlobalUnlock(memory);
paths
}
}
};
unsafe { CloseClipboard() };
paths
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
}
// SAFETY: the block is allocated, filled, handed to the clipboard and
// freed only on the paths where the clipboard did not take ownership.
unsafe {
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
if memory.is_null() {
return false;
}
let data = GlobalLock(memory);
if data.is_null() {
GlobalFree(memory);
return false;
}
ptr::copy_nonoverlapping(bytes.as_ptr(), data as *mut u8, bytes.len());
GlobalUnlock(memory);
if !open() {
GlobalFree(memory);
return false;
}
// Replacing the list also drops the text the user copied before.
if EmptyClipboard() == 0 {
CloseClipboard();
GlobalFree(memory);
return false;
}
let taken = !SetClipboardData(CF_HDROP, memory).is_null();
CloseClipboard();
if !taken {
GlobalFree(memory);
}
taken
}
}
}
#[cfg(not(windows))]
mod imp {
use std::path::PathBuf;
pub fn has_files() -> bool {
false
}
pub fn files() -> Vec<PathBuf> {
Vec::new()
}
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
assert_eq!(decode(&encode(&list)), list);
}
#[test]
fn the_header_says_where_the_paths_start_and_that_they_are_wide() {
let bytes = encode(&paths(&["C:/a"]));
assert_eq!(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]), HEADER as u32);
assert_eq!(u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]), 1);
// `C:/a` plus its NUL, then the empty string that ends the list.
assert_eq!(bytes.len(), HEADER + (4 + 1 + 1) * 2);
assert_eq!(&bytes[HEADER + 6..HEADER + 8], b"a\0");
assert_eq!(&bytes[bytes.len() - 4..], &[0, 0, 0, 0]);
}
#[test]
fn names_outside_the_ansi_code_page_survive() {
let list = paths(&["C:/工作/文档/测试.txt", "C:/a/"]);
assert_eq!(decode(&encode(&list)), list);
}
#[test]
fn an_empty_list_has_no_paths() {
assert_eq!(decode(&encode(&[])), Vec::<PathBuf>::new());
// A lone terminator is enough for the reader to stop.
assert_eq!(decode(&[0u8; HEADER]), Vec::<PathBuf>::new());
}
#[test]
fn a_truncated_or_foreign_block_reads_as_no_paths() {
assert_eq!(decode(&[]), Vec::<PathBuf>::new());
assert_eq!(decode(&[1, 2, 3]), Vec::<PathBuf>::new());
let mut far = encode(&paths(&["C:/a"]));
far[0] = 0xff; // pFiles past the end
assert_eq!(decode(&far), Vec::<PathBuf>::new());
}
#[test]
fn an_ansi_list_is_still_read_before_the_terminator() {
let mut bytes = vec![0u8; HEADER];
bytes[..4].copy_from_slice(&(HEADER as u32).to_le_bytes());
bytes[16] = 0; // fWide: the list is single-byte
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
}
}
+13 -84
Переглянути файл
@@ -39,7 +39,7 @@ impl Default for EditorGeneralSettings {
caret_scroll: "minimize".into(),
soft_wrap_files: "*.md; *.txt; *.rst; *.adoc".into(),
soft_wrap_indent: true,
scroll_past_end: false,
scroll_past_end: true,
strip_trailing_scope: "modified".into(),
keep_trailing_on_caret_line: true,
remove_trailing_blank_lines: false,
@@ -102,7 +102,7 @@ pub struct BreadcrumbsSettings {
impl Default for BreadcrumbsSettings {
fn default() -> Self {
Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
Self { show: false, placement: "bottom".into(), disabled_languages: Vec::new() }
}
}
@@ -117,12 +117,6 @@ pub struct CompletionSettings {
pub auto_popup: bool,
/// Insert the selected suggestion by pressing space, dot, or other context-dependent keys.
pub insert_on_special_keys: bool,
/// Insert a sole suggestion of explicit (⌃Space) completion right away.
pub auto_insert_single: bool,
/// Sort suggestions by name instead of relevance.
pub sort_alphabetically: bool,
/// Add `()` after function and method suggestions.
pub insert_parentheses: bool,
pub show_documentation: bool,
pub documentation_delay: u32,
pub parameter_info: bool,
@@ -136,13 +130,10 @@ impl Default for CompletionSettings {
case_sensitivity: "first".into(),
auto_popup: true,
insert_on_special_keys: false,
auto_insert_single: true,
sort_alphabetically: false,
insert_parentheses: true,
show_documentation: false,
show_documentation: true,
documentation_delay: 500,
parameter_info: true,
parameter_info_delay: 1000,
parameter_info_delay: 300,
}
}
}
@@ -175,22 +166,13 @@ impl Default for FoldingSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct EditorTabsSettings {
/// `top` | `bottom` | `none`.
/// `top` | `none`.
pub placement: String,
pub multiple_rows: bool,
/// One row that doesn't fit: `scroll` the tabs panel | `squeeze` the tabs.
pub one_row_overflow: String,
pub pinned_separate_row: bool,
pub show_file_icon: bool,
pub show_extension: bool,
pub show_directory_for_non_unique: bool,
/// Mark modified tabs with an asterisk.
pub mark_modified: bool,
pub show_full_path_on_hover: bool,
pub show_close_button: bool,
/// `right` | `left` (with `show_close_button`).
pub close_button_position: String,
pub sort_alphabetically: bool,
pub preview_tab: bool,
pub open_at_end: bool,
pub tab_limit: u32,
@@ -205,21 +187,14 @@ impl Default for EditorTabsSettings {
Self {
placement: "top".into(),
multiple_rows: false,
one_row_overflow: "scroll".into(),
pinned_separate_row: false,
show_file_icon: true,
show_extension: true,
show_directory_for_non_unique: true,
mark_modified: false,
show_full_path_on_hover: true,
show_close_button: true,
close_button_position: "right".into(),
sort_alphabetically: false,
preview_tab: true,
open_at_end: false,
tab_limit: 30,
closing_policy: "lru".into(),
activate_on_close: "left".into(),
tab_limit: 10,
closing_policy: "unchanged".into(),
activate_on_close: "mru".into(),
}
}
}
@@ -239,7 +214,7 @@ pub struct SmartKeysSettings {
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
pub smart_indent: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
/// Backspace › Unindent: `nearest` indent position | `none`.
pub backspace_unindent: String,
}
@@ -251,10 +226,10 @@ impl Default for SmartKeysSettings {
pair_brackets: true,
pair_quotes: true,
surround_selection: true,
tab_out_of_pair: true,
reformat_on_paste: "indentEachLine".into(),
tab_out_of_pair: false,
reformat_on_paste: "indentBlock".into(),
smart_indent: true,
backspace_unindent: "autoindent".into(),
backspace_unindent: "nearest".into(),
}
}
}
@@ -300,38 +275,11 @@ pub struct InlayHintsSettings {
pub disabled_languages: Vec<String>,
/// Code vision: usages above declarations.
pub code_vision_usages: bool,
/// Code vision: last author of a declaration (VCS blame) beside its usages.
pub code_vision_author: bool,
}
impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
parameters: true,
other: true,
disabled_languages: Vec::new(),
code_vision_usages: true,
code_vision_author: true,
}
}
}
/// Editor › General › Inline Completion: ghost text from language servers that
/// support `textDocument/inlineCompletion` (LSP 3.18).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct InlineCompletionSettings {
pub enabled: bool,
/// Ask only once typing has paused for `pause_ms`, instead of right after each change.
pub only_on_pause: bool,
pub pause_ms: u32,
pub disabled_languages: Vec<String>,
}
impl Default for InlineCompletionSettings {
fn default() -> Self {
Self { enabled: true, only_on_pause: false, pause_ms: 500, disabled_languages: Vec::new() }
Self { types: true, parameters: true, other: true, disabled_languages: Vec::new(), code_vision_usages: true }
}
}
@@ -366,12 +314,6 @@ pub struct LanguageCodeStyle {
pub indent: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hard_wrap_at: Option<u32>,
/// Comment Code › Line comment at first column.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_at_first_column: Option<bool>,
/// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -387,14 +329,6 @@ pub struct CodeStyleSettings {
/// Enable EditorConfig support.
pub editorconfig: bool,
pub languages: BTreeMap<String, LanguageCodeStyle>,
/// Formatter › Do not format: globs (`*.min.js`, `generated/**`) Reformat Code skips.
pub do_not_format: Vec<String>,
/// Formatter › Turn formatter on/off with markers in code comments.
pub formatter_tags_enabled: bool,
pub formatter_off_tag: String,
pub formatter_on_tag: String,
/// The markers are regular expressions.
pub formatter_tags_regexp: bool,
}
impl Default for CodeStyleSettings {
@@ -406,11 +340,6 @@ impl Default for CodeStyleSettings {
detect_indents: true,
editorconfig: true,
languages: BTreeMap::new(),
do_not_format: Vec::new(),
formatter_tags_enabled: false,
formatter_off_tag: "@formatter:off".into(),
formatter_on_tag: "@formatter:on".into(),
formatter_tags_regexp: false,
}
}
}
-8
Переглянути файл
@@ -32,11 +32,6 @@ pub enum IdeEvent {
doc: DocId,
dirty: bool,
},
/// An open document's language changed (Settings › File Types, Override File Type).
DocLanguage {
doc: DocId,
language: crate::LanguageId,
},
/// Full replacement of diagnostics for one file from one producer.
Diagnostics {
path: crate::IpcPath,
@@ -111,9 +106,6 @@ pub enum ServerStatus {
Crashed,
Stopped,
Missing,
/// Not started: its configuration can't launch it (e.g. no JDK new enough);
/// the message says what to change, and a settings change retries.
Misconfigured,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
-114
Переглянути файл
@@ -1,114 +0,0 @@
//! Settings › Editor › Inspections: inspection profiles. `Default` and the
//! user's IDE-level copies live in the IDE (global) settings, `Project Default`
//! and project-level copies in the project's; the project picks which one is in
//! effect. The UI applies the profile to diagnostics. Also Editor › Natural
//! Languages › Spelling (the Typo inspection's dictionaries).
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct InspectionSettings {
/// Profile in effect for the project: `default`, `project`, or a copy
/// as `ide:<key>` / `project:<key>`.
pub profile: String,
/// The `Default` profile (IDE level): inspection id → override.
pub default: BTreeMap<String, InspectionOverride>,
/// The `Project Default` profile (stored with the project).
pub project: BTreeMap<String, InspectionOverride>,
/// Profiles copied at IDE level (global settings), by key.
pub ide_profiles: BTreeMap<String, CustomInspectionProfile>,
/// Profiles copied at project level (project settings), by key.
pub project_profiles: BTreeMap<String, CustomInspectionProfile>,
}
impl Default for InspectionSettings {
fn default() -> Self {
Self {
profile: "default".into(),
default: BTreeMap::new(),
project: BTreeMap::new(),
ide_profiles: BTreeMap::new(),
project_profiles: BTreeMap::new(),
}
}
}
/// A named profile made with Copy.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CustomInspectionProfile {
pub name: String,
pub overrides: BTreeMap<String, InspectionOverride>,
}
/// Editor › Natural Languages › Spelling.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SpellingSettings {
/// Application-level dictionary: accepted words (IDE settings).
pub ide_words: Vec<String>,
/// Project-level dictionary: accepted words (project settings).
pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<String>,
}
/// Changes to one inspection; absent fields keep the inspection's defaults.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct InspectionOverride {
#[specta(optional)]
pub enabled: Option<bool>,
#[specta(optional)]
pub severity: Option<InspectionLevel>,
/// The inspection's own options (Typo: `processCode`, `processLiterals`,
/// `processComments`); absent ones keep their defaults.
#[specta(optional)]
pub options: Option<BTreeMap<String, bool>>,
}
/// IDEA's highlighting levels.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum InspectionLevel {
Error,
Warning,
WeakWarning,
ServerProblem,
Typo,
/// Reported (Problems, Inspect Code) but not highlighted in the editor.
None,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overrides_parse_partially() {
let s: InspectionSettings = serde_json::from_str(
r#"{"default":{"lsp:ruff":{"enabled":false},"lsp:ruff:F401":{"severity":"weakWarning"}}}"#,
)
.unwrap();
assert_eq!(s.profile, "default");
assert_eq!(s.default["lsp:ruff"].enabled, Some(false));
assert_eq!(s.default["lsp:ruff:F401"].severity, Some(InspectionLevel::WeakWarning));
assert!(s.project.is_empty());
assert!(s.ide_profiles.is_empty());
let s: InspectionSettings = serde_json::from_str(
r#"{"profile":"ide:strict","ideProfiles":{"strict":{"name":"Strict","overrides":{"lsp:ruff":{"severity":"error"}}}}}"#,
)
.unwrap();
assert_eq!(s.ide_profiles["strict"].name, "Strict");
assert_eq!(s.ide_profiles["strict"].overrides["lsp:ruff"].severity, Some(InspectionLevel::Error));
assert!(serde_json::from_str::<InspectionSettings>(r#"{"default":{"x":{"severity":"loud"}}}"#).is_err());
let s: InspectionSettings =
serde_json::from_str(r#"{"default":{"builtin:spelling":{"options":{"processCode":false}}}}"#).unwrap();
assert!(!s.default["builtin:spelling"].options.as_ref().unwrap()["processCode"]);
let back: InspectionSettings = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
assert_eq!(back, s);
}
}
-2
Переглянути файл
@@ -9,9 +9,7 @@ pub mod error;
pub mod event;
pub mod ids;
pub mod ignored;
pub mod inspection_settings;
pub mod ipc_path;
pub mod process;
pub mod project_dir;
pub mod settings;
pub mod text;
-53
Переглянути файл
@@ -1,53 +0,0 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Keeps a console child (java, node, curl, a language server, ...) from
/// opening its own console window on Windows. Release builds use the GUI
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
pub fn no_window(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW);
}
cmd
}
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
/// Records the login shell's environment, read once at startup off the main thread.
pub fn set_shell_env(vars: Vec<(OsString, OsString)>) {
let _ = SHELL_ENV.set(vars);
}
/// The login shell's variables this process lacks: an app started from Finder/Dock gets only
/// PATH from the shell, not what rc files export (API keys and provider switches, SDK homes...).
/// Apply before a call site's own variables so those win. Empty until the shell has been read.
pub fn shell_env() -> impl Iterator<Item = (&'static OsStr, &'static OsStr)> {
SHELL_ENV
.get()
.into_iter()
.flatten()
.filter(|(k, _)| std::env::var_os(k).is_none())
.map(|(k, v)| (k.as_os_str(), v.as_os_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_env_adds_only_what_the_process_lacks() {
set_shell_env(vec![("OPENIDEA_SHELL_ONLY_VAR".into(), "1".into()), ("PATH".into(), "/from/shell".into())]);
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
}
+1 -145
Переглянути файл
@@ -6,7 +6,6 @@ use specta::Type;
use std::collections::BTreeMap;
pub use crate::editor_settings::*;
pub use crate::inspection_settings::*;
pub use crate::workflow_settings::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -38,27 +37,6 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
/// Editor › Inspections profiles.
pub inspections: InspectionSettings,
/// Editor › Natural Languages › Spelling.
pub spelling: SpellingSettings,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
/// Executable to launch instead of the managed / `PATH` one; empty = auto-detect.
pub path: String,
}
impl Settings {
/// The configured executable for `command`, if any (`~/` not yet expanded).
pub fn tool_path(&self, command: &str) -> Option<&str> {
self.tools.get(command).map(|t| t.path.trim()).filter(|p| !p.is_empty())
}
}
impl Default for Settings {
@@ -81,9 +59,6 @@ impl Default for Settings {
terminal: TerminalSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
}
}
}
@@ -116,11 +91,6 @@ pub struct GeneralSettings {
pub save_on_idle: bool,
pub idle_seconds: u32,
pub date_format: DateFormatSettings,
/// File › Power Save Mode: no automatic popups (completion, parameter info,
/// quick documentation) or background highlighting (usages, code vision).
pub power_save_mode: bool,
/// File › Rename Project… (project layer): the name shown for the project; empty = its folder name.
pub project_name: String,
}
impl Default for GeneralSettings {
@@ -133,8 +103,6 @@ impl Default for GeneralSettings {
save_on_idle: false,
idle_seconds: 15,
date_format: DateFormatSettings::default(),
power_save_mode: false,
project_name: String::new(),
}
}
}
@@ -224,20 +192,6 @@ pub struct AppearanceSettings {
/// Status bar widgets shown (`true`) or hidden (`false`) by the user
/// (status bar context menu); widgets not listed use their default.
pub status_bar_widgets: BTreeMap<String, bool>,
/// Customize Main Toolbar; `None` = the default toolbar.
pub main_toolbar: Option<MainToolbarSettings>,
}
/// Main toolbar entries per side, in order: title widget ids (`project`,
/// `vcs.branch`…) or `action:<id>`. Widgets in neither list nor `hidden`
/// (registered later) keep their default place.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec<String>,
pub right: Vec<String>,
/// Widgets the user removed.
pub hidden: Vec<String>,
}
impl Default for AppearanceSettings {
@@ -267,7 +221,6 @@ impl Default for AppearanceSettings {
show_tool_window_names: true,
widescreen_tool_windows: false,
status_bar_widgets: BTreeMap::new(),
main_toolbar: None,
}
}
}
@@ -289,18 +242,9 @@ pub struct EditorSettings {
pub color_scheme: String,
/// Color Scheme edits: scheme id → attribute id → override.
pub color_overrides: BTreeMap<String, BTreeMap<String, TextAttributesOverride>>,
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
pub semantic_highlighting: bool,
/// Color Scheme › Language Defaults › Rainbow brackets: `()`, `[]`, `{}` coloured by depth.
pub rainbow_brackets: bool,
pub ligatures: bool,
/// Fallback font for glyphs the main font lacks; empty = none.
pub fallback_font: String,
/// Typography Settings › Main font weight (CSS 100–900), as IDEA.
pub font_weight: u16,
/// Typography Settings › Bold font weight: wherever the editor renders bold.
pub bold_font_weight: u16,
pub general: EditorGeneralSettings,
pub appearance: EditorAppearanceSettings,
pub breadcrumbs: BreadcrumbsSettings,
@@ -311,7 +255,6 @@ pub struct EditorSettings {
pub smart_keys: SmartKeysSettings,
pub code_editing: CodeEditingSettings,
pub inlay: InlayHintsSettings,
pub inline_completion: InlineCompletionSettings,
/// Gutter icon groups turned off (`run`, `breakpoints`, `bookmarks`, `vcs`, `blame`).
pub gutter_icons_disabled: Vec<String>,
pub show_gutter_icons: bool,
@@ -334,12 +277,8 @@ impl Default for EditorSettings {
format_on_save: false,
color_scheme: "theme-default".into(),
color_overrides: BTreeMap::new(),
semantic_highlighting: false,
rainbow_brackets: false,
ligatures: false,
fallback_font: String::new(),
font_weight: 400,
bold_font_weight: 700,
general: EditorGeneralSettings::default(),
appearance: EditorAppearanceSettings::default(),
breadcrumbs: BreadcrumbsSettings::default(),
@@ -350,7 +289,6 @@ impl Default for EditorSettings {
smart_keys: SmartKeysSettings::default(),
code_editing: CodeEditingSettings::default(),
inlay: InlayHintsSettings::default(),
inline_completion: InlineCompletionSettings::default(),
gutter_icons_disabled: Vec::new(),
show_gutter_icons: true,
code_style: CodeStyleSettings::default(),
@@ -373,22 +311,6 @@ pub struct FileSettings {
pub local_history_days: u32,
/// Upper bound for a project's Local History in MB; the oldest revisions go first.
pub local_history_max_mb: u32,
/// File Types › Recognized File Types: the user's changes, by language id.
pub file_types: BTreeMap<String, FileTypeAssociation>,
/// Override File Type: file (project-relative and `/`-separated, or absolute) → language id.
pub file_type_overrides: BTreeMap<String, String>,
}
/// One language's file name and hashbang patterns on top of its definition.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FileTypeAssociation {
/// Added file name patterns: `*.foo`, `Jenkinsfile`, `Dockerfile.*` (`*` and `?` wildcards).
pub patterns: Vec<String>,
/// Patterns of the definition (`*.ext`, file names) the user removed.
pub removed_patterns: Vec<String>,
/// Interpreters run by a `#!` first line, e.g. `node` for `#!/usr/bin/env node`.
pub hashbangs: Vec<String>,
}
impl Default for FileSettings {
@@ -401,8 +323,6 @@ impl Default for FileSettings {
ensure_final_newline: true,
local_history_days: 5,
local_history_max_mb: 512,
file_types: BTreeMap::new(),
file_type_overrides: BTreeMap::new(),
}
}
}
@@ -415,7 +335,6 @@ pub struct LanguagesSettings {
pub rust: RustSettings,
pub go: GoSettings,
pub typescript: TypeScriptSettings,
pub java: JavaSettings,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -478,35 +397,6 @@ pub struct GoSettings {
pub gopath: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct JavaSettings {
/// Project JDK home; empty = per module, the installed JDK matching the
/// Java version it targets.
pub jdk: String,
/// JDK home the Java language server (jdtls) runs on, apart from the project
/// JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
/// else the first installed one that is.
pub jdtls_jdk: String,
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
/// Build Tools › Maven.
pub maven: MavenSettings,
}
/// Build Tools › Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MavenSettings {
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
pub home: String,
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
pub user_settings: String,
/// Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`.
pub local_repository: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct TypeScriptSettings {
@@ -533,17 +423,6 @@ pub struct ProjectStructureSettings {
pub excluded: Vec<String>,
/// Auto-detected roots (from `pom.xml`, `build.gradle`, `Cargo.toml`, …) the user unmarked.
pub unmarked: Vec<String>,
/// Content roots besides the project folder (absolute paths), shown and searched with it.
pub content_roots: Vec<String>,
/// "Exclude files": `;`-separated name patterns (`*.log;tmp*`) excluded at any depth.
pub exclude_files: String,
}
impl ProjectStructureSettings {
/// The "Exclude files" name patterns.
pub fn exclude_file_patterns(&self) -> Vec<String> {
self.exclude_files.split(';').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned).collect()
}
}
impl Settings {
@@ -559,12 +438,10 @@ impl Settings {
out
}
/// `files.exclude`, `files.ignoredNames` and the Project Structure "Exclude files"
/// patterns (a bare name matches at any depth).
/// `files.exclude` plus `files.ignoredNames` (a bare name matches at any depth).
pub fn file_excludes(&self) -> Vec<String> {
let mut out = self.files.exclude.clone();
out.extend(self.files.ignored_names.iter().filter(|n| !n.trim().is_empty()).cloned());
out.extend(self.project_structure.exclude_file_patterns().into_iter().filter(|p| !p.contains('/')));
out
}
@@ -577,16 +454,6 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn editor_font_weights_default_to_regular_and_bold() {
let json = serde_json::to_value(Settings::default()).unwrap();
assert_eq!(json["editor"]["fontWeight"], 400);
assert_eq!(json["editor"]["boldFontWeight"], 700);
let s: Settings = serde_json::from_str(r#"{"editor":{"fontWeight":300,"boldFontWeight":600}}"#).unwrap();
assert_eq!((s.editor.font_weight, s.editor.bold_font_weight), (300, 600));
assert_eq!(s.editor.font_size, 13.0);
}
#[test]
fn keymap_overrides_are_camel_case_and_default_empty() {
let s: Settings =
@@ -609,15 +476,4 @@ mod tests {
assert!(k.overrides["file.save"].is_empty());
assert_eq!(serde_json::to_value(Settings::default()).unwrap()["customKeymaps"], serde_json::json!({}));
}
#[test]
fn exclude_files_patterns_join_the_file_excludes() {
let s: Settings = serde_json::from_str(
r#"{"files":{"exclude":[],"ignoredNames":[]},"projectStructure":{"excludeFiles":" *.log ; tmp*;;"}}"#,
)
.unwrap();
assert_eq!(s.project_structure.exclude_file_patterns(), vec!["*.log", "tmp*"]);
assert_eq!(s.file_excludes(), vec!["*.log", "tmp*"]);
assert!(Settings::default().files.file_types.is_empty());
}
}
-20
Переглянути файл
@@ -129,11 +129,6 @@ pub struct Diagnostic {
pub unnecessary: bool,
#[serde(default)]
pub deprecated: bool,
/// Language server (or tool) that reported it, e.g. `basedpyright`; `source`
/// is what the producer calls itself. Inspection profiles key on this.
#[serde(default)]
#[specta(optional)]
pub server: Option<String>,
}
/// Symbol kinds, a stable subset of LSP `SymbolKind`.
@@ -173,17 +168,6 @@ impl SymbolKind {
}
}
/// Declared (or conventional) visibility of an outline symbol.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Visibility {
Public,
Protected,
/// Package / module / assembly scope (Java default, `internal`, `pub(crate)`, Go unexported).
Package,
Private,
}
/// A node of a document outline (Structure tool window, breadcrumbs).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct OutlineItem {
@@ -195,10 +179,6 @@ pub struct OutlineItem {
/// The identifier itself; where navigation lands.
pub selection_range: Range,
pub children: Vec<OutlineItem>,
/// Unknown (`None`) for language-server symbols and languages without the notion.
#[serde(default)]
#[specta(optional)]
pub visibility: Option<Visibility>,
}
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
+2 -14
Переглянути файл
@@ -24,8 +24,7 @@ pub struct VcsSettings {
impl Default for VcsSettings {
fn default() -> Self {
Self {
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
show_dirty_directories: false,
show_dirty_directories: true,
limit_history: true,
history_limit: 1000,
git: GitSettings::default(),
@@ -212,8 +211,6 @@ impl Default for PythonDebuggerSettings {
#[serde(default, rename_all = "camelCase")]
pub struct RunSettings {
pub confirm_rerun: bool,
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
pub show_on_start: bool,
/// Grace period between interrupt and kill when stopping a process.
pub termination_timeout_ms: u32,
@@ -221,7 +218,7 @@ pub struct RunSettings {
impl Default for RunSettings {
fn default() -> Self {
Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 }
Self { confirm_rerun: true, show_on_start: true, termination_timeout_ms: 3000 }
}
}
@@ -244,8 +241,6 @@ pub struct TerminalSettings {
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub option_as_meta: bool,
/// Escape moves focus to the editor instead of reaching the shell.
pub escape_to_editor: bool,
/// `block` | `underline` | `bar`.
pub cursor_shape: String,
pub cursor_blink: bool,
@@ -254,10 +249,6 @@ pub struct TerminalSettings {
pub font_size: f32,
/// Multiple of the cell height.
pub line_height: f32,
/// Font tried for glyphs the main font lacks; empty = none.
pub fallback_font_family: String,
/// Multiple of the cell width.
pub column_width: f32,
}
impl Default for TerminalSettings {
@@ -276,15 +267,12 @@ impl Default for TerminalSettings {
shell_integration: true,
highlight_hyperlinks: true,
option_as_meta: false,
escape_to_editor: false,
cursor_shape: "block".into(),
cursor_blink: true,
use_editor_font: true,
font_family: "JetBrains Mono".into(),
font_size: 13.0,
line_height: 1.0,
fallback_font_family: String::new(),
column_width: 1.0,
}
}
}
-173
Переглянути файл
@@ -1,173 +0,0 @@
//! "Import a report collected in CI from disk": the format is sniffed from the
//! content (lcov, Go cover profile, JaCoCo XML) and paths recorded on another
//! machine are mapped into the project by their longest existing suffix.
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov};
use ide_core::{IdeError, IdeResult};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Format {
Lcov,
GoProfile,
Jacoco,
}
pub(crate) fn detect(text: &str) -> Option<Format> {
let head = text.trim_start_matches('\u{feff}').trim_start();
if head.starts_with('<') {
return head.contains("<report").then_some(Format::Jacoco);
}
let first = head.lines().next().unwrap_or_default();
if first.starts_with("mode:") {
return Some(Format::GoProfile);
}
head.lines().any(|l| l.trim_start().starts_with("SF:")).then_some(Format::Lcov)
}
/// Reads the report at `path` for the project at `root`. Blocking.
pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
let text = std::fs::read_to_string(path)?;
let mut suite = match detect(&text) {
Some(Format::Lcov) => lcov::parse(&text, root).finish("lcov"),
Some(Format::GoProfile) => {
let (module, module_dir) = go_module_for(root, &text);
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
}
Some(Format::Jacoco) => {
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
let module = jacoco::module_dir(path);
let module =
if path.starts_with(root) && module.starts_with(root) && module != path.parent().unwrap_or(path) {
module
} else {
root.to_path_buf()
};
let mut acc = Accumulator { has_branches: true, ..Default::default() };
jacoco::parse_into(&text, &module, &mut acc)
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
acc.finish("JaCoCo")
}
None => {
return Err(IdeError::invalid(format!(
"{} is not an lcov tracefile, Go cover profile or JaCoCo XML report",
path.display()
)));
}
};
for f in &mut suite.files {
let p: &Path = f.path.as_ref();
if !p.exists()
&& let Some(found) = relocate(p, root)
{
f.path = found.into();
}
}
suite.files.sort_by(|a, b| (a.path.as_ref() as &Path).cmp(b.path.as_ref()));
Ok(suite)
}
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
/// `path` that exists under `root`.
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
let parts: Vec<&std::ffi::OsStr> = path
.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s),
_ => None,
})
.collect();
(0..parts.len()).find_map(|skip| {
let candidate = parts[skip..].iter().fold(root.to_path_buf(), |p, s| p.join(s));
candidate.is_file().then_some(candidate)
})
}
/// The Go module the profile's import paths belong to: the project's `go.mod`, else one
/// a level or two down whose module path prefixes the profile's files.
fn go_module_for(root: &Path, profile: &str) -> (String, PathBuf) {
let first = profile
.lines()
.map(str::trim)
.find(|l| !l.is_empty() && !l.starts_with("mode:"))
.and_then(|l| l.rsplit_once(':').map(|(f, _)| f.to_owned()))
.unwrap_or_default();
let matches = |module: &str| !module.is_empty() && (first == module || first.starts_with(&format!("{module}/")));
let read = |dir: &Path| -> Option<String> {
let text = std::fs::read_to_string(dir.join("go.mod")).ok()?;
text.lines().find_map(|l| l.trim().strip_prefix("module")).map(|m| m.trim().trim_matches('"').to_owned())
};
let mut candidates = vec![root.to_path_buf()];
for dir in std::fs::read_dir(root).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
candidates
.extend(std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()));
candidates.push(dir);
}
let found: Vec<(String, PathBuf)> = candidates.into_iter().filter_map(|d| read(&d).map(|m| (m, d))).collect();
found
.iter()
.find(|(m, _)| matches(m))
.or_else(|| found.iter().find(|(_, d)| d == root))
.cloned()
.unwrap_or_else(|| (String::new(), root.to_path_buf()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_formats() {
assert_eq!(detect("TN:\nSF:a.rs\nDA:1,1\nend_of_record\n"), Some(Format::Lcov));
assert_eq!(detect("mode: atomic\nm/a.go:1.1,2.2 1 0\n"), Some(Format::GoProfile));
assert_eq!(
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
Some(Format::Jacoco)
);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
assert_eq!(detect("hello"), None);
}
#[test]
fn imports_ci_lcov_with_foreign_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/lib.rs"), "").unwrap();
let report = tmp.path().join("lcov.info");
std::fs::write(&report, "SF:/home/runner/work/app/app/src/lib.rs\nDA:1,1\nDA:2,0\nend_of_record\n").unwrap();
let suite = import(&report, &root).unwrap();
assert_eq!(suite.runner, "lcov");
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("src/lib.rs"));
assert_eq!(suite.files[0].lines_covered, 1);
assert!(import(&tmp.path().join("missing"), &root).is_err());
std::fs::write(&report, "nothing").unwrap();
assert!(import(&report, &root).is_err());
}
#[test]
fn imports_go_profiles_of_nested_modules() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("svc/calc")).unwrap();
std::fs::write(root.join("svc/go.mod"), "module example.com/svc\n").unwrap();
let report = root.join("cover.out");
std::fs::write(&report, "mode: set\nexample.com/svc/calc/calc.go:3.1,4.2 1 1\n").unwrap();
let suite = import(&report, root).unwrap();
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("svc/calc/calc.go"));
}
#[test]
fn imports_jacoco_against_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("p");
std::fs::create_dir_all(root.join("src/main/java/com/x")).unwrap();
std::fs::write(root.join("src/main/java/com/x/A.java"), "").unwrap();
let report = tmp.path().join("jacoco.xml");
let xml = r#"<report name="p"><package name="com/x"><sourcefile name="A.java"><line nr="2" mi="0" ci="1" mb="0" cb="0"/></sourcefile></package></report>"#;
std::fs::write(&report, xml).unwrap();
let suite = import(&report, &root).unwrap();
assert_eq!(suite.files[0].path.as_ref() as &Path, root.join("src/main/java/com/x/A.java"));
assert!(suite.has_branches);
}
}
+1 -3
Переглянути файл
@@ -16,12 +16,10 @@
//! Lines in the model are 0-based, like every IPC coordinate.
mod goprofile;
mod import;
mod jacoco;
mod lcov;
mod plan;
pub use import::import;
pub use plan::prepare;
use ide_core::{IdeError, IdeResult, IpcPath};
@@ -206,7 +204,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
let (program, args) =
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
let out = ide_core::process::no_window(&mut Command::new(program))
let out = Command::new(program)
.args(args)
.current_dir(cwd)
.envs(env)
-2
Переглянути файл
@@ -287,8 +287,6 @@ mod tests {
detected: true,
is_test: true,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
+8 -74
Переглянути файл
@@ -18,8 +18,6 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::process::{Child, Command};
pub const PORT_PLACEHOLDER: &str = "${port}";
/// Replaced by the session's working directory (the project) in adapter arguments.
pub const ROOT_PLACEHOLDER: &str = "${root}";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Transport {
@@ -38,11 +36,6 @@ pub struct AdapterSpec {
pub cwd: PathBuf,
/// Extra environment of the adapter process (debugpy's private copy on `PYTHONPATH`).
pub env: Vec<(String, String)>,
/// Host of an adapter that is already running (`debugServer`); `None` is the loopback interface.
pub server_host: Option<String>,
/// `host:port` of an adapter inside another program (the Godot editor): connected to
/// when it accepts, else `command` is started.
pub connect: Option<String>,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -52,7 +45,6 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
command: command.to_owned(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: transport.to_owned(),
connect: None,
install_hint: Some(hint.to_owned()),
};
Some(match adapter {
@@ -124,8 +116,6 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
install_hint: config.install_hint.clone(),
cwd,
env: Vec::new(),
server_host: None,
connect: config.connect.clone(),
}
}
@@ -134,19 +124,6 @@ pub fn substitute_port(args: &[String], port: u16) -> Vec<String> {
args.iter().map(|a| a.replace(PORT_PLACEHOLDER, &port.to_string())).collect()
}
/// Replaces every `${root}` occurrence with `root`.
pub fn substitute_root(args: &[String], root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter().map(|a| a.replace(ROOT_PLACEHOLDER, &root)).collect()
}
/// Splits `host:port` (`[v6]:port`).
pub fn parse_address(addr: &str) -> Option<(String, u16)> {
let (host, port) = addr.trim().rsplit_once(':')?;
let host = host.trim_start_matches('[').trim_end_matches(']');
Some((host.to_owned(), port.parse().ok().filter(|p| *p != 0)?))
}
/// A port that was free a moment ago on the loopback interface.
pub fn free_port() -> std::io::Result<u16> {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
@@ -256,9 +233,7 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
let mut probe = Command::new(&python);
ide_core::process::no_window(probe.as_std_mut());
let probe = probe
let probe = Command::new(&python)
.args(["-c", "import debugpy.adapter"])
.current_dir(&spec.cwd)
.stdin(Stdio::null())
@@ -326,22 +301,13 @@ pub trait AdapterLauncher: Send + Sync + 'static {
pub struct ProcessLauncher;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
/// How long an adapter inside another program (a headless Godot editor) may take to listen.
const EMBEDDED_START_TIMEOUT: Duration = Duration::from_secs(120);
/// Probe of a `connect` address before starting the command.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
impl AdapterLauncher for ProcessLauncher {
fn launch(&self, mut spec: AdapterSpec, reuse_port: Option<u16>) -> LaunchFuture {
Box::pin(async move {
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
if let Some(port) = reuse_port {
// A remote adapter (`dlv --headless` on another machine) may answer slowly.
let (host, timeout) = match spec.server_host.as_deref() {
Some(host) => (host, CONNECT_TIMEOUT),
None => (LOOPBACK, Duration::from_secs(5)),
};
let stream = connect_with_retries(host, port, None, timeout).await?;
let stream = connect_with_retries(port, None, Duration::from_secs(5)).await?;
let (r, w) = stream.into_split();
return Ok(AdapterIo {
reader: Box::new(r),
@@ -351,28 +317,6 @@ impl AdapterLauncher for ProcessLauncher {
stderr,
});
}
let embedded = match spec.connect.as_deref().filter(|_| spec.transport == Transport::Tcp) {
Some(addr) => Some(
parse_address(addr)
.ok_or_else(|| IdeError::invalid(format!("invalid debug adapter address `{addr}`")))?,
),
None => None,
};
// An adapter inside a program the user runs (the Godot editor): use it, never stop it.
if let Some((host, port)) = &embedded
&& let Ok(Ok(stream)) =
tokio::time::timeout(PROBE_TIMEOUT, tokio::net::TcpStream::connect((host.as_str(), *port))).await
{
let _ = stream.set_nodelay(true);
let (r, w) = stream.into_split();
return Ok(AdapterIo {
reader: Box::new(r),
writer: Box::new(w),
child: None,
port: Some(*port),
stderr,
});
}
if spec.adapter == DEBUGPY_TOOL {
prepare_debugpy(&mut spec).await?;
}
@@ -383,20 +327,14 @@ impl AdapterLauncher for ProcessLauncher {
.flatten()
.ok_or_else(|| missing(&spec))?;
let port = match spec.transport {
// An embedded adapter started without `${port}` listens on its usual address.
Transport::Tcp => match &embedded {
Some((_, port)) if !spec.args.iter().any(|a| a.contains(PORT_PLACEHOLDER)) => Some(*port),
_ => Some(free_port()?),
},
Transport::Tcp => Some(free_port()?),
Transport::Stdio => None,
};
let args = substitute_root(&spec.args, &spec.cwd);
let args = match port {
Some(port) => substitute_port(&args, port),
None => args,
Some(port) => substitute_port(&spec.args, port),
None => spec.args.clone(),
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
@@ -425,8 +363,7 @@ impl AdapterLauncher for ProcessLauncher {
if let Some(out) = child.stdout.take() {
pump_lines(out, spec.adapter.clone(), stderr.clone());
}
let timeout = if embedded.is_some() { EMBEDDED_START_TIMEOUT } else { CONNECT_TIMEOUT };
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), timeout).await {
let stream = match connect_with_retries(port, Some(&mut child), CONNECT_TIMEOUT).await {
Ok(s) => s,
Err(e) => {
let _ = child.start_kill();
@@ -470,17 +407,14 @@ fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
});
}
const LOOPBACK: &str = "127.0.0.1";
async fn connect_with_retries(
host: &str,
port: u16,
mut child: Option<&mut Child>,
timeout: Duration,
) -> IdeResult<tokio::net::TcpStream> {
let deadline = Instant::now() + timeout;
loop {
match tokio::net::TcpStream::connect((host, port)).await {
match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
Ok(s) => {
let _ = s.set_nodelay(true);
return Ok(s);
@@ -495,7 +429,7 @@ async fn connect_with_retries(
}
if Instant::now() >= deadline {
return Err(IdeError::unavailable(format!(
"could not connect to debug adapter at {host}:{port}: {e}"
"could not connect to debug adapter on port {port}: {e}"
)));
}
tokio::time::sleep(Duration::from_millis(100)).await;
-1
Переглянути файл
@@ -55,7 +55,6 @@ pub async fn build(
) -> IdeResult<PathBuf> {
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.current_dir(cwd)
-97
Переглянути файл
@@ -1,97 +0,0 @@
//! "Listen to remote JVM" (IDEA's Remote JVM Debug in listen mode): the IDE listens,
//! the remote JVM (`-agentlib:jdwp=…,server=n,address=<ide-host>:<port>`) connects to
//! it. java-debug can only attach, so the connection is relayed: once the JVM has
//! connected, java-debug attaches to a one-shot loopback port that forwards the JDWP
//! stream (handshake included) both ways.
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::ErrorKind;
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
/// How long the relay waits for java-debug to attach once the JVM is connected.
const ATTACH_TIMEOUT: Duration = Duration::from_secs(60);
/// The address to listen on for `host`: the interface it names, or every interface when
/// it is not one of this machine's (a DNS name or a NAT address the JVM connects to).
async fn bind(host: &str, port: u16) -> IdeResult<TcpListener> {
let host = host.trim();
let host = if host.is_empty() { "0.0.0.0" } else { host.trim_start_matches('[').trim_end_matches(']') };
match TcpListener::bind((host, port)).await {
Ok(l) => Ok(l),
Err(e) if e.kind() == ErrorKind::AddrNotAvailable || e.kind() == ErrorKind::Other => {
TcpListener::bind(("0.0.0.0", port))
.await
.map_err(|e| IdeError::unavailable(format!("cannot listen on port {port}: {e}")))
}
Err(e) => Err(IdeError::unavailable(format!("cannot listen on {host}:{port}: {e}"))),
}
}
/// Waits for a JVM to connect to `host:port`, then returns a loopback port that relays
/// to it (accepts one connection). Cancelled through `cancel` while waiting.
pub async fn listen_for_jvm(host: &str, port: u16, cancel: CancellationToken) -> IdeResult<u16> {
let listener = bind(host, port).await?;
let jvm = tokio::select! {
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
accepted = listener.accept() => accepted.map_err(IdeError::from)?.0,
};
drop(listener);
let _ = jvm.set_nodelay(true);
let relay = TcpListener::bind(("127.0.0.1", 0)).await?;
let local = relay.local_addr()?.port();
tokio::spawn(relay_one(relay, jvm));
Ok(local)
}
async fn relay_one(relay: TcpListener, mut jvm: TcpStream) {
let debugger = match tokio::time::timeout(ATTACH_TIMEOUT, relay.accept()).await {
Ok(Ok((s, _))) => s,
_ => return,
};
drop(relay);
let _ = debugger.set_nodelay(true);
let mut debugger = debugger;
if let Err(e) = tokio::io::copy_bidirectional(&mut debugger, &mut jvm).await {
tracing::debug!(target: "ide_dap::jdwp", "JDWP relay closed: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::test]
async fn relays_the_jdwp_handshake_both_ways() {
let port = TcpListener::bind(("127.0.0.1", 0)).await.unwrap().local_addr().unwrap().port();
let waiting = tokio::spawn(listen_for_jvm("127.0.0.1", port, CancellationToken::new()));
// The remote JVM (`server=n`) connects to the IDE.
let mut jvm = loop {
if let Ok(s) = TcpStream::connect(("127.0.0.1", port)).await {
break s;
}
tokio::time::sleep(Duration::from_millis(20)).await;
};
let local = waiting.await.unwrap().unwrap();
// java-debug attaches to the relay and starts the handshake.
let mut debugger = TcpStream::connect(("127.0.0.1", local)).await.unwrap();
debugger.write_all(b"JDWP-Handshake").await.unwrap();
let mut buf = [0u8; 14];
jvm.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"JDWP-Handshake");
jvm.write_all(b"JDWP-Handshake").await.unwrap();
debugger.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"JDWP-Handshake");
}
#[tokio::test]
async fn waiting_is_cancellable() {
let cancel = CancellationToken::new();
let waiting = tokio::spawn(listen_for_jvm("127.0.0.1", 0, cancel.clone()));
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
let err = waiting.await.unwrap().unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
}
+16 -65
Переглянути файл
@@ -12,7 +12,6 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
pub mod jdwp;
mod session;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
@@ -46,8 +45,7 @@ pub struct LaunchConfig {
/// A `"cargo": {"args": [...], "filter": {"name", "kind"}}` entry builds with cargo
/// and launches the produced executable; `"debugServer": <port>` connects to an
/// adapter already listening on that local port (e.g. java-debug inside jdtls)
/// instead of starting one, `"debugServer": "host:port"` to one on another machine
/// (`dlv --headless`, `debugpy --listen`).
/// instead of starting one.
pub extra_json: Option<String>,
}
@@ -359,34 +357,15 @@ pub(crate) fn substitute_free_port(value: &mut Value, port: &mut impl FnMut() ->
})
}
/// Where a running adapter listens: `debugServer` of the launch arguments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DebugServer {
/// `None` for the loopback interface (an adapter inside a local process such as jdtls).
pub host: Option<String>,
pub port: u16,
}
/// Removes `debugServer` (VS Code's "connect to a running adapter" attribute) from the
/// launch arguments: a port (`4711`, `"4711"`) on this machine, or `"host:port"` /
/// `"[v6]:port"` of a remote one (`dlv --headless`, `debugpy --listen`).
pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<DebugServer>> {
/// launch arguments and returns its port.
pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<u16>> {
let Some(v) = arguments.as_object_mut().and_then(|o| o.remove("debugServer")) else { return Ok(None) };
let invalid = || IdeError::invalid(format!("invalid debugServer address: {v}"));
let port_of = |p: u64| u16::try_from(p).ok().filter(|p| *p != 0);
if let Some(p) = v.as_u64() {
return port_of(p).map(|port| Some(DebugServer { host: None, port })).ok_or_else(invalid);
let port = v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()));
match port.and_then(|p| u16::try_from(p).ok()).filter(|p| *p != 0) {
Some(p) => Ok(Some(p)),
None => Err(IdeError::invalid(format!("invalid debugServer port: {v}"))),
}
let s = v.as_str().map(str::trim).ok_or_else(invalid)?;
let (host, port) = match s.rsplit_once(':') {
Some((host, port)) => {
let host = host.trim().trim_start_matches('[').trim_end_matches(']');
(Some(host).filter(|h| !h.is_empty()).map(str::to_owned), port)
}
None => (None, s),
};
let port = port.trim().parse::<u64>().ok().and_then(port_of).ok_or_else(invalid)?;
Ok(Some(DebugServer { host, port }))
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
@@ -543,17 +522,6 @@ impl DebugManager {
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
pub async fn start(&self, config: LaunchConfig, owner: SessionOwner) -> IdeResult<DebugSessionId> {
self.start_with(config, owner, |_| None).await
}
/// [`start`](Self::start) with the adapter executable chosen by `custom_command`
/// (the configured command → a user-chosen executable, from settings).
pub async fn start_with(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
let cwd = config
.cwd
@@ -563,9 +531,6 @@ impl DebugManager {
let dbg = adapter::find_config(&self.languages, &config.adapter)
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
let mut spec = adapter::resolve(&dbg, cwd.clone());
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy).
if config.adapter == "debugpy" {
let python = match arguments.get("python") {
@@ -579,9 +544,6 @@ impl DebugManager {
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
spec.server_host = server.host.clone();
}
if let Some(cargo) = arguments.as_object_mut().and_then(|o| o.remove("cargo")) {
let cargo_args: Vec<String> = cargo
.get("args")
@@ -620,19 +582,11 @@ impl DebugManager {
if config.adapter == "js-debug" && arguments.get("__workspaceFolder").is_none() {
arguments["__workspaceFolder"] = json!(cwd);
}
// Godot compares `project` with its own (resolved) project path: `/tmp/game` is
// rejected by an editor that opened `/private/tmp/game`.
if config.adapter == "godot"
&& let Some(project) = arguments.get("project").and_then(Value::as_str)
&& let Ok(real) = std::fs::canonicalize(project)
{
arguments["project"] = json!(real);
}
if config.adapter == "codelldb" && arguments.get("sourceLanguages").is_none() {
arguments["sourceLanguages"] = json!(["rust"]);
}
let port = debug_server.map(|s| s.port);
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, debug_server)
.await
}
/// `startDebugging` reverse request: a child session on the same adapter.
@@ -992,8 +946,8 @@ impl DebugManager {
}
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
let session = self.session(s)?;
let body = session
let body = self
.session(s)?
.conn
.request_timeout(
"stackTrace",
@@ -1001,14 +955,11 @@ impl DebugManager {
REQUEST_TIMEOUT,
)
.await?;
let frame = |f: &Value| {
let mut frame = frame_from(f);
if let Some(client) = frame.path.as_deref().and_then(|p| session.client_path(&p.to_string_lossy())) {
frame.path = Some(client.into());
}
frame
};
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
Ok(body
.get("stackFrames")
.and_then(Value::as_array)
.map(|f| f.iter().map(frame_from).collect())
.unwrap_or_default())
}
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
+3 -40
Переглянути файл
@@ -51,16 +51,9 @@ pub(crate) struct Session {
pub pending_restore: Mutex<PendingRestore>,
/// Adapter breakpoint id → (file, index in the stored list).
pub breakpoint_ids: Mutex<HashMap<i64, (PathBuf, usize)>>,
/// Resolved path → the path as the IDE knows it, for adapters given resolved paths.
resolved_paths: Mutex<HashMap<PathBuf, PathBuf>>,
progress: Mutex<HashMap<String, TaskId>>,
}
/// Adapters that only match files by their resolved path: Godot maps a script to
/// `res://` by prefix and silently never stops at a breakpoint set through a
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -93,7 +86,6 @@ impl Session {
terminated: AtomicBool::new(false),
pending_restore: Mutex::default(),
breakpoint_ids: Mutex::new(HashMap::new()),
resolved_paths: Mutex::new(HashMap::new()),
progress: Mutex::new(HashMap::new()),
}
}
@@ -102,25 +94,6 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if !RESOLVES_PATHS.contains(&self.adapter.as_str()) {
return path.to_path_buf();
}
match std::fs::canonicalize(path) {
Ok(real) if real != path => {
self.resolved_paths.lock().insert(real.clone(), path.to_path_buf());
real
}
_ => path.to_path_buf(),
}
}
/// A path from the adapter as the IDE knows it (undoes [`Session::adapter_path`]).
pub fn client_path(&self, path: &str) -> Option<PathBuf> {
self.resolved_paths.lock().get(Path::new(path)).cloned()
}
pub fn supports(&self, cap: &str) -> bool {
self.caps.lock().get(cap).and_then(Value::as_bool).unwrap_or(false)
}
@@ -162,7 +135,7 @@ impl Session {
.request_timeout(
"setBreakpoints",
json!({
"source": { "path": self.adapter_path(path), "name": name },
"source": { "path": path, "name": name },
"breakpoints": source_bps,
"sourceModified": false,
}),
@@ -338,11 +311,7 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, body:
s.emit(DebugEvent::BreakpointsChanged { path: path.into() });
}
}
// Godot repeats `exited` / `terminated` when the client disconnects afterwards.
"exited" if !s.terminated.load(Ordering::Acquire) => {
s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 })
}
"exited" => {}
"exited" => s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 }),
"terminated" => {
if !s.terminated.swap(true, Ordering::AcqRel) {
s.emit(DebugEvent::Terminated);
@@ -421,13 +390,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
return Err("runInTerminal without args".into());
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
}
+2 -180
Переглянути файл
@@ -597,23 +597,14 @@ async fn sessions_deliver_events_to_their_owner_only() {
#[test]
fn debug_server_is_taken_from_launch_arguments() {
let local = |port| Some(DebugServer { host: None, port });
let remote = |host: &str, port| Some(DebugServer { host: Some(host.into()), port });
let mut args = json!({"name": "x", "debugServer": 4711, "mainClass": "a.B"});
assert_eq!(take_debug_server(&mut args).unwrap(), local(4711));
assert_eq!(take_debug_server(&mut args).unwrap(), Some(4711));
assert!(args.get("debugServer").is_none());
assert_eq!(args["mainClass"], "a.B");
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), local(5005));
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), Some(5005));
assert_eq!(take_debug_server(&mut json!({"name": "x"})).unwrap(), None);
// A remote adapter: `dlv --headless --listen=:2345`, `debugpy --listen 0.0.0.0:5678`.
assert_eq!(take_debug_server(&mut json!({"debugServer": "build-box:2345"})).unwrap(), remote("build-box", 2345));
assert_eq!(take_debug_server(&mut json!({"debugServer": "10.0.0.7:5678"})).unwrap(), remote("10.0.0.7", 5678));
assert_eq!(take_debug_server(&mut json!({"debugServer": "[::1]:2345"})).unwrap(), remote("::1", 2345));
assert_eq!(take_debug_server(&mut json!({"debugServer": ":2345"})).unwrap(), local(2345));
assert!(take_debug_server(&mut json!({"debugServer": 0})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": 70000})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": "host:"})).is_err());
assert!(take_debug_server(&mut json!({"debugServer": "host:abc"})).is_err());
}
#[test]
@@ -705,41 +696,6 @@ async fn connects_to_running_debug_server_over_tcp() {
assert!(events.lock().iter().any(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Started { .. }, .. })));
}
/// Go Remote / Python remote: the adapter runs on another machine (`dlv --headless`,
/// `debugpy --listen`); `debugServer: "host:port"` connects there instead of spawning one.
#[tokio::test]
async fn connects_to_remote_debug_server_by_host() {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let config = LaunchConfig {
name: "Remote".into(),
adapter: "delve".into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(std::env::temp_dir().into()),
env: BTreeMap::new(),
extra_json: Some(
json!({"debugServer": format!("localhost:{port}"), "mode": "remote", "substitutePath": [{"from": "/src", "to": "/app"}]})
.to_string(),
),
};
let id = manager.start(config, owner).await.unwrap();
let attach = log.lock().iter().find(|m| m["command"] == "attach").cloned().unwrap();
assert_eq!(attach["arguments"]["mode"], "remote");
assert_eq!(attach["arguments"]["substitutePath"][0]["to"], "/app");
assert!(attach["arguments"].get("debugServer").is_none(), "consumed by the client");
manager.stop(id).await.unwrap();
}
fn requests(h: &Harness, command: &str) -> Vec<Value> {
h.log
.lock()
@@ -881,137 +837,3 @@ async fn hot_swap_only_for_java_debug() {
let failed = hot_swap_result(&json!({"changedClasses": [], "errorMessage": "boom"}));
assert_eq!(failed.error_message.as_deref(), Some("boom"));
}
fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegistry> {
let lang = ide_language::LanguageConfig {
id: ide_core::LanguageId::new("gdscript"),
name: "GDScript".into(),
extensions: vec!["gd".into()],
filenames: vec![],
first_line: None,
line_comment: None,
block_comment: None,
indent: None,
ui_mode: None,
tree_sitter: None,
language_servers: vec![],
debugger: Some(ide_language::DebuggerConfig {
adapter: "godot".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: "tcp".into(),
connect: Some(format!("127.0.0.1:{port}")),
install_hint: Some("Open the project in the Godot editor".into()),
}),
};
Arc::new(LanguageRegistry::from_configs(vec![lang]))
}
fn godot_launch(project: &std::path::Path) -> LaunchConfig {
LaunchConfig {
name: "Main Scene".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(project.to_path_buf().into()),
env: BTreeMap::new(),
extra_json: Some(json!({"project": project, "scene": "main"}).to_string()),
}
}
/// Godot's debug adapter runs inside the editor (port 6006): an open editor is
/// used as is, nothing is started.
#[tokio::test]
async fn godot_connects_to_the_editor_adapter() {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let project = std::env::temp_dir();
let id = manager.start(godot_launch(&project), owner).await.unwrap();
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["scene"], "main");
assert_eq!(launch["arguments"]["project"], json!(std::fs::canonicalize(&project).unwrap()));
assert!(log.lock().iter().any(|m| m["command"] == "configurationDone"));
manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn godot_without_editor_or_executable_says_what_to_do() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let err = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.contains("Open the project in the Godot editor"), "{}", err.message);
}
/// No editor open: the command (a headless editor) is started for the project and
/// the client connects once it listens; the started process ends with the session.
#[cfg(unix)]
#[tokio::test]
async fn godot_starts_a_headless_editor_when_none_is_open() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
// `sleep` stands in for `godot --headless --editor --path ${root} …`.
let manager = DebugManager::new(godot_registry(port, "sleep", &["30"]));
let id = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap();
assert!(log.lock().iter().any(|m| m["command"] == "launch"));
manager.stop(id).await.unwrap();
}
/// Godot never stops at a breakpoint given through a symlinked path (it maps scripts
/// to `res://` by its resolved project path): breakpoints and `project` go out resolved.
#[cfg(unix)]
#[tokio::test]
async fn godot_gets_resolved_paths() {
let real = std::env::temp_dir().join(format!("openidea-godot-real-{}", std::process::id()));
let link = std::env::temp_dir().join(format!("openidea-godot-link-{}", std::process::id()));
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("player.gd"), "extends Node\n").unwrap();
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&real, &link).unwrap();
let real = std::fs::canonicalize(&real).unwrap();
let log: Log = Arc::default();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::with_launcher(
godot_registry(1, "godot", &[]),
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
);
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
let id = manager.start(godot_launch(&link), owner).await.unwrap();
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["project"], json!(real));
manager.stop(id).await.unwrap();
std::fs::remove_file(&link).ok();
std::fs::remove_dir_all(&real).ok();
}
#[test]
fn root_and_address_placeholders() {
let args: Vec<String> = ["--path", "${root}", "--dap-port", "${port}"].iter().map(|s| s.to_string()).collect();
let args = adapter::substitute_port(&adapter::substitute_root(&args, std::path::Path::new("/g")), 6010);
assert_eq!(args, ["--path", "/g", "--dap-port", "6010"]);
assert_eq!(adapter::parse_address("127.0.0.1:6006"), Some(("127.0.0.1".into(), 6006)));
assert_eq!(adapter::parse_address("[::1]:6006"), Some(("::1".into(), 6006)));
assert_eq!(adapter::parse_address("6006"), None);
}
-157
Переглянути файл
@@ -1,157 +0,0 @@
//! Drives Godot's debug adapter (inside the Godot editor) with the GDScript
//! language definition: a headless editor is started for the project, the main
//! scene is played, a breakpoint hits, stack / variables / stepping work, and the
//! game and the editor end with the session.
//!
//! Ignored by default (needs Godot 4). Run with
//! `GODOT_BIN=<godot executable> cargo test -p ide-dap --test godot -- --ignored --nocapture`.
use ide_core::event::DebugEvent;
use ide_core::{IdeEvent, SharedSink};
use ide_dap::*;
use ide_language::{LanguageConfig, LanguageRegistry};
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
const SCRIPT: &str = "extends Node
var health: int = 3
func _ready() -> void:
\tvar total := add(2, 3)
\tprint(\"total = \", total)
\thealth -= 1
\tget_tree().quit()
func add(a: int, b: int) -> int:
\treturn a + b
";
/// 0-based line of `return a + b`.
const BREAK_LINE: u32 = 11;
fn project(dir: &Path) {
std::fs::write(
dir.join("project.godot"),
"config_version=5\n\n[application]\nconfig/name=\"Probe\"\nrun/main_scene=\"res://main.tscn\"\n",
)
.unwrap();
std::fs::write(
dir.join("main.tscn"),
"[gd_scene load_steps=2 format=3]\n\n[ext_resource type=\"Script\" path=\"res://player.gd\" id=\"1\"]\n\n[node name=\"Main\" type=\"Node\"]\nscript = ExtResource(\"1\")\n",
)
.unwrap();
std::fs::write(dir.join("player.gd"), SCRIPT).unwrap();
}
/// The built-in GDScript definition, with the editor's usual port moved aside so an
/// open editor can't answer instead of the one this test starts.
fn registry() -> Arc<LanguageRegistry> {
let builtin = LanguageRegistry::load(None).unwrap();
let mut gd: LanguageConfig = builtin.get(&ide_core::LanguageId::new("gdscript")).unwrap();
let dbg = gd.debugger.as_mut().unwrap();
let unused = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
dbg.connect = Some(format!("127.0.0.1:{unused}"));
Arc::new(LanguageRegistry::from_configs(vec![gd]))
}
async fn wait_for(events: &Mutex<Vec<IdeEvent>>, timeout: Duration, pred: impl Fn(&DebugEvent) -> bool) -> DebugEvent {
let start = Instant::now();
loop {
if let Some(e) = events.lock().iter().find_map(|e| match e {
IdeEvent::Debug { event, .. } if pred(event) => Some(event.clone()),
_ => None,
}) {
return e;
}
assert!(start.elapsed() < timeout, "timed out; events: {:#?}", events.lock());
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
fn godot_processes(project: &Path) -> usize {
let out = std::process::Command::new("pgrep").args(["-f", &project.to_string_lossy()]).output().unwrap();
String::from_utf8_lossy(&out.stdout).lines().count()
}
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn breakpoints_stepping_and_variables_in_a_real_godot() {
let Ok(godot) = std::env::var("GODOT_BIN") else {
eprintln!("GODOT_BIN not set; skipping");
return;
};
let dir = std::env::temp_dir().join(format!("openidea-godot-dap-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let root = std::fs::canonicalize(&dir).unwrap();
project(&root);
let manager = DebugManager::new(registry());
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let script_as_opened = dir.join("player.gd");
manager
.set_breakpoints(
script_as_opened.clone(),
vec![Breakpoint {
line: BREAK_LINE,
condition: None,
hit_condition: None,
log_message: None,
enabled: true,
}],
)
.await
.unwrap();
// As the UI builds it for "Godot Project" (`godot --path .`).
let config = LaunchConfig {
name: "Godot Project".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
// The project as opened, through a symlink on macOS (`/var` → `/private/var`).
cwd: Some(dir.clone().into()),
env: BTreeMap::new(),
extra_json: Some(serde_json::json!({ "project": dir, "scene": "main" }).to_string()),
};
let id = manager
.start_with(config, SessionOwner::new("main", sink), |_| Some(godot.clone()))
.await
.unwrap_or_else(|e| panic!("start: {e:?}"));
let stopped = wait_for(&events, Duration::from_secs(120), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!(frames[0].name, "add");
assert_eq!(frames[0].line, BREAK_LINE);
// Frames name the file as the IDE opened it, not Godot's resolved path.
assert_eq!(frames[0].path.as_deref().map(Path::new), Some(script_as_opened.as_path()));
assert_eq!(frames[1].name, "_ready");
let scopes = manager.scopes(id, frames[0].id).await.unwrap();
let locals = scopes.iter().find(|s| s.name == "Locals").expect("Locals scope");
let vars = manager.variables(id, locals.variables_reference).await.unwrap();
let value = |n: &str| vars.iter().find(|v| v.name == n).map(|v| v.value.clone());
assert_eq!((value("a").as_deref(), value("b").as_deref()), (Some("2"), Some("3")), "{vars:?}");
events.lock().clear();
manager.step(id, thread_id, StepKind::Over).await.unwrap();
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!((frames[0].name.as_str(), frames[0].line), ("_ready", 6), "stepped back into `_ready`, at the print");
manager.resume(id, thread_id).await.unwrap();
// (The game's last output is not always forwarded when it quits right away.)
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Terminated)).await;
let _ = manager.stop(id).await;
// The headless editor started for the session ends with it, the game too.
let start = Instant::now();
while godot_processes(&root) > 0 {
assert!(start.elapsed() < Duration::from_secs(10), "Godot still running for {}", root.display());
tokio::time::sleep(Duration::from_millis(200)).await;
}
std::fs::remove_dir_all(&root).ok();
}
+19 -235
Переглянути файл
@@ -15,8 +15,7 @@ use sqlx::{
postgres::{PgConnectOptions, PgPool, PgPoolOptions, PgSslMode},
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::path::Path;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -40,8 +39,6 @@ pub struct QueryResult {
/// More rows exist beyond the limit.
pub has_more: bool,
pub elapsed_ms: f64,
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
pub execution_ms: f64,
}
pub enum Pool {
@@ -132,9 +129,7 @@ macro_rules! fetch {
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut failure = None;
let mut first: Option<Instant> = None;
while let Some(item) = stream.next().await {
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()),
Ok(sqlx::Either::Right(row)) => {
@@ -156,13 +151,12 @@ macro_rules! fetch {
drop(stream);
match failure {
Some(e) => Err(e),
None => Ok((columns, rows, affected, has_more, first)),
None => Ok((columns, rows, affected, has_more)),
}
}};
}
/// Columns, rows, rows affected, more rows beyond the limit, time of the first answer.
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool, Option<Instant>);
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool);
/// The server-side id of a connection (to cancel its statement from another one).
macro_rules! backend_id {
@@ -190,90 +184,6 @@ fn looks_like_query(sql: &str) -> bool {
)
}
fn file_setting(path: &str) -> Option<PathBuf> {
let path = path.trim();
(!path.is_empty()).then(|| crate::tunnel::expand(path))
}
fn is_identifier(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
}
/// A MySQL `SET` value: numbers and keywords as they are, anything else quoted.
fn mysql_value(v: &str) -> String {
let keyword = ["ON", "OFF", "TRUE", "FALSE", "DEFAULT"].iter().any(|k| k.eq_ignore_ascii_case(v));
if keyword || v.parse::<f64>().is_ok() {
v.to_owned()
} else {
format!("'{}'", v.replace('\\', "\\\\").replace('\'', "''"))
}
}
/// How the Options and Advanced tabs reach a connection.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Setup {
/// PostgreSQL run-time parameters (startup `options`), SQLite pragmas.
pub params: Vec<(String, String)>,
/// Run on every new connection: MySQL session settings, then the startup script.
pub statements: Vec<String>,
pub application_name: Option<String>,
pub charset: Option<String>,
pub collation: Option<String>,
pub statement_cache: Option<usize>,
pub connect_timeout: Option<Duration>,
}
impl Setup {
pub fn of(source: &DataSource) -> IdeResult<Self> {
let mut s = Setup::default();
let o = &source.options;
match source.driver {
DbDriver::Postgres => {
if source.read_only {
s.params.push(("default_transaction_read_only".into(), "on".into()));
}
if !o.default_schema.trim().is_empty() {
s.params.push(("search_path".into(), o.default_schema.trim().into()));
}
if !o.time_zone.trim().is_empty() {
s.params.push(("TimeZone".into(), o.time_zone.trim().into()));
}
}
DbDriver::Mysql if source.read_only => s.statements.push("SET SESSION TRANSACTION READ ONLY".into()),
_ => {}
}
for p in &source.properties {
let value = p.value.trim();
let name = p.name.trim().replace('-', "_");
if name.is_empty() {
continue;
}
if !is_identifier(&name) {
return Err(IdeError::invalid(format!("invalid driver property name: {}", p.name.trim())));
}
let number = |what: &str| {
value.parse::<u64>().map_err(|_| IdeError::invalid(format!("{what} must be a whole number: {value}")))
};
match (source.driver, name.to_ascii_lowercase().as_str()) {
(_, "statement_cache_capacity") => s.statement_cache = Some(number(&name)? as usize),
(_, "connect_timeout") => s.connect_timeout = Some(Duration::from_secs(number(&name)?)),
(DbDriver::Postgres, "application_name") => s.application_name = Some(value.to_owned()),
(DbDriver::Mysql, "charset") => s.charset = Some(value.to_owned()),
(DbDriver::Mysql, "collation") => s.collation = Some(value.to_owned()),
(DbDriver::Mysql, _) => s.statements.push(format!("SET SESSION {name} = {}", mysql_value(value))),
_ => s.params.push((name, value.to_owned())),
}
}
let script = o.startup_script.trim();
if !script.is_empty() {
s.statements.extend(crate::split::split(script, source.driver).into_iter().map(|st| st.text));
}
Ok(s)
}
}
impl Pool {
pub fn driver(&self) -> DbDriver {
match self {
@@ -286,24 +196,7 @@ impl Pool {
/// Opens a pool and one connection (so bad settings fail here).
pub async fn connect(source: &DataSource, password: Option<&str>, root: Option<&Path>) -> IdeResult<Self> {
const MAX: u32 = 4;
let setup = Setup::of(source)?;
let timeout = setup.connect_timeout.unwrap_or(Duration::from_secs(30));
let init = Arc::new(setup.statements);
// Runs the session statements (startup script…) on every new connection.
macro_rules! after_connect {
() => {{
let init = init.clone();
move |conn, _| {
let init = init.clone();
Box::pin(async move {
for sql in init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
}
Ok(())
})
}
}};
}
let timeout = Duration::from_secs(30);
match source.driver {
DbDriver::Sqlite => {
let file = source.file.as_deref().ok_or_else(|| IdeError::invalid("no database file"))?;
@@ -311,18 +204,11 @@ impl Pool {
Some(r) if file.is_relative() => r.join(file),
_ => file.to_path_buf(),
};
let mut opts =
let opts =
SqliteConnectOptions::new().filename(&file).create_if_missing(false).read_only(source.read_only);
for (k, v) in setup.params {
opts = opts.pragma(k, v);
}
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let pool = SqlitePoolOptions::new()
.max_connections(MAX)
.acquire_timeout(timeout)
.after_connect(after_connect!())
.connect_with(opts)
.await
.map_err(db_err)?;
@@ -333,39 +219,24 @@ impl Pool {
.host(&source.host)
.port(source.port.unwrap_or(5432))
.username(&source.user)
.application_name(setup.application_name.as_deref().unwrap_or("OpenIDEA"))
.application_name("OpenIDEA")
.ssl_mode(match source.ssl {
DbSslMode::Disable => PgSslMode::Disable,
DbSslMode::Prefer => PgSslMode::Prefer,
DbSslMode::Require => PgSslMode::Require,
DbSslMode::VerifyCa => PgSslMode::VerifyCa,
DbSslMode::VerifyFull => PgSslMode::VerifyFull,
});
if let Some(f) = file_setting(&source.ssl_ca_file) {
opts = opts.ssl_root_cert(f);
}
if let Some(f) = file_setting(&source.ssl_cert_file) {
opts = opts.ssl_client_cert(f);
}
if let Some(f) = file_setting(&source.ssl_key_file) {
opts = opts.ssl_client_key(f);
}
if !source.database.is_empty() {
opts = opts.database(&source.database);
}
if let Some(p) = password {
opts = opts.password(p);
}
if !setup.params.is_empty() {
opts = opts.options(setup.params);
}
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
if source.read_only {
opts = opts.options([("default_transaction_read_only", "on")]);
}
let pool = PgPoolOptions::new()
.max_connections(MAX)
.acquire_timeout(timeout)
.after_connect(after_connect!())
.connect_with(opts)
.await
.map_err(db_err)?;
@@ -380,41 +251,25 @@ impl Pool {
DbSslMode::Disable => MySqlSslMode::Disabled,
DbSslMode::Prefer => MySqlSslMode::Preferred,
DbSslMode::Require => MySqlSslMode::Required,
DbSslMode::VerifyCa => MySqlSslMode::VerifyCa,
DbSslMode::VerifyFull => MySqlSslMode::VerifyIdentity,
});
if let Some(f) = file_setting(&source.ssl_ca_file) {
opts = opts.ssl_ca(f);
}
if let Some(f) = file_setting(&source.ssl_cert_file) {
opts = opts.ssl_client_cert(f);
}
if let Some(f) = file_setting(&source.ssl_key_file) {
opts = opts.ssl_client_key(f);
}
if !source.database.is_empty() {
opts = opts.database(&source.database);
}
if let Some(p) = password {
opts = opts.password(p);
}
if let Some(c) = &setup.charset {
opts = opts.charset(c);
}
if let Some(c) = &setup.collation {
opts = opts.collation(c);
}
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let tz = source.options.time_zone.trim();
if !tz.is_empty() {
opts = opts.timezone(Some(tz.to_owned()));
}
let read_only = source.read_only;
let pool = MySqlPoolOptions::new()
.max_connections(MAX)
.acquire_timeout(timeout)
.after_connect(after_connect!())
.after_connect(move |conn, _| {
Box::pin(async move {
if read_only {
conn.execute("SET SESSION TRANSACTION READ ONLY").await?;
}
Ok(())
})
})
.connect_with(opts)
.await
.map_err(db_err)?;
@@ -427,10 +282,6 @@ impl Pool {
with_pool!(self, p => p.close().await)
}
pub fn is_closed(&self) -> bool {
with_pool!(self, p => p.is_closed())
}
/// Runs `sql` (no row limit beyond `max`), for introspection.
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
let fetched: IdeResult<Fetched> = with_pool!(self, p => fetch!(p, sql, max));
@@ -557,16 +408,14 @@ impl Held {
}
Held::Mysql(c) => run!(c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
};
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
let (columns, rows, affected, has_more) = fetched;
Ok(QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
})
}
}
@@ -585,68 +434,3 @@ fn statement_columns<S: sqlx::Statement>(s: &S) -> Vec<ResultColumn> {
.map(|c| ResultColumn { name: c.name().to_owned(), type_name: c.type_info().name().to_owned() })
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::{DbOptions, DbProperty};
fn prop(name: &str, value: &str) -> DbProperty {
DbProperty { name: name.into(), value: value.into() }
}
#[test]
fn postgres_options_become_runtime_parameters() {
let s = DataSource {
driver: DbDriver::Postgres,
read_only: true,
options: DbOptions {
default_schema: "app, public".into(),
time_zone: "Europe/Paris".into(),
startup_script: "SET work_mem = '64MB'; select 1;".into(),
..Default::default()
},
properties: vec![prop("statement_timeout", "5s"), prop("application_name", "me"), prop("", "x")],
..Default::default()
};
let setup = Setup::of(&s).unwrap();
let names: Vec<_> = setup.params.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(names, ["default_transaction_read_only", "search_path", "TimeZone", "statement_timeout"]);
assert_eq!(setup.application_name.as_deref(), Some("me"));
assert_eq!(setup.statements, ["SET work_mem = '64MB'", "select 1"]);
}
#[test]
fn mysql_properties_become_session_variables() {
let s = DataSource {
driver: DbDriver::Mysql,
read_only: true,
properties: vec![
prop("sql_mode", "ANSI_QUOTES"),
prop("max_execution_time", "1000"),
prop("charset", "utf8mb4"),
prop("connect-timeout", "5"),
],
..Default::default()
};
let setup = Setup::of(&s).unwrap();
assert_eq!(
setup.statements,
[
"SET SESSION TRANSACTION READ ONLY",
"SET SESSION sql_mode = 'ANSI_QUOTES'",
"SET SESSION max_execution_time = 1000"
]
);
assert_eq!(setup.charset.as_deref(), Some("utf8mb4"));
assert_eq!(setup.connect_timeout, Some(Duration::from_secs(5)));
assert!(Setup::of(&DataSource { properties: vec![prop("a; drop", "1")], ..s.clone() }).is_err());
assert!(Setup::of(&DataSource { properties: vec![prop("connect_timeout", "soon")], ..s }).is_err());
}
#[test]
fn sqlite_properties_become_pragmas() {
let s = DataSource { properties: vec![prop("cache_size", "-2000")], ..Default::default() };
assert_eq!(Setup::of(&s).unwrap().params, [("cache_size".to_owned(), "-2000".to_owned())]);
}
}
-137
Переглянути файл
@@ -1,137 +0,0 @@
//! Query history (IDEA's Browse Query History): the statements each data
//! source ran, newest first. One JSON file in the app's data directory for all
//! projects, keyed by project root, then data source id — never committed.
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Statements kept per data source.
pub const MAX_ENTRIES: usize = 500;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbHistoryEntry")]
pub struct HistoryEntry {
pub text: String,
/// Milliseconds since the Unix epoch.
pub time: f64,
}
/// Project root → data source id → entries, newest first.
type Contents = BTreeMap<String, BTreeMap<String, Vec<HistoryEntry>>>;
/// Serialises read-modify-write across the projects sharing the file.
static LOCK: Mutex<()> = Mutex::new(());
pub struct HistoryStore {
path: PathBuf,
project: String,
}
impl HistoryStore {
pub fn new(path: PathBuf, root: &Path) -> Self {
Self { path, project: root.to_string_lossy().into_owned() }
}
pub fn list(&self, source: &str) -> Vec<HistoryEntry> {
let _g = LOCK.lock();
self.read().remove(&self.project).and_then(|mut p| p.remove(source)).unwrap_or_default()
}
/// Records `text`; running a statement again moves it to the top.
pub fn add(&self, source: &str, text: &str, time: f64) -> IdeResult<()> {
let text = text.trim();
if text.is_empty() {
return Ok(());
}
let _g = LOCK.lock();
let mut all = self.read();
let entries = all.entry(self.project.clone()).or_default().entry(source.to_owned()).or_default();
entries.retain(|e| e.text != text);
entries.insert(0, HistoryEntry { text: text.to_owned(), time });
entries.truncate(MAX_ENTRIES);
self.write(&all)
}
/// Removes the entries with these texts (all of them for `None`).
pub fn remove(&self, source: &str, texts: Option<&[String]>) -> IdeResult<()> {
let _g = LOCK.lock();
let mut all = self.read();
let Some(project) = all.get_mut(&self.project) else { return Ok(()) };
match texts {
None => {
project.remove(source);
}
Some(texts) => {
if let Some(entries) = project.get_mut(source) {
entries.retain(|e| !texts.contains(&e.text));
}
}
}
self.write(&all)
}
fn read(&self) -> Contents {
match std::fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("query history: {}: {e}", self.path.display());
Contents::new()
}),
Err(_) => Contents::new(),
}
}
fn write(&self, all: &Contents) -> IdeResult<()> {
let err = |e: std::io::Error| IdeError::unavailable(format!("query history: {e}"));
if let Some(dir) = self.path.parent() {
std::fs::create_dir_all(dir).map_err(err)?;
}
let tmp = self.path.with_extension("json.tmp");
let bytes = serde_json::to_vec(all).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(&tmp, bytes).map_err(err)?;
std::fs::rename(&tmp, &self.path).map_err(err)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_newest_first_without_duplicates_per_project_and_source() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("h.json");
let a = HistoryStore::new(file.clone(), Path::new("/p/a"));
let b = HistoryStore::new(file, Path::new("/p/b"));
a.add("s1", "select 1", 1.0).unwrap();
a.add("s1", " select 2 ", 2.0).unwrap();
a.add("s1", "select 1", 3.0).unwrap();
a.add("s2", "select 3", 4.0).unwrap();
b.add("s1", "select 4", 5.0).unwrap();
let texts = |v: Vec<HistoryEntry>| v.into_iter().map(|e| e.text).collect::<Vec<_>>();
assert_eq!(texts(a.list("s1")), ["select 1", "select 2"]);
assert_eq!(texts(a.list("s2")), ["select 3"]);
assert_eq!(texts(b.list("s1")), ["select 4"]);
a.remove("s1", Some(&["select 2".to_owned()])).unwrap();
assert_eq!(texts(a.list("s1")), ["select 1"]);
a.remove("s1", None).unwrap();
assert!(a.list("s1").is_empty());
assert_eq!(texts(b.list("s1")), ["select 4"]);
}
#[test]
fn caps_entries() {
let dir = tempfile::tempdir().unwrap();
let h = HistoryStore::new(dir.path().join("h.json"), Path::new("/p"));
for i in 0..MAX_ENTRIES + 5 {
h.add("s", &format!("select {i}"), i as f64).unwrap();
}
let list = h.list("s");
assert_eq!(list.len(), MAX_ENTRIES);
assert_eq!(list[0].text, format!("select {}", MAX_ENTRIES + 4));
}
}
+18 -256
Переглянути файл
@@ -3,8 +3,6 @@
//! and statement splitting ([`split`]), for SQLite, PostgreSQL and MySQL/MariaDB.
pub mod conn;
pub mod history;
pub mod plan;
pub mod secrets;
pub mod source;
pub mod split;
@@ -12,14 +10,9 @@ pub mod sql;
pub mod tunnel;
pub use conn::{Held, Pool, QueryResult, ResultColumn};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
};
pub use source::{DataSource, DbDriver, DbSsh, DbSshAuth, DbSslMode};
pub use sql::{CellValue, DbRowEdit, SortKey};
use history::HistoryStore;
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use secrets::SecretStore;
@@ -28,7 +21,6 @@ use specta::Type;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tunnel::{OpenError, Tunnel, TunnelSpec, UnknownHostKey};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -36,67 +28,6 @@ use tunnel::{OpenError, Tunnel, TunnelSpec, UnknownHostKey};
pub enum DbTableKind {
Table,
View,
MaterializedView,
}
impl DbTableKind {
fn from_catalog(kind: Option<&str>) -> Self {
match kind {
Some("view") => Self::View,
Some("materialized view") => Self::MaterializedView,
_ => Self::Table,
}
}
}
/// Schema objects other than tables and columns (Go to DDL, Drop).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbObjectKind {
Function,
Procedure,
Trigger,
Sequence,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTriggerInfo")]
pub struct TriggerInfo {
pub name: String,
/// `before`, `after`, `instead of`.
pub timing: String,
/// `insert`, `update or delete`…
pub events: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbRoutineInfo")]
pub struct RoutineInfo {
pub name: String,
/// `Function` or `Procedure`.
pub kind: DbObjectKind,
pub arguments: String,
/// Result type of a function.
pub returns: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSequenceInfo")]
pub struct SequenceInfo {
pub name: String,
pub data_type: String,
}
/// A schema's routines and sequences (the tree's `routines` / `sequences` folders).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbSchemaObjects")]
pub struct SchemaObjects {
pub routines: Vec<RoutineInfo>,
pub sequences: Vec<SequenceInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -134,7 +65,6 @@ pub struct TableDetails {
pub columns: Vec<ColumnInfo>,
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
pub triggers: Vec<TriggerInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -215,7 +145,6 @@ pub struct DbManager {
known_hosts: PathBuf,
ssh_config: Option<PathBuf>,
saved_passwords: SecretStore,
history: Arc<HistoryStore>,
/// Passwords entered this session (not saved, or not yet), by credential key.
session_passwords: Mutex<HashMap<String, String>>,
/// Manual-commit data sources, each with the connection of its open
@@ -290,24 +219,6 @@ fn through_tunnel(e: IdeError, source: &DataSource, tunneled: bool) -> IdeError
)
}
/// Options › Run keep-alive query: pings the pool until it is closed or dropped
/// (a dropped SSH tunnel or an idle-killing proxy stays alive meanwhile).
fn keep_alive(pool: &Arc<Pool>, every: Duration) {
let pool = Arc::downgrade(pool);
tokio::spawn(async move {
let mut tick = tokio::time::interval(every);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
tick.tick().await;
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.rows("SELECT 1", 1).await {
tracing::debug!("keep-alive: {}", e.message);
}
}
});
}
/// Rolls back a session's transaction and releases its connection.
async fn end_session(session: &Session) {
let held = session.lock().await.take();
@@ -319,24 +230,21 @@ async fn end_session(session: &Session) {
}
impl DbManager {
/// `passwords` / `history` are the app-wide files of saved passwords
/// ([`SecretStore`]) and query history ([`HistoryStore`]).
pub fn new(root: PathBuf, passwords: PathBuf, history: PathBuf) -> Self {
/// `passwords` is the app-wide file of saved passwords ([`SecretStore`]).
pub fn new(root: PathBuf, passwords: PathBuf) -> Self {
let ssh_dir = dirs::home_dir().unwrap_or_default().join(".ssh");
Self::with_ssh_files(root, passwords, history, ssh_dir.join("known_hosts"), Some(ssh_dir.join("config")))
Self::with_ssh_files(root, passwords, ssh_dir.join("known_hosts"), Some(ssh_dir.join("config")))
}
/// [`DbManager::new`] with other `known_hosts` / `~/.ssh/config` files (tests).
pub fn with_ssh_files(
root: PathBuf,
passwords: PathBuf,
history: PathBuf,
known_hosts: PathBuf,
ssh_config: Option<PathBuf>,
) -> Self {
Self {
saved_passwords: SecretStore::new(passwords, &root),
history: Arc::new(HistoryStore::new(history, &root)),
root,
pools: Mutex::default(),
tunnels: Mutex::default(),
@@ -353,16 +261,14 @@ impl DbManager {
source::load(&self.root)
}
/// The connection settings of target `target` ([`DataSource::resolved`]), with
/// its database for `<id>:<database>`.
/// The data source of connection target `target`, with its database for `<id>:<database>`.
pub fn source(&self, target: &str) -> IdeResult<DataSource> {
let (id, database) = split_target(target);
let mut source = self
.sources()?
.into_iter()
.find(|s| s.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
.resolved()?;
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?;
if let Some(db) = database {
source.database = db.to_owned();
}
@@ -435,10 +341,7 @@ impl DbManager {
}
async fn password(&self, source: &DataSource) -> Option<String> {
match self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
Some(p) => Some(p),
None => source.url_password(),
}
self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await
}
/// Trusts the host key that failed the last connection of `id` (adds it to `known_hosts`).
@@ -508,7 +411,6 @@ impl DbManager {
password: Option<String>,
ssh_secret: Option<String>,
) -> IdeResult<String> {
let source = &source.resolved()?;
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
@@ -556,14 +458,9 @@ impl DbManager {
return Err(through_tunnel(e, &source, tunnel.is_some()));
}
};
let mut pools = self.pools.lock();
// Another caller may have connected meanwhile; keep theirs.
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
if Arc::ptr_eq(&kept, &pool)
&& let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0)
{
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(kept)
Ok(pools.entry(id.to_owned()).or_insert(pool).clone())
}
/// Closes the tunnel of `source_id` once none of its targets is connected.
@@ -599,30 +496,24 @@ impl DbManager {
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
let introspection = self.source(id)?.introspection;
let system = introspection.show_system;
let pool = self.pool(id).await?;
let pool = self.pool(split_target(id).0).await?;
if pool.driver() != DbDriver::Postgres {
return Err(IdeError::invalid("only PostgreSQL data sources list databases"));
}
let first = |rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
let current = first(pool.rows("SELECT current_database()", 1).await?).next().unwrap_or_default();
let rows = pool.rows(sql::databases(introspection.show_templates), MAX_META_ROWS).await?;
let rows = pool.rows(sql::DATABASES, MAX_META_ROWS).await?;
let mut names: Vec<String> =
first(rows).filter(|n| system || *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
first(rows).filter(|n| *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
if !names.contains(&current) {
names.insert(0, current.clone());
}
Ok(Databases { current, names })
}
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
/// only with [`DbIntrospection::show_system`].
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
let system = self.source(id)?.introspection.show_system;
let pool = self.pool(id).await?;
let rows = pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?;
let rows = pool.rows(sql::schemas(pool.driver()), MAX_META_ROWS).await?;
Ok(rows.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect())
}
@@ -634,7 +525,9 @@ impl DbManager {
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
let kind =
if it.next().flatten().as_deref() == Some("view") { DbTableKind::View } else { DbTableKind::Table };
Some(TableInfo { name, kind })
})
.collect())
}
@@ -682,85 +575,7 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
let triggers = pool
.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS)
.await
.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let (timing, events) = if driver == DbDriver::Sqlite {
sql::sqlite_trigger_event(&it.next().flatten().unwrap_or_default())
} else {
(it.next().flatten().unwrap_or_default(), it.next().flatten().unwrap_or_default())
};
Some(TriggerInfo { name, timing, events })
})
.collect();
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
}
/// The routines and sequences of `schema`.
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
let pool = self.pool(id).await?;
let driver = pool.driver();
let mut out = SchemaObjects::default();
if let Some(q) = sql::routines(driver, schema) {
out.routines = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let kind = if it.next().flatten().as_deref() == Some("procedure") {
DbObjectKind::Procedure
} else {
DbObjectKind::Function
};
let arguments = it.next().flatten().unwrap_or_default();
let returns = it.next().flatten().filter(|r| !r.is_empty() && kind == DbObjectKind::Function);
Some(RoutineInfo { name, kind, arguments, returns })
})
.collect();
}
if let Some(q) = sql::sequences(driver, schema) {
out.sequences = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some(SequenceInfo {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
})
})
.collect();
}
Ok(out)
}
/// The definition of a routine (every overload), trigger or sequence.
pub async fn object_ddl(&self, id: &str, schema: &str, kind: DbObjectKind, name: &str) -> IdeResult<String> {
let pool = self.pool(id).await?;
let (q, column) = sql::object_ddl(pool.driver(), schema, kind, name)
.ok_or_else(|| IdeError::invalid(format!("no {kind:?} objects in this database")))?;
let defs: Vec<String> = pool
.rows(&q, MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| r.into_iter().nth(column).flatten())
.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';')))
.collect();
if defs.is_empty() {
return Err(IdeError::not_found(format!("{schema}.{name}")));
}
Ok(defs.join("\n"))
Ok(TableDetails { columns, indexes, foreign_keys })
}
/// The DDL of table or view `name`: SQLite's stored statements, MySQL's
@@ -856,7 +671,7 @@ impl DbManager {
_ => tables.push(CompletionTable {
schema,
name,
kind: DbTableKind::from_catalog(Some(&kind)),
kind: if kind == "view" { DbTableKind::View } else { DbTableKind::Table },
columns: vec![column],
}),
}
@@ -880,65 +695,12 @@ impl DbManager {
Ok(CompletionModel { default_schema, tables, foreign_keys })
}
/// Runs `statement` on `id` (in its open transaction in manual-commit mode),
/// recording it in the data source's query history.
pub async fn execute(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, max_rows, cancel).await;
let ran = match &r {
Ok(_) => true,
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
};
if ran {
self.remember_statement(id, statement);
}
r
}
fn remember_statement(&self, id: &str, statement: &str) {
let (history, source, text) = (self.history.clone(), split_target(id).0.to_owned(), statement.to_owned());
let time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0.0, |d| d.as_secs_f64() * 1000.0);
tokio::task::spawn_blocking(move || {
if let Err(e) = history.add(&source, &text, time) {
tracing::warn!("{}", e.message);
}
});
}
/// The query history of data source `id`, newest first.
pub async fn history(&self, id: &str) -> IdeResult<Vec<HistoryEntry>> {
let (history, source) = (self.history.clone(), split_target(id).0.to_owned());
tokio::task::spawn_blocking(move || history.list(&source)).await.map_err(|e| IdeError::internal(e.to_string()))
}
/// Forgets statements of the query history of `id` (all of them for `None`).
pub async fn remove_history(&self, id: &str, texts: Option<Vec<String>>) -> IdeResult<()> {
let (history, source) = (self.history.clone(), split_target(id).0.to_owned());
tokio::task::spawn_blocking(move || history.remove(&source, texts.as_deref()))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The execution plan of `statement` (explained, not run).
pub async fn explain(&self, id: &str, statement: &str, cancel: &CancellationToken) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
let result = self.run(id, &plan::explain_statement(driver, statement), MAX_META_ROWS, cancel).await?;
plan::parse(driver, &result)
}
async fn run(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
let session = self.sessions.lock().get(id).cloned();
-268
Переглянути файл
@@ -1,268 +0,0 @@
//! Execution plans (IDEA's Explain Plan): the `EXPLAIN` statement of each
//! dialect and its output read into one flat tree of operations.
use crate::DbDriver;
use crate::conn::QueryResult;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbPlanProperty")]
pub struct PlanProperty {
pub name: String,
pub value: String,
}
/// One operation of a plan; `parent` indexes the plan's node list (roots: `None`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbPlanNode")]
pub struct PlanNode {
pub parent: Option<u32>,
/// `Full Scan`, `Index Scan`, `Hash Join`…
pub operation: String,
/// The object it works on and its key details (`table: o;`).
pub params: String,
pub properties: Vec<PlanProperty>,
}
/// The statement that explains `statement` without running it.
pub fn explain_statement(driver: DbDriver, statement: &str) -> String {
let s = statement.trim().trim_end_matches(';');
match driver {
DbDriver::Sqlite => format!("EXPLAIN QUERY PLAN {s}"),
DbDriver::Postgres => format!("EXPLAIN (FORMAT JSON) {s}"),
DbDriver::Mysql => format!("EXPLAIN {s}"),
}
}
/// Reads the result of [`explain_statement`].
pub fn parse(driver: DbDriver, result: &QueryResult) -> IdeResult<Vec<PlanNode>> {
match driver {
DbDriver::Sqlite => Ok(sqlite(&result.rows)),
DbDriver::Postgres => {
let text: String =
result.rows.iter().filter_map(|r| r.first().cloned().flatten()).collect::<Vec<_>>().join("\n");
let json: Value = serde_json::from_str(&text).map_err(|e| IdeError::invalid(format!("plan: {e}")))?;
let mut out = Vec::new();
for root in json.as_array().into_iter().flatten() {
if let Some(plan) = root.get("Plan") {
postgres(plan, None, &mut out);
}
}
Ok(out)
}
DbDriver::Mysql => {
let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect();
Ok(mysql(&names, &result.rows))
}
}
}
fn prop(name: &str, value: impl Into<String>) -> PlanProperty {
PlanProperty { name: name.to_owned(), value: value.into() }
}
/// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`).
fn sqlite(rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
let mut ids: Vec<String> = Vec::new();
let mut out = Vec::new();
for r in rows {
let cell = |i: usize| r.get(i).cloned().flatten().unwrap_or_default();
let (id, parent, detail) = (cell(0), cell(1), cell(3));
let parent = ids.iter().position(|x| *x == parent).map(|i| i as u32);
let (operation, params) = sqlite_operation(&detail);
out.push(PlanNode { parent, operation, params, properties: vec![prop("Detail", detail.clone())] });
ids.push(id);
}
out
}
fn sqlite_operation(detail: &str) -> (String, String) {
let words: Vec<&str> = detail.split_whitespace().collect();
let object = |i: usize| words.get(i).map(|t| format!("table: {t};")).unwrap_or_default();
let using = || detail.find(" USING ").map(|i| detail[i + 1..].to_owned()).unwrap_or_default();
match words.first().copied() {
Some("SCAN") if detail.contains(" USING ") => ("Index Scan".into(), format!("{} {}", object(1), using())),
Some("SCAN") => ("Full Scan".into(), object(1)),
Some("SEARCH") => ("Index Scan".into(), format!("{} {}", object(1), using()).trim().to_owned()),
Some("USE") if detail.contains("ORDER BY") => ("Order By".into(), String::new()),
Some("USE") if detail.contains("GROUP BY") => ("Group By".into(), String::new()),
Some("USE") if detail.contains("DISTINCT") => ("Distinct".into(), String::new()),
_ => (detail.to_owned(), String::new()),
}
}
/// PostgreSQL JSON plan node: `Node Type`, `Relation Name`, nested `Plans`.
fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
let text = |k: &str| node.get(k).and_then(Value::as_str).unwrap_or_default();
let mut operation = text("Node Type").to_owned();
if let Some(j) = node.get("Join Type").and_then(Value::as_str).filter(|j| *j != "Inner") {
operation = format!("{operation} ({j})");
}
let mut params = Vec::new();
if let Some(r) = node.get("Relation Name").and_then(Value::as_str) {
let alias = text("Alias");
params.push(if alias.is_empty() || alias == r {
format!("table: {r};")
} else {
format!("table: {r} {alias};")
});
}
if let Some(i) = node.get("Index Name").and_then(Value::as_str) {
params.push(format!("index: {i};"));
}
for k in ["Index Cond", "Hash Cond", "Merge Cond", "Filter", "Join Filter"] {
if let Some(c) = node.get(k).and_then(Value::as_str) {
params.push(format!("{}: {c};", k.to_lowercase()));
}
}
let properties = node
.as_object()
.into_iter()
.flatten()
.filter(|(k, _)| k.as_str() != "Plans")
.map(|(k, v)| {
let value = match v {
Value::String(s) => s.clone(),
Value::Array(a) => a
.iter()
.map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
.collect::<Vec<_>>()
.join(", "),
other => other.to_string(),
};
prop(k, value)
})
.collect();
let me = out.len() as u32;
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
for child in node.get("Plans").and_then(Value::as_array).into_iter().flatten() {
postgres(child, Some(me), out);
}
}
/// MySQL's tabular `EXPLAIN`: one row per table access, flat.
fn mysql(names: &[&str], rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
let col = |r: &[Option<String>], n: &str| {
names.iter().position(|c| c.eq_ignore_ascii_case(n)).and_then(|i| r.get(i).cloned().flatten())
};
rows.iter()
.map(|r| {
let access = col(r, "type").unwrap_or_default();
let operation = match access.as_str() {
"ALL" => "Full Scan".to_owned(),
"index" => "Full Index Scan".to_owned(),
"range" => "Index Range Scan".to_owned(),
"ref" | "eq_ref" | "ref_or_null" => "Index Lookup".to_owned(),
"const" | "system" => "Constant Lookup".to_owned(),
"" => col(r, "Extra").unwrap_or_else(|| "Select".to_owned()),
other => other.to_owned(),
};
let mut params = Vec::new();
if let Some(t) = col(r, "table") {
params.push(format!("table: {t};"));
}
if let Some(k) = col(r, "key") {
params.push(format!("key: {k};"));
}
let properties = names.iter().zip(r).filter_map(|(n, v)| v.as_ref().map(|v| prop(n, v.clone()))).collect();
PlanNode { parent: None, operation, params: params.join(" "), properties }
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::conn::ResultColumn;
fn result(columns: &[&str], rows: Vec<Vec<Option<&str>>>) -> QueryResult {
QueryResult {
statement: String::new(),
columns: columns.iter().map(|c| ResultColumn { name: (*c).into(), type_name: String::new() }).collect(),
rows: rows.into_iter().map(|r| r.into_iter().map(|v| v.map(str::to_owned)).collect()).collect(),
affected: None,
has_more: false,
elapsed_ms: 0.0,
execution_ms: 0.0,
}
}
#[test]
fn explains_per_dialect() {
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1");
assert_eq!(explain_statement(DbDriver::Postgres, " select 1 "), "EXPLAIN (FORMAT JSON) select 1");
assert_eq!(explain_statement(DbDriver::Mysql, "select 1"), "EXPLAIN select 1");
}
#[test]
fn reads_sqlite_plans_like_idea() {
let r = result(
&["id", "parent", "notused", "detail"],
vec![
vec![Some("3"), Some("0"), Some("0"), Some("SCAN o")],
vec![Some("5"), Some("0"), Some("0"), Some("SEARCH c USING INTEGER PRIMARY KEY (rowid=?)")],
vec![Some("9"), Some("0"), Some("0"), Some("USE TEMP B-TREE FOR ORDER BY")],
],
);
let plan = parse(DbDriver::Sqlite, &r).unwrap();
let ops: Vec<(&str, &str)> = plan.iter().map(|n| (n.operation.as_str(), n.params.as_str())).collect();
assert_eq!(
ops,
[
("Full Scan", "table: o;"),
("Index Scan", "table: c; USING INTEGER PRIMARY KEY (rowid=?)"),
("Order By", "")
]
);
assert!(plan.iter().all(|n| n.parent.is_none()));
}
#[test]
fn nests_sqlite_children_under_their_parent() {
let r = result(
&["id", "parent", "notused", "detail"],
vec![
vec![Some("2"), Some("0"), Some("0"), Some("CO-ROUTINE sub")],
vec![Some("4"), Some("2"), Some("0"), Some("SCAN t")],
],
);
let plan = parse(DbDriver::Sqlite, &r).unwrap();
assert_eq!(plan[1].parent, Some(0));
}
#[test]
fn reads_postgres_json_trees() {
let json = r#"[{"Plan": {"Node Type": "Hash Join", "Join Type": "Inner", "Hash Cond": "(o.customer_id = c.id)",
"Total Cost": 12.5, "Plans": [
{"Node Type": "Seq Scan", "Relation Name": "orders", "Alias": "o", "Filter": "(status <> 'x')"},
{"Node Type": "Hash", "Plans": [{"Node Type": "Seq Scan", "Relation Name": "customers", "Alias": "c"}]}
]}}]"#;
let plan = parse(DbDriver::Postgres, &result(&["QUERY PLAN"], vec![vec![Some(json)]])).unwrap();
assert_eq!(plan.len(), 4);
assert_eq!(plan[0].operation, "Hash Join");
assert_eq!(plan[0].params, "hash cond: (o.customer_id = c.id);");
assert!(plan[0].properties.iter().any(|p| p.name == "Total Cost" && p.value == "12.5"));
assert_eq!((plan[1].parent, plan[1].params.as_str()), (Some(0), "table: orders o; filter: (status <> 'x');"));
assert_eq!((plan[3].parent, plan[3].operation.as_str()), (Some(2), "Seq Scan"));
}
#[test]
fn reads_mysql_rows() {
let r = result(
&["id", "select_type", "table", "type", "key", "rows", "Extra"],
vec![
vec![Some("1"), Some("SIMPLE"), Some("o"), Some("ALL"), None, Some("20"), Some("Using where")],
vec![Some("1"), Some("SIMPLE"), Some("c"), Some("eq_ref"), Some("PRIMARY"), Some("1"), None],
],
);
let plan = parse(DbDriver::Mysql, &r).unwrap();
assert_eq!((plan[0].operation.as_str(), plan[0].params.as_str()), ("Full Scan", "table: o;"));
assert_eq!((plan[1].operation.as_str(), plan[1].params.as_str()), ("Index Lookup", "table: c; key: PRIMARY;"));
assert!(plan[0].properties.iter().any(|p| p.name == "rows" && p.value == "20"));
}
}
-350
Переглянути файл
@@ -35,91 +35,6 @@ pub enum DbSslMode {
#[default]
Prefer,
Require,
/// Require, and check the server certificate against the CA file.
VerifyCa,
/// [`DbSslMode::VerifyCa`], and check that the certificate names the host.
VerifyFull,
}
/// IDEA's data source colours (tree node and console tab tint), e.g. red for production.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbColor {
Red,
Orange,
Yellow,
Green,
Blue,
Violet,
}
/// Transaction control of the data source's consoles.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbTxMode {
#[default]
Auto,
Manual,
}
/// Options tab: session settings applied to every connection.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DbOptions {
pub transaction: DbTxMode,
/// PostgreSQL `search_path` (unqualified names resolve there).
pub default_schema: String,
/// Session time zone (`TimeZone` / `time_zone`); empty keeps the default.
pub time_zone: String,
/// Statements run on every new connection.
pub startup_script: String,
/// Run `SELECT 1` this often while connected.
pub keep_alive_secs: Option<u32>,
/// Disconnect after this long without statements (enforced by the UI, which sees the activity).
pub auto_disconnect_secs: Option<u32>,
/// PostgreSQL: show only the configured database, its schemas right under the data source.
pub single_database: bool,
}
/// Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DbIntrospection {
pub all_databases: bool,
pub databases: Vec<String>,
pub all_schemas: bool,
pub schemas: Vec<String>,
/// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…).
pub show_system: bool,
/// PostgreSQL template databases (`template0`, `template1`).
pub show_templates: bool,
/// Object filter: the tree lists only tables, views, routines and sequences matching
/// one of these patterns (`*`, `?`; separated by commas or spaces). Empty: all.
pub object_filter: String,
}
impl Default for DbIntrospection {
fn default() -> Self {
Self {
all_databases: true,
databases: Vec::new(),
all_schemas: true,
schemas: Vec::new(),
show_system: false,
show_templates: false,
object_filter: String::new(),
}
}
}
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
/// SQLite: pragmas. See [`crate::conn`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DbProperty {
pub name: String,
pub value: String,
}
/// How the SSH tunnel authenticates (IDEA's SSH configuration "Authentication type").
@@ -169,20 +84,6 @@ pub struct DataSource {
pub read_only: bool,
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
pub ssh: Option<DbSsh>,
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
pub vendor: String,
pub color: Option<DbColor>,
pub comment: String,
/// Connect with [`DataSource::url`] instead of the host / port / database fields.
pub url_only: bool,
pub url: String,
/// PEM files; `~/` is the home directory.
pub ssl_ca_file: String,
pub ssl_cert_file: String,
pub ssl_key_file: String,
pub options: DbOptions,
pub introspection: DbIntrospection,
pub properties: Vec<DbProperty>,
}
impl Default for DataSource {
@@ -200,188 +101,10 @@ impl Default for DataSource {
save_password: false,
read_only: false,
ssh: None,
vendor: String::new(),
color: None,
comment: String::new(),
url_only: false,
url: String::new(),
ssl_ca_file: String::new(),
ssl_cert_file: String::new(),
ssl_key_file: String::new(),
options: DbOptions::default(),
introspection: DbIntrospection::default(),
properties: Vec::new(),
}
}
}
/// The connection settings of a URL (`jdbc:` prefix allowed).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ParsedUrl {
pub driver: Option<DbDriver>,
pub host: String,
pub port: Option<u16>,
pub database: String,
pub user: String,
pub password: Option<String>,
/// Query parameters, in order.
pub params: Vec<(String, String)>,
/// SQLite file.
pub file: Option<String>,
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
let hex = |i: usize| b.get(i).and_then(|&c| (c as char).to_digit(16));
while i < b.len() {
if b[i] == b'%'
&& let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(b[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// The driver speaking the protocol of URL scheme `scheme` (wire-compatible products included).
pub fn scheme_driver(scheme: &str) -> Option<DbDriver> {
match scheme.to_ascii_lowercase().as_str() {
"postgres" | "postgresql" | "pgsql" | "redshift" | "cockroachdb" | "cockroach" | "yugabytedb"
| "timescaledb" | "greenplum" => Some(DbDriver::Postgres),
"mysql" | "mariadb" | "tidb" | "singlestore" | "memsql" | "oceanbase" => Some(DbDriver::Mysql),
"sqlite" | "sqlite3" => Some(DbDriver::Sqlite),
_ => None,
}
}
/// Parses `scheme://[user[:password]@]host[:port][/database][?k=v&…]`, `jdbc:` forms
/// included, and `sqlite:path`.
pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
let bad = || IdeError::invalid(format!("not a database URL: {raw}"));
let url = raw.trim();
let url = url.strip_prefix("jdbc:").or_else(|| url.strip_prefix("JDBC:")).unwrap_or(url);
let (scheme, rest) = url.split_once(':').ok_or_else(bad)?;
let driver = scheme_driver(scheme).ok_or_else(bad)?;
if driver == DbDriver::Sqlite {
let file = rest.strip_prefix("//").unwrap_or(rest);
let file = file.split('?').next().unwrap_or_default();
if file.is_empty() {
return Err(bad());
}
return Ok(ParsedUrl { driver: Some(driver), file: Some(percent_decode(file)), ..Default::default() });
}
let rest = rest.strip_prefix("//").ok_or_else(bad)?;
let (main, query) = rest.split_once('?').unwrap_or((rest, ""));
let (authority, database) = main.split_once('/').unwrap_or((main, ""));
let (userinfo, hostport) = match authority.rsplit_once('@') {
Some((u, h)) => (Some(u), h),
None => (None, authority),
};
// Several hosts (failover lists): the first.
let hostport = hostport.split(',').next().unwrap_or_default();
let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
let (h, after) = v6.split_once(']').ok_or_else(bad)?;
(h.to_owned(), after.strip_prefix(':'))
} else {
match hostport.rsplit_once(':') {
Some((h, p)) => (h.to_owned(), Some(p)),
None => (hostport.to_owned(), None),
}
};
let port = match port.filter(|p| !p.is_empty()) {
Some(p) => Some(p.parse::<u16>().map_err(|_| bad())?),
None => None,
};
let mut parsed = ParsedUrl {
driver: Some(driver),
host,
port,
database: percent_decode(database.trim_end_matches('/')),
..Default::default()
};
if let Some(u) = userinfo {
let (user, password) = match u.split_once(':') {
Some((u, p)) => (u, Some(percent_decode(p))),
None => (u, None),
};
parsed.user = percent_decode(user);
parsed.password = password;
}
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let (k, v) = (percent_decode(k), percent_decode(v));
match k.as_str() {
"user" if parsed.user.is_empty() => parsed.user = v,
"password" if parsed.password.is_none() => parsed.password = Some(v),
_ => parsed.params.push((k, v)),
}
}
Ok(parsed)
}
impl DataSource {
/// The settings to connect with: with [`DataSource::url_only`], host, port,
/// database, user, SSL and driver properties come from the URL (properties
/// of the Advanced tab still apply after the URL's).
pub fn resolved(&self) -> IdeResult<DataSource> {
if !self.url_only {
return Ok(self.clone());
}
let u = parse_url(&self.url)?;
let mut s = self.clone();
if let Some(d) = u.driver
&& d != s.driver
{
return Err(IdeError::invalid(format!("the URL is not for the {:?} driver", s.driver)));
}
if s.driver == DbDriver::Sqlite {
s.file = u.file.map(IpcPath::from);
return Ok(s);
}
s.host = u.host;
s.port = u.port;
s.database = u.database;
if !u.user.is_empty() {
s.user = u.user;
}
let mut properties = Vec::new();
for (k, v) in u.params {
match k.to_ascii_lowercase().as_str() {
"sslmode" | "ssl-mode" => {
s.ssl = match v.to_ascii_lowercase().replace('-', "_").as_str() {
"disable" | "disabled" => DbSslMode::Disable,
"require" | "required" => DbSslMode::Require,
"verify_ca" => DbSslMode::VerifyCa,
"verify_full" | "verify_identity" => DbSslMode::VerifyFull,
_ => DbSslMode::Prefer,
}
}
"sslrootcert" | "ssl-ca" | "sslca" => s.ssl_ca_file = v,
"sslcert" | "ssl-cert" => s.ssl_cert_file = v,
"sslkey" | "ssl-key" => s.ssl_key_file = v,
_ => properties.push(DbProperty { name: k, value: v }),
}
}
properties.append(&mut s.properties);
s.properties = properties;
Ok(s)
}
/// The password written in the URL of a [`DataSource::url_only`] data source.
pub fn url_password(&self) -> Option<String> {
if !self.url_only {
return None;
}
parse_url(&self.url).ok()?.password
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct SourcesFile {
#[serde(default, rename = "data-source")]
@@ -441,77 +164,4 @@ mod tests {
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
}
#[test]
fn reads_configs_written_before_the_new_settings() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join(".openidea");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(FILE),
"[[data-source]]\nid = \"a\"\nname = \"old\"\ndriver = \"postgres\"\nhost = \"db\"\nssl = \"require\"\n",
)
.unwrap();
let s = load(tmp.path()).unwrap().remove(0);
assert_eq!(s.ssl, DbSslMode::Require);
assert!(s.introspection.all_databases && s.introspection.all_schemas);
assert_eq!((s.color, s.url_only, s.options.transaction), (None, false, DbTxMode::Auto));
}
#[test]
fn round_trips_the_new_settings() {
let tmp = tempfile::tempdir().unwrap();
let s = DataSource {
id: "b".into(),
name: "prod".into(),
driver: DbDriver::Mysql,
vendor: "tidb".into(),
color: Some(DbColor::Red),
comment: "careful".into(),
ssl: DbSslMode::VerifyFull,
ssl_ca_file: "~/ca.pem".into(),
options: DbOptions { time_zone: "UTC".into(), keep_alive_secs: Some(60), ..Default::default() },
introspection: DbIntrospection { all_schemas: false, schemas: vec!["app*".into()], ..Default::default() },
properties: vec![DbProperty { name: "sql_mode".into(), value: "ANSI".into() }],
..Default::default()
};
save(tmp.path(), std::slice::from_ref(&s)).unwrap();
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
}
#[test]
fn parses_urls() {
let u = parse_url("jdbc:postgresql://ann:s%[email protected]:5433/shop?sslmode=require&search_path=app").unwrap();
assert_eq!(u.driver, Some(DbDriver::Postgres));
assert_eq!((u.host.as_str(), u.port, u.database.as_str()), ("db.local", Some(5433), "shop"));
assert_eq!((u.user.as_str(), u.password.as_deref()), ("ann", Some("s@cret")));
assert_eq!(u.params, vec![("sslmode".into(), "require".into()), ("search_path".into(), "app".into())]);
let u = parse_url("mysql://[::1]/app?user=root").unwrap();
assert_eq!((u.host.as_str(), u.port, u.user.as_str()), ("::1", None, "root"));
assert_eq!(parse_url("jdbc:redshift://r:5439/dev").unwrap().driver, Some(DbDriver::Postgres));
assert_eq!(parse_url("tidb://h:4000").unwrap().driver, Some(DbDriver::Mysql));
assert_eq!(parse_url("sqlite:/tmp/a.db").unwrap().file.as_deref(), Some("/tmp/a.db"));
assert!(parse_url("oracle://x").is_err());
assert!(parse_url("postgres://h:99999/db").is_err());
}
#[test]
fn url_only_sources_connect_with_the_url() {
let s = DataSource {
driver: DbDriver::Postgres,
user: "fallback".into(),
url_only: true,
url: "postgres://ann:pw@h:6543/app?sslmode=verify-full&sslrootcert=/ca.pem&statement_timeout=5000".into(),
properties: vec![DbProperty { name: "work_mem".into(), value: "64MB".into() }],
..Default::default()
};
let r = s.resolved().unwrap();
assert_eq!((r.host.as_str(), r.port, r.database.as_str(), r.user.as_str()), ("h", Some(6543), "app", "ann"));
assert_eq!((r.ssl, r.ssl_ca_file.as_str()), (DbSslMode::VerifyFull, "/ca.pem"));
let names: Vec<_> = r.properties.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["statement_timeout", "work_mem"]);
assert_eq!(s.url_password().as_deref(), Some("pw"));
assert!(DataSource { url: "mysql://h/db".into(), ..s.clone() }.resolved().is_err());
assert_eq!(DataSource { url_only: false, ..s }.resolved().unwrap().host, "localhost");
}
}
+6 -165
Переглянути файл
@@ -32,26 +32,15 @@ pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// PostgreSQL databases one can connect to; template databases only with `templates`.
pub fn databases(templates: bool) -> &'static str {
if templates {
"SELECT datname FROM pg_database WHERE datallowconn ORDER BY datname"
} else {
"SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname"
}
}
/// Databases one can connect to (PostgreSQL).
pub const DATABASES: &str = "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname";
/// Databases of managed services that their users cannot use (hidden unless connected to).
pub const INTERNAL_DATABASES: &[&str] = &["rdsadmin", "azure_maintenance", "azure_sys", "cloudsqladmin"];
pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
pub fn schemas(driver: DbDriver) -> &'static str {
match driver {
DbDriver::Sqlite => "SELECT name FROM pragma_database_list WHERE name <> 'temp' ORDER BY seq",
DbDriver::Postgres if system => {
"SELECT schema_name FROM information_schema.schemata \
WHERE schema_name NOT LIKE 'pg\\_toast%' AND schema_name NOT LIKE 'pg\\_temp%' ORDER BY 1"
}
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Postgres => {
"SELECT schema_name FROM information_schema.schemata \
WHERE schema_name NOT IN ('pg_catalog', 'information_schema') \
@@ -64,7 +53,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
}
}
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
/// Rows: `name, kind` where kind is `table` or `view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Sqlite => format!(
@@ -72,13 +61,7 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Mysql => format!(
_ => format!(
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
@@ -151,7 +134,7 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
}
DbDriver::Postgres => {
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
"SELECT n.nspname, c.relname, CASE WHEN c.relkind IN ('v', 'm') THEN 'view' ELSE 'table' END, a.attname, \
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
@@ -380,123 +363,6 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
)
}
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Sqlite => format!(
"SELECT name, sql FROM {}.sqlite_master WHERE type = 'trigger' AND tbl_name = {t} ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT t.tgname, CASE WHEN t.tgtype & 2 <> 0 THEN 'before' WHEN t.tgtype & 64 <> 0 THEN 'instead of' \
ELSE 'after' END, concat_ws(' or ', CASE WHEN t.tgtype & 4 <> 0 THEN 'insert' END, \
CASE WHEN t.tgtype & 16 <> 0 THEN 'update' END, CASE WHEN t.tgtype & 8 <> 0 THEN 'delete' END, \
CASE WHEN t.tgtype & 32 <> 0 THEN 'truncate' END) \
FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE NOT t.tgisinternal AND n.nspname = {s} AND c.relname = {t} ORDER BY 1"
),
DbDriver::Mysql => format!(
"SELECT trigger_name, lower(action_timing), lower(event_manipulation) FROM information_schema.triggers \
WHERE event_object_schema = {s} AND event_object_table = {t} ORDER BY 1"
),
}
}
/// `before`, `insert` of SQLite's `CREATE TRIGGER name BEFORE INSERT ON …` (its catalog keeps only the text).
pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
let upper = sql.to_ascii_uppercase();
let words: Vec<&str> = upper.split_whitespace().collect();
let timing = if words.contains(&"BEFORE") {
"before"
} else if words.windows(2).any(|w| w == ["INSTEAD", "OF"]) {
"instead of"
} else {
"after"
};
let event = ["INSERT", "UPDATE", "DELETE"].into_iter().find(|e| words.contains(e)).unwrap_or_default();
(timing.to_owned(), event.to_ascii_lowercase())
}
/// Rows: `name, kind (function/procedure), arguments, result` of a schema's routines (none in SQLite).
pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
let s = quote_literal(driver, schema);
match driver {
DbDriver::Sqlite => None,
// Functions of extensions are left out, as in IDEA.
DbDriver::Postgres => Some(format!(
"SELECT p.proname, CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END, \
pg_get_function_identity_arguments(p.oid), pg_get_function_result(p.oid) \
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = {s} AND p.prokind IN ('f', 'p') \
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e') ORDER BY 1, 3"
)),
DbDriver::Mysql => Some(format!(
"SELECT r.routine_name, lower(r.routine_type), \
(SELECT GROUP_CONCAT(CONCAT(p.parameter_name, ' ', p.dtd_identifier) ORDER BY p.ordinal_position \
SEPARATOR ', ') FROM information_schema.parameters p WHERE p.specific_schema = r.routine_schema \
AND p.specific_name = r.specific_name AND p.ordinal_position > 0), r.dtd_identifier \
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
}
}
/// Rows: `name, data type` of a schema's sequences (PostgreSQL).
pub fn sequences(driver: DbDriver, schema: &str) -> Option<String> {
(driver == DbDriver::Postgres).then(|| {
format!(
"SELECT sequence_name, data_type FROM information_schema.sequences WHERE sequence_schema = {} ORDER BY 1",
quote_literal(driver, schema)
)
})
}
/// The statement reading the definition of a routine (a row per overload), trigger
/// or sequence, and the column that holds it.
pub fn object_ddl(driver: DbDriver, schema: &str, kind: crate::DbObjectKind, name: &str) -> Option<(String, usize)> {
use crate::DbObjectKind as K;
let (s, n) = (quote_literal(driver, schema), quote_literal(driver, name));
let target = qualified(driver, schema, name);
Some(match (driver, kind) {
(DbDriver::Sqlite, K::Trigger) => (
format!(
"SELECT sql FROM {}.sqlite_master WHERE type = 'trigger' AND name = {n}",
quote_ident(driver, schema)
),
0,
),
(DbDriver::Postgres, K::Function | K::Procedure) => (
format!(
"SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname = {s} AND p.proname = {n} ORDER BY pg_get_function_identity_arguments(p.oid)"
),
0,
),
(DbDriver::Postgres, K::Trigger) => (
format!(
"SELECT pg_get_triggerdef(t.oid, true) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid \
JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE NOT t.tgisinternal AND n.nspname = {s} AND t.tgname = {n}"
),
0,
),
(DbDriver::Postgres, K::Sequence) => (
format!(
"SELECT format(E'create sequence %s\\n as %s\\n increment by %s\\n minvalue %s\\n \
maxvalue %s\\n start with %s%s', {}, data_type, increment_by, min_value, max_value, start_value, \
CASE WHEN cycle THEN E'\\n cycle' ELSE '' END) \
FROM pg_sequences WHERE schemaname = {s} AND sequencename = {n}",
quote_literal(driver, &target)
),
0,
),
(DbDriver::Mysql, K::Function) => (format!("SHOW CREATE FUNCTION {target}"), 2),
(DbDriver::Mysql, K::Procedure) => (format!("SHOW CREATE PROCEDURE {target}"), 2),
(DbDriver::Mysql, K::Trigger) => (format!("SHOW CREATE TRIGGER {target}"), 2),
_ => return None,
})
}
/// A column of [`postgres_table_ddl`].
pub struct DdlColumn {
pub name: String,
@@ -586,31 +452,6 @@ mod tests {
assert!(edit_statement(DbDriver::Postgres, "s", "t", &DbRowEdit::Delete { key: vec![] }).is_err());
}
#[test]
fn sqlite_trigger_events() {
let ev = sqlite_trigger_event;
assert_eq!(
ev("CREATE TRIGGER t BEFORE UPDATE OF a ON x BEGIN SELECT 1; END"),
("before".into(), "update".into())
);
assert_eq!(ev("create trigger t instead of insert on v begin end"), ("instead of".into(), "insert".into()));
assert_eq!(ev("CREATE TRIGGER t DELETE ON x BEGIN END"), ("after".into(), "delete".into()));
}
#[test]
fn schema_objects_per_dialect() {
use crate::DbObjectKind as K;
assert!(routines(DbDriver::Sqlite, "main").is_none());
assert!(sequences(DbDriver::Mysql, "db").is_none());
assert!(routines(DbDriver::Postgres, "public").unwrap().contains("n.nspname = 'public'"));
assert_eq!(
object_ddl(DbDriver::Mysql, "db", K::Procedure, "p"),
Some(("SHOW CREATE PROCEDURE `db`.`p`".into(), 2))
);
assert!(object_ddl(DbDriver::Sqlite, "main", K::Function, "f").is_none());
assert!(object_ddl(DbDriver::Postgres, "s", K::Sequence, "q").unwrap().0.contains("sequencename = 'q'"));
}
#[test]
fn postgres_ddl() {
let cols = [
+1 -1
Переглянути файл
@@ -200,7 +200,7 @@ fn home() -> Option<PathBuf> {
}
/// `~/x` → `$HOME/x`.
pub(crate) fn expand(path: &str) -> PathBuf {
fn expand(path: &str) -> PathBuf {
match (path.strip_prefix("~/"), home()) {
(Some(rest), Some(h)) => h.join(rest),
_ => PathBuf::from(path),
+2 -73
Переглянути файл
@@ -1,13 +1,13 @@
//! Introspection, queries and table edits against a real SQLite file.
use ide_core::{CancellationToken, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbTableKind, SortKey};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbTableKind, SortKey};
async fn setup() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
std::fs::File::create(root.join("app.db")).unwrap();
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"));
let db = DbManager::new(root.clone(), root.join("passwords.json"));
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
@@ -246,74 +246,3 @@ async fn ddl_of_tables_and_views() -> IdeResult<()> {
assert!(db.ddl("s1", "main", "nope").await.is_err());
Ok(())
}
#[tokio::test]
async fn explains_queries_without_running_them() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
let plan = db.explain("s1", "SELECT * FROM users WHERE id > 1 ORDER BY note;", &c).await?;
let ops: Vec<_> = plan.iter().map(|n| n.operation.as_str()).collect();
assert_eq!(ops, vec!["Index Scan", "Order By"]);
assert!(plan[0].params.starts_with("table: users;"), "{}", plan[0].params);
db.explain("s1", "DELETE FROM users", &c).await?;
assert_eq!(count(&db).await, "3");
Ok(())
}
#[tokio::test]
async fn records_executed_statements_in_the_query_history() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
db.execute("s1", "SELECT 1", 1, &c).await?;
assert!(db.execute("s1", "SELECT nope", 1, &c).await.is_err());
// Recorded off the async threads.
let mut texts = Vec::new();
for _ in 0..50 {
texts = db.history("s1").await?.into_iter().map(|e| e.text).collect::<Vec<_>>();
if texts.first().map(String::as_str) == Some("SELECT nope") {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(texts[..2], ["SELECT nope", "SELECT 1"]);
db.remove_history("s1", Some(vec!["SELECT 1".into()])).await?;
assert!(!db.history("s1").await?.iter().any(|e| e.text == "SELECT 1"));
db.remove_history("s1", None).await?;
assert!(db.history("s1").await?.is_empty());
Ok(())
}
#[tokio::test]
async fn lists_triggers_and_their_ddl() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
db.execute("s1", "CREATE TRIGGER users_touch AFTER UPDATE ON users BEGIN SELECT 1; END", 1, &c).await?;
let d = db.table_details("s1", "main", "users").await?;
let triggers: Vec<_> = d.triggers.iter().map(|t| (t.name.as_str(), t.timing.as_str(), t.events.as_str())).collect();
assert_eq!(triggers, vec![("users_touch", "after", "update")]);
let ddl = db.object_ddl("s1", "main", ide_db::DbObjectKind::Trigger, "users_touch").await?;
assert!(ddl.starts_with("CREATE TRIGGER users_touch"), "{ddl}");
// SQLite has neither routines nor sequences.
assert_eq!(db.schema_objects("s1", "main").await?, ide_db::SchemaObjects::default());
Ok(())
}
#[tokio::test]
async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeResult<()> {
let (tmp, db) = setup().await;
let mut s = db.sources()?.remove(0);
s.properties = vec![DbProperty { name: "cache_size".into(), value: "-1234".into() }];
s.options = DbOptions {
startup_script: "CREATE TEMP TABLE boot (x); INSERT INTO boot VALUES (7);".into(),
..Default::default()
};
db.save_sources(vec![s.clone()]).await?;
let c = CancellationToken::new();
let r = db.execute("s1", "SELECT (SELECT x FROM boot), (SELECT cache_size FROM pragma_cache_size)", 10, &c).await?;
assert_eq!(r.rows, vec![vec![Some("7".into()), Some("-1234".into())]]);
// URL only: the file comes from the URL.
let url = format!("jdbc:sqlite:{}", tmp.path().join("app.db").display());
db.save_sources(vec![DataSource { url_only: true, url, file: None, ..s }]).await?;
assert_eq!(db.schemas("s1").await?, vec!["main"]);
Ok(())
}
-3
Переглянути файл
@@ -15,6 +15,3 @@ which = "8"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
tempfile.workspace = true
-402
Переглянути файл
@@ -1,402 +0,0 @@
//! Docker connections (which daemon the CLI talks to) and registries, as the
//! Services tool window's "Add Service" menu creates them. Both are app-wide
//! like in IDEA: `docker.json` in the app data directory; registry passwords
//! live beside it in an owner-only `docker-passwords.json`.
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Which daemon a docker command talks to.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum DockerEndpoint {
/// Whatever the CLI is configured for (`DOCKER_HOST`, the current context).
#[default]
Default,
/// A local daemon socket, e.g. `/var/run/docker.sock` (or a `npipe://` URL on Windows).
Socket { path: String },
/// A remote daemon, e.g. `tcp://build:2376` or `ssh://me@build`; with TLS when
/// `tls_cert_dir` holds `ca.pem`, `cert.pem` and `key.pem`.
Tcp { host: String, tls_cert_dir: Option<String> },
/// A named `docker context`.
Context { name: String },
}
impl DockerEndpoint {
/// Global CLI options selecting this endpoint (before the subcommand).
pub fn global_args(&self) -> Vec<String> {
match self {
Self::Default => Vec::new(),
Self::Socket { path } => {
let path = path.trim();
let url = if path.contains("://") { path.to_owned() } else { format!("unix://{path}") };
vec!["--host".into(), url]
}
Self::Tcp { host, tls_cert_dir } => {
let host = host.trim();
let url = if host.contains("://") { host.to_owned() } else { format!("tcp://{host}") };
let mut args = vec!["--host".into(), url];
if let Some(dir) = tls_cert_dir.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
let file = |name: &str| Path::new(dir).join(name).to_string_lossy().into_owned();
args.extend([
"--tlsverify".into(),
"--tlscacert".into(),
file("ca.pem"),
"--tlscert".into(),
file("cert.pem"),
"--tlskey".into(),
file("key.pem"),
]);
}
args
}
Self::Context { name } => vec!["--context".into(), name.trim().to_owned()],
}
}
/// Adds the global options to `cmd`; an explicit endpoint also drops the
/// inherited `DOCKER_HOST` / `DOCKER_CONTEXT`, which would conflict.
pub(crate) fn apply(&self, cmd: &mut Command) {
if *self != Self::Default {
cmd.env_remove("DOCKER_HOST").env_remove("DOCKER_CONTEXT").env_remove("DOCKER_TLS_VERIFY");
}
cmd.args(self.global_args());
}
/// The same selection as environment variables, for docker command lines run by
/// others (run configurations). An empty value clears an inherited variable: the
/// CLI treats `DOCKER_HOST=""` as unset.
pub fn env_vars(&self) -> BTreeMap<String, String> {
let mut env = BTreeMap::new();
let mut set = |k: &str, v: String| {
env.insert(k.to_owned(), v);
};
match self {
Self::Default => {}
Self::Socket { path } => {
let path = path.trim();
set("DOCKER_HOST", if path.contains("://") { path.to_owned() } else { format!("unix://{path}") });
set("DOCKER_CONTEXT", String::new());
set("DOCKER_TLS_VERIFY", String::new());
}
Self::Tcp { host, tls_cert_dir } => {
let host = host.trim();
set("DOCKER_HOST", if host.contains("://") { host.to_owned() } else { format!("tcp://{host}") });
set("DOCKER_CONTEXT", String::new());
match tls_cert_dir.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
// `DOCKER_CERT_PATH` holds `ca.pem`, `cert.pem` and `key.pem`, as `global_args` expects.
Some(dir) => {
set("DOCKER_TLS_VERIFY", "1".into());
set("DOCKER_CERT_PATH", dir.to_owned());
}
None => set("DOCKER_TLS_VERIFY", String::new()),
}
}
Self::Context { name } => {
set("DOCKER_CONTEXT", name.trim().to_owned());
set("DOCKER_HOST", String::new());
set("DOCKER_TLS_VERIFY", String::new());
}
}
env
}
pub fn validate(&self) -> IdeResult<()> {
let empty = match self {
Self::Default => false,
Self::Socket { path } => path.trim().is_empty(),
Self::Tcp { host, .. } => host.trim().is_empty(),
Self::Context { name } => name.trim().is_empty() || name.trim().starts_with('-'),
};
if empty { Err(IdeError::invalid("the Docker connection needs a socket, host or context")) } else { Ok(()) }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerConnection {
pub id: String,
pub name: String,
pub endpoint: DockerEndpoint,
}
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerRegistry {
pub id: String,
pub name: String,
/// `docker.io`, `ghcr.io`, `registry.example.com:5000`.
pub address: String,
#[serde(default)]
pub username: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerSettings {
#[serde(default = "default_connections")]
pub connections: Vec<DockerConnection>,
#[serde(default)]
pub registries: Vec<DockerRegistry>,
}
impl Default for DockerSettings {
fn default() -> Self {
Self { connections: default_connections(), registries: Vec::new() }
}
}
/// Before anything is configured the CLI's own daemon is shown, as before connections existed.
fn default_connections() -> Vec<DockerConnection> {
vec![DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default }]
}
const SETTINGS_FILE: &str = "docker.json";
const PASSWORDS_FILE: &str = "docker-passwords.json";
pub fn load_settings(data_dir: &Path) -> DockerSettings {
match std::fs::read(data_dir.join(SETTINGS_FILE)) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!("{SETTINGS_FILE}: {e}");
DockerSettings::default()
}),
Err(_) => DockerSettings::default(),
}
}
pub fn save_settings(data_dir: &Path, settings: &DockerSettings) -> IdeResult<()> {
for c in &settings.connections {
if c.id.is_empty() || c.name.trim().is_empty() {
return Err(IdeError::invalid("every Docker connection needs a name"));
}
c.endpoint.validate()?;
}
for r in &settings.registries {
if r.id.is_empty() || r.address.trim().is_empty() {
return Err(IdeError::invalid("every Docker registry needs an address"));
}
}
let bytes = serde_json::to_vec_pretty(settings).map_err(|e| IdeError::internal(e.to_string()))?;
write_file(&data_dir.join(SETTINGS_FILE), &bytes, false)?;
// Forget passwords of registries that are gone.
let mut passwords = read_passwords(data_dir);
let before = passwords.len();
passwords.retain(|id, _| settings.registries.iter().any(|r| &r.id == id));
if passwords.len() != before { write_passwords(data_dir, &passwords) } else { Ok(()) }
}
fn read_passwords(data_dir: &Path) -> BTreeMap<String, String> {
std::fs::read(data_dir.join(PASSWORDS_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
fn write_passwords(data_dir: &Path, all: &BTreeMap<String, String>) -> IdeResult<()> {
let bytes = serde_json::to_vec_pretty(all).map_err(|e| IdeError::internal(e.to_string()))?;
write_file(&data_dir.join(PASSWORDS_FILE), &bytes, true)
}
pub fn registry_password(data_dir: &Path, id: &str) -> Option<String> {
read_passwords(data_dir).remove(id)
}
/// Saves (or with `None` forgets) the password of registry `id`.
pub fn set_registry_password(data_dir: &Path, id: &str, password: Option<&str>) -> IdeResult<()> {
let mut all = read_passwords(data_dir);
match password {
Some(p) => all.insert(id.to_owned(), p.to_owned()),
None => all.remove(id),
};
write_passwords(data_dir, &all)
}
fn write_file(path: &Path, bytes: &[u8], private: bool) -> IdeResult<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
if private {
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
}
#[cfg(not(unix))]
let _ = private;
std::io::Write::write_all(&mut options.open(&tmp)?, bytes)?;
std::fs::rename(&tmp, path)?;
Ok(())
}
/// Canonical registry host: no scheme or path; Docker Hub's aliases become `docker.io`.
pub fn registry_host(address: &str) -> String {
let a = address.trim();
let a = a.split_once("://").map_or(a, |(_, rest)| rest);
let host = a.split('/').next().unwrap_or_default().to_ascii_lowercase();
match host.as_str() {
"index.docker.io" | "registry-1.docker.io" | "registry.hub.docker.com" | "hub.docker.com" => "docker.io".into(),
_ => host,
}
}
/// Registry host an image reference pulls from (`postgres:16` → `docker.io`).
pub fn reference_registry(reference: &str) -> String {
match reference.split_once('/') {
Some((first, _)) if first.contains('.') || first.contains(':') || first == "localhost" => registry_host(first),
_ => "docker.io".into(),
}
}
/// Credentials for a `docker login`.
#[derive(Clone, Debug)]
pub struct RegistryAuth {
pub address: String,
pub username: String,
pub password: String,
}
/// The saved registry (with a password) matching `reference`, if any.
pub fn auth_for(data_dir: &Path, reference: &str) -> Option<RegistryAuth> {
let host = reference_registry(reference);
let settings = load_settings(data_dir);
let registry =
settings.registries.into_iter().find(|r| registry_host(&r.address) == host && !r.username.is_empty())?;
let password = registry_password(data_dir, &registry.id)?;
Some(RegistryAuth { address: registry.address, username: registry.username, password })
}
/// A throwaway docker config directory: logins happen there, never in the user's
/// `~/.docker/config.json`. Contexts are copied so a context endpoint still resolves.
pub(crate) struct TempConfig {
pub dir: PathBuf,
}
impl TempConfig {
pub fn new() -> IdeResult<Self> {
let nanos =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
let dir = std::env::temp_dir().join(format!("openidea-docker-{}-{nanos}", std::process::id()));
std::fs::create_dir_all(&dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
}
if let Some(contexts) = user_config_dir().map(|d| d.join("contexts")).filter(|d| d.is_dir()) {
let _ = copy_dir(&contexts, &dir.join("contexts"));
}
Ok(Self { dir })
}
}
impl Drop for TempConfig {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn user_config_dir() -> Option<PathBuf> {
if let Some(dir) = std::env::var_os("DOCKER_CONFIG") {
return Some(PathBuf::from(dir));
}
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })?;
Some(PathBuf::from(home).join(".docker"))
}
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for e in std::fs::read_dir(from)?.flatten() {
let target = to.join(e.file_name());
if e.file_type()?.is_dir() {
copy_dir(&e.path(), &target)?;
} else {
std::fs::copy(e.path(), target)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn endpoint_args() {
assert!(DockerEndpoint::Default.global_args().is_empty());
assert_eq!(
DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }.global_args(),
["--host", "unix:///var/run/docker.sock"]
);
let tls = DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: Some("/certs".into()) }.global_args();
assert_eq!(tls[..3], ["--host", "tcp://build:2376", "--tlsverify"]);
assert!(tls.contains(&Path::new("/certs").join("key.pem").to_string_lossy().into_owned()));
assert_eq!(
DockerEndpoint::Tcp { host: "ssh://me@box".into(), tls_cert_dir: Some(" ".into()) }.global_args(),
["--host", "ssh://me@box"]
);
assert_eq!(DockerEndpoint::Context { name: "orbstack".into() }.global_args(), ["--context", "orbstack"]);
assert!(DockerEndpoint::Context { name: "--x".into() }.validate().is_err());
}
#[test]
fn endpoint_env() {
assert!(DockerEndpoint::Default.env_vars().is_empty());
let socket = DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }.env_vars();
assert_eq!(socket["DOCKER_HOST"], "unix:///var/run/docker.sock");
assert_eq!(socket["DOCKER_CONTEXT"], "");
let tls = DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: Some("/certs".into()) }.env_vars();
assert_eq!(
(tls["DOCKER_HOST"].as_str(), tls["DOCKER_TLS_VERIFY"].as_str(), tls["DOCKER_CERT_PATH"].as_str()),
("tcp://build:2376", "1", "/certs")
);
let ssh = DockerEndpoint::Tcp { host: "ssh://me@box".into(), tls_cert_dir: None }.env_vars();
assert_eq!((ssh["DOCKER_HOST"].as_str(), ssh["DOCKER_TLS_VERIFY"].as_str()), ("ssh://me@box", ""));
assert!(!ssh.contains_key("DOCKER_CERT_PATH"));
let ctx = DockerEndpoint::Context { name: " orbstack ".into() }.env_vars();
assert_eq!((ctx["DOCKER_CONTEXT"].as_str(), ctx["DOCKER_HOST"].as_str()), ("orbstack", ""));
}
#[test]
fn registries_match_references() {
assert_eq!(reference_registry("postgres:16"), "docker.io");
assert_eq!(reference_registry("library/postgres"), "docker.io");
assert_eq!(reference_registry("ghcr.io/org/app:1"), "ghcr.io");
assert_eq!(reference_registry("localhost:5000/app"), "localhost:5000");
assert_eq!(registry_host("https://index.docker.io/v1/"), "docker.io");
assert_eq!(registry_host("GHCR.io"), "ghcr.io");
}
#[test]
fn settings_round_trip_and_passwords() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
assert_eq!(load_settings(dir).connections[0].endpoint, DockerEndpoint::Default);
let settings = DockerSettings {
connections: vec![DockerConnection {
id: "c1".into(),
name: "Build box".into(),
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
}],
registries: vec![DockerRegistry {
id: "r1".into(),
name: "GHCR".into(),
address: "ghcr.io".into(),
username: "me".into(),
}],
};
save_settings(dir, &settings).unwrap();
assert_eq!(load_settings(dir), settings);
set_registry_password(dir, "r1", Some("s3cret")).unwrap();
let auth = auth_for(dir, "ghcr.io/org/app").unwrap();
assert_eq!((auth.username.as_str(), auth.password.as_str()), ("me", "s3cret"));
assert!(auth_for(dir, "postgres").is_none());
save_settings(dir, &DockerSettings { registries: Vec::new(), ..settings }).unwrap();
assert_eq!(registry_password(dir, "r1"), None);
// An empty list stays empty (the default connection is only for a missing file).
save_settings(dir, &DockerSettings { connections: Vec::new(), registries: Vec::new() }).unwrap();
assert!(load_settings(dir).connections.is_empty());
}
}
+28 -109
Переглянути файл
@@ -4,11 +4,9 @@
//!
//! Every function blocks; callers run them off the UI / command threads.
mod connection;
mod model;
mod process;
pub use connection::*;
pub use model::*;
use ide_core::{CancellationToken, IdeError, IdeResult};
@@ -63,38 +61,21 @@ pub fn docker_executable() -> Option<PathBuf> {
.clone()
}
/// Environment for docker command lines a run configuration launches: the endpoint's
/// variables plus a `PATH` that starts with docker's directory (GUI apps on macOS
/// lack the usual install locations), so `docker` / `docker compose` resolve.
pub fn run_env(ep: &DockerEndpoint) -> std::collections::BTreeMap<String, String> {
let mut env = ep.env_vars();
if let Some(dir) = docker_executable().as_deref().and_then(Path::parent) {
let current = std::env::var_os("PATH").unwrap_or_default();
let mut dirs: Vec<PathBuf> = vec![dir.to_path_buf()];
dirs.extend(std::env::split_paths(&current).filter(|d| d != dir));
if let Ok(path) = std::env::join_paths(dirs) {
env.insert("PATH".into(), path.to_string_lossy().into_owned());
}
}
env
}
fn binary() -> IdeResult<PathBuf> {
docker_executable()
.ok_or_else(|| IdeError::unavailable("docker executable not found; install Docker and make sure it is on PATH"))
}
fn command(ep: &DockerEndpoint, args: &[&str]) -> IdeResult<Command> {
fn command(args: &[&str]) -> IdeResult<Command> {
let mut cmd = Command::new(binary()?);
ep.apply(&mut cmd);
cmd.args(args).env("DOCKER_CLI_HINTS", "false").env("NO_COLOR", "1");
tracing::debug!(?args, "docker");
Ok(cmd)
}
/// Runs a docker command, mapping a non-zero exit to an error with docker's message.
fn run(ep: &DockerEndpoint, args: &[&str], timeout: Duration) -> IdeResult<String> {
let out = process::run(command(ep, args)?, timeout, None)?;
fn run(args: &[&str], timeout: Duration) -> IdeResult<String> {
let out = process::run(command(args)?, timeout, None)?;
if out.success { Ok(out.stdout) } else { Err(failure(args, &out.stderr, &out.stdout)) }
}
@@ -113,8 +94,8 @@ fn failure(args: &[&str], stderr: &str, stdout: &str) -> IdeError {
}
/// Whether docker can be used right now.
pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
let Ok(cmd) = command(ep, &["version", "--format", "{{json .}}"]) else {
pub fn availability() -> DockerAvailability {
let Ok(cmd) = command(&["version", "--format", "{{json .}}"]) else {
return DockerAvailability::NotInstalled;
};
match process::run(cmd, Duration::from_secs(15), None) {
@@ -124,8 +105,8 @@ pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
}
/// Availability plus containers, images, volumes and networks (listed in parallel).
pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
let availability = availability(ep);
pub fn snapshot() -> DockerSnapshot {
let availability = availability();
let executable = docker_executable().map(|p| ide_core::ipc_path::to_ipc(&p));
let mut snap = DockerSnapshot {
availability,
@@ -135,17 +116,16 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
volumes: Vec::new(),
networks: Vec::new(),
errors: Vec::new(),
global_args: ep.global_args(),
};
if !matches!(snap.availability, DockerAvailability::Ready { .. }) {
return snap;
}
const FMT: &str = "{{json .}}";
let (containers, images, volumes, networks) = std::thread::scope(|s| {
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
let c = s.spawn(|| run(&["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
let i = s.spawn(|| run(&["image", "ls", "--no-trunc", "--format", FMT], QUICK));
let v = s.spawn(|| run(&["volume", "ls", "--format", FMT], QUICK));
let n = s.spawn(|| run(&["network", "ls", "--no-trunc", "--format", FMT], QUICK));
let join = |h: std::thread::ScopedJoinHandle<'_, IdeResult<String>>| {
h.join().unwrap_or_else(|_| Err(IdeError::internal("docker listing panicked")))
};
@@ -198,13 +178,13 @@ impl ContainerOp {
}
/// Starts / stops / … the containers `ids`.
pub fn container_op(ep: &DockerEndpoint, ids: &[String], op: ContainerOp) -> IdeResult<()> {
pub fn container_op(ids: &[String], op: ContainerOp) -> IdeResult<()> {
if ids.is_empty() {
return Ok(());
}
let mut args = vec!["container", op.verb()];
args.extend(ids.iter().map(String::as_str));
run(ep, &args, LIFECYCLE).map(drop)
run(&args, LIFECYCLE).map(drop)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -228,7 +208,7 @@ impl DockerObject {
}
/// `docker <object> rm` (`force`: stop running containers / untag used images first).
pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
pub fn remove(object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
if ids.is_empty() {
return Ok(());
}
@@ -237,12 +217,12 @@ pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force:
args.push("--force");
}
args.extend(ids.iter().map(String::as_str));
run(ep, &args, LIFECYCLE).map(drop)
run(&args, LIFECYCLE).map(drop)
}
/// `docker inspect` of one object, pretty-printed.
pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult<String> {
let out = run(ep, &["inspect", "--type", object.noun(), id], QUICK)?;
pub fn inspect(object: DockerObject, id: &str) -> IdeResult<String> {
let out = run(&["inspect", "--type", object.noun(), id], QUICK)?;
match serde_json::from_str::<serde_json::Value>(&out) {
// A one-element array for a single id: show the object itself.
Ok(serde_json::Value::Array(mut items)) if items.len() == 1 => {
@@ -256,7 +236,6 @@ pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// until it ends or `cancel` fires.
pub fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
@@ -273,16 +252,16 @@ pub fn logs(
args.push("--timestamps");
}
args.push(id);
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, text| {
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, text| {
on_line(DockerLogLine { stderr: stream == Stream::Stderr, text })
})?;
if ok { Ok(()) } else { Err(failure(&args, &stderr.join("\n"), "")) }
}
/// Follows `docker events` until it ends (daemon gone) or `cancel` fires.
pub fn watch_events(ep: &DockerEndpoint, cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
pub fn watch_events(cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
let args = ["events", "--format", "{{json .}}"];
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| {
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, line| {
if stream == Stream::Stdout
&& let Some(e) = parse_event(&line)
{
@@ -293,19 +272,9 @@ pub fn watch_events(ep: &DockerEndpoint, cancel: &CancellationToken, on_event: &
}
/// Runs a long docker command (pull, prune, compose…), streaming its output lines.
fn run_streaming(
ep: &DockerEndpoint,
config: Option<&Path>,
args: &[&str],
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
fn run_streaming(args: &[&str], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
on_output(format!("docker {}", args.join(" ")));
let mut cmd = command(ep, args)?;
if let Some(dir) = config {
cmd.env("DOCKER_CONFIG", dir);
}
let (ok, stderr) = process::stream(cmd, cancel, &mut |_, line| {
let (ok, stderr) = process::stream(command(args)?, cancel, &mut |_, line| {
if !line.trim().is_empty() {
on_output(line);
}
@@ -313,57 +282,13 @@ fn run_streaming(
if ok { Ok(()) } else { Err(failure(args, &stderr.join("\n"), "")) }
}
/// `docker pull <reference>`; with `auth` it logs in to the registry first, in a
/// throwaway config directory (the user's docker config stays untouched).
pub fn pull(
ep: &DockerEndpoint,
reference: &str,
auth: Option<&RegistryAuth>,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
/// `docker pull <reference>`.
pub fn pull(reference: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let reference = reference.trim();
if reference.is_empty() || reference.starts_with('-') {
return Err(IdeError::invalid("enter an image name, e.g. postgres:16"));
}
let Some(auth) = auth else { return run_streaming(ep, None, &["pull", reference], cancel, on_output) };
let config = TempConfig::new()?;
on_output(format!("Logging in to {} as {}", auth.address, auth.username));
login_in(ep, &config.dir, auth, Some(cancel))?;
run_streaming(ep, Some(&config.dir), &["pull", reference], cancel, on_output)
}
/// `docker login` with `auth`; returns docker's answer (`Login Succeeded`). Nothing is
/// stored in the user's docker config.
pub fn login(ep: &DockerEndpoint, auth: &RegistryAuth) -> IdeResult<String> {
let config = TempConfig::new()?;
login_in(ep, &config.dir, auth, None)
}
fn login_in(
ep: &DockerEndpoint,
config: &Path,
auth: &RegistryAuth,
cancel: Option<&CancellationToken>,
) -> IdeResult<String> {
let host = registry_host(&auth.address);
let user = auth.username.trim();
if host.is_empty() || host.starts_with('-') || user.is_empty() || user.starts_with('-') {
return Err(IdeError::invalid("the registry needs an address and a username"));
}
let mut args = vec!["login", "--username", user, "--password-stdin"];
// Docker Hub is the CLI's default server.
if host != "docker.io" {
args.push(&host);
}
let mut cmd = command(ep, &args)?;
cmd.env("DOCKER_CONFIG", config);
let out = process::run_with_input(cmd, QUICK, cancel, Some(&auth.password))?;
if out.success {
Ok(out.stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or("Login Succeeded").to_owned())
} else {
Err(failure(&args, &out.stderr, &out.stdout))
}
run_streaming(&["pull", reference], cancel, on_output)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -381,12 +306,7 @@ pub enum PruneTarget {
}
/// `docker <object> prune --force`.
pub fn prune(
ep: &DockerEndpoint,
target: PruneTarget,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
pub fn prune(target: PruneTarget, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
let args: &[&str] = match target {
PruneTarget::Containers => &["container", "prune", "--force"],
PruneTarget::Images => &["image", "prune", "--force"],
@@ -395,7 +315,7 @@ pub fn prune(
PruneTarget::Networks => &["network", "prune", "--force"],
PruneTarget::System => &["system", "prune", "--force"],
};
run_streaming(ep, None, args, cancel, on_output)
run_streaming(args, cancel, on_output)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -412,7 +332,6 @@ pub enum ComposeOp {
/// labels. `files` / `working_dir` (from the labels too) are passed when they still
/// exist, so commands that need the model keep working.
pub fn compose_op(
ep: &DockerEndpoint,
project: &str,
files: &[String],
working_dir: Option<&str>,
@@ -438,5 +357,5 @@ pub fn compose_op(
ComposeOp::Restart => "restart",
ComposeOp::Down => "down",
});
run_streaming(ep, None, &args, cancel, on_output)
run_streaming(&args, cancel, on_output)
}
-3
Переглянути файл
@@ -105,9 +105,6 @@ pub struct DockerSnapshot {
pub networks: Vec<DockerNetwork>,
/// Lists that failed although the daemon answered (shown, not fatal).
pub errors: Vec<String>,
/// Global CLI options selecting the connection's daemon (for `docker exec` in a terminal).
#[serde(default)]
pub global_args: Vec<String>,
}
/// One relevant `docker events` entry.
+6 -19
Переглянути файл
@@ -25,7 +25,11 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
ide_core::process::no_window(cmd);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
@@ -60,26 +64,9 @@ fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Str
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
run_with_input(cmd, timeout, cancel, None)
}
/// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`).
pub(crate) fn run_with_input(
mut cmd: Command,
timeout: Duration,
cancel: Option<&CancellationToken>,
input: Option<&str>,
) -> IdeResult<Output> {
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
prepare(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = spawn(&mut cmd)?;
if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = std::io::Write::write_all(&mut stdin, text.as_bytes());
}
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
+5 -1
Переглянути файл
@@ -25,7 +25,11 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
ide_core::process::no_window(cmd);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+4 -4
Переглянути файл
@@ -181,10 +181,10 @@ impl IndexData {
Some(old)
}
/// Removes every file at or below `dir`; returns their paths.
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
/// Removes every file at or below `dir`; returns their relative paths.
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<String> {
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
doomed.iter().filter_map(|p| self.remove(p)).map(|e| e.rel.into_string()).collect()
}
/// Releases spare capacity (after large deletions).
@@ -235,7 +235,7 @@ mod tests {
assert_eq!((d.file_count, d.symbol_count), (1, 5));
d.insert(entry("d.rs", 0));
assert_eq!(d.files.len(), 2, "slot reused");
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
assert_eq!(d.remove_tree(Path::new("/r/a")), vec!["a/b.rs".to_owned()]);
assert_eq!((d.file_count, d.symbol_count), (1, 0));
let e = d.get(Path::new("/r/d.rs")).unwrap();
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
+25 -135
Переглянути файл
@@ -1,6 +1,5 @@
//! Which paths belong in the index: `.gitignore`/`.ignore` rules (via the
//! `ignore` crate) plus the user's `files.exclude` globs, below the project root
//! and the extra content roots (Project Structure).
//! `ignore` crate) plus the user's `files.exclude` globs.
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
@@ -15,45 +14,10 @@ const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj"];
pub(crate) struct PathFilter {
root: PathBuf,
/// Content roots outside `root`, indexed as `<folder name>/<path>`.
extra: Vec<ExtraRoot>,
excludes: GlobSet,
/// Root-level ignore files, for paths reported by the watcher (the walker
/// applies nested ignore files itself).
gitignore: Gitignore,
/// What the filter was built from: `(extra roots, exclude globs)`.
config: (Vec<PathBuf>, Vec<String>),
}
struct ExtraRoot {
path: PathBuf,
/// Shown before the paths inside it (`shared-lib/src/x.rs`).
name: String,
gitignore: Gitignore,
}
fn root_ignores(root: &Path) -> Gitignore {
let mut gi = GitignoreBuilder::new(root);
for f in [".gitignore", ".ignore", ".git/info/exclude"] {
let path = root.join(f);
if path.is_file()
&& let Some(e) = gi.add(&path)
{
tracing::debug!("{}: {e}", path.display());
}
}
gi.build().unwrap_or_else(|_| Gitignore::empty())
}
fn rel_string(rel: &Path) -> String {
let mut out = String::new();
for c in rel.components() {
if !out.is_empty() {
out.push('/');
}
out.push_str(&c.as_os_str().to_string_lossy());
}
out
}
#[derive(Clone, Debug)]
@@ -68,9 +32,9 @@ pub(crate) fn mtime_of(meta: &std::fs::Metadata) -> u64 {
}
impl PathFilter {
pub(crate) fn new(root: &Path, extra_roots: &[PathBuf], exclude_globs: &[String]) -> Self {
pub(crate) fn new(root: &Path, excludes: &[String]) -> Self {
let mut set = GlobSetBuilder::new();
for raw in exclude_globs {
for raw in excludes {
let p = raw.trim().trim_end_matches('/');
let anchored = p.starts_with('/');
let p = p.trim_start_matches("./").trim_start_matches('/');
@@ -91,76 +55,34 @@ impl PathFilter {
}
}
let excludes = set.build().unwrap_or_else(|_| GlobSet::empty());
let mut extra: Vec<ExtraRoot> = Vec::new();
for r in extra_roots {
let path = dunce::canonicalize(r).unwrap_or_else(|_| r.clone());
let nested = path.starts_with(root)
|| root.starts_with(&path)
|| extra.iter().any(|e| path.starts_with(&e.path) || e.path.starts_with(&path));
if nested || !path.is_dir() {
continue;
let mut gi = GitignoreBuilder::new(root);
for f in [".gitignore", ".ignore", ".git/info/exclude"] {
let path = root.join(f);
if path.is_file()
&& let Some(e) = gi.add(&path)
{
tracing::debug!("{}: {e}", path.display());
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
extra.push(ExtraRoot { gitignore: root_ignores(&path), name, path });
}
Self {
root: root.to_owned(),
extra,
excludes,
gitignore: root_ignores(root),
config: (extra_roots.to_vec(), exclude_globs.to_vec()),
}
}
/// Whether the filter was built from these roots and globs.
pub(crate) fn same_config(&self, extra_roots: &[PathBuf], excludes: &[String]) -> bool {
self.config.0 == extra_roots && self.config.1 == excludes
let gitignore = gi.build().unwrap_or_else(|_| Gitignore::empty());
Self { root: root.to_owned(), excludes, gitignore }
}
pub(crate) fn root(&self) -> &Path {
&self.root
}
/// The project root, then the extra content roots.
pub(crate) fn roots(&self) -> impl Iterator<Item = &Path> {
std::iter::once(self.root.as_path()).chain(self.extra.iter().map(|e| e.path.as_path()))
}
/// The root containing `path`, its display prefix (`None` for the project root) and ignore rules.
fn base_of(&self, path: &Path) -> Option<(&Path, Option<&str>, &Gitignore)> {
if path.starts_with(&self.root) {
return Some((&self.root, None, &self.gitignore));
}
self.extra
.iter()
.find(|e| path.starts_with(&e.path))
.map(|e| (e.path.as_path(), Some(e.name.as_str()), &e.gitignore))
}
/// Whether `path` is (at or) below one of the roots.
pub(crate) fn contains(&self, path: &Path) -> bool {
self.base_of(path).is_some()
}
/// `/`-separated path relative to its root, as displayed; paths in extra
/// content roots start with the root's folder name.
/// `/`-separated path relative to the root.
pub(crate) fn rel(&self, path: &Path) -> Option<String> {
let (base, prefix, _) = self.base_of(path)?;
let rel = rel_string(path.strip_prefix(base).ok()?);
if rel.is_empty() {
return None;
let rel = path.strip_prefix(&self.root).ok()?;
let mut out = String::new();
for c in rel.components() {
if !out.is_empty() {
out.push('/');
}
out.push_str(&c.as_os_str().to_string_lossy());
}
Some(match prefix {
Some(p) => format!("{p}/{rel}"),
None => rel,
})
}
/// Key of `path` in the persistent store: only files below the project root
/// are persisted (extra content roots are rescanned when the project opens).
pub(crate) fn store_key(&self, path: &Path) -> Option<String> {
let rel = rel_string(path.strip_prefix(&self.root).ok()?);
(!rel.is_empty()).then_some(rel)
(!out.is_empty()).then_some(out)
}
fn excluded_rel(&self, rel: &str) -> bool {
@@ -174,11 +96,7 @@ impl PathFilter {
/// Whether a path reported by the watcher should be ignored (outside the
/// root, inside an excluded/ignored directory, or ignored itself).
pub(crate) fn is_excluded(&self, path: &Path, is_dir: bool) -> bool {
let Some((base, _, gitignore)) = self.base_of(path) else { return true };
let rel = path.strip_prefix(base).map(rel_string).unwrap_or_default();
if rel.is_empty() {
return true;
}
let Some(rel) = self.rel(path) else { return true };
let mut prefix = String::new();
for seg in rel.split('/') {
if Self::skip_name(seg) {
@@ -192,15 +110,14 @@ impl PathFilter {
return true;
}
}
gitignore.matched_path_or_any_parents(path, is_dir).is_ignore()
self.gitignore.matched_path_or_any_parents(path, is_dir).is_ignore()
}
/// All indexable files at or below `dir`, walked in parallel.
/// Stops early (returning what was found so far) once `cancel` is set.
pub(crate) fn walk(&self, dir: &Path, cancel: &AtomicBool) -> Vec<Found> {
let (tx, rx) = mpsc::channel::<Vec<Found>>();
let Some((root, _, _)) = self.base_of(dir) else { return Vec::new() };
let root = root.to_path_buf();
let root = self.root.clone();
let excludes = self.excludes.clone();
let walker = WalkBuilder::new(dir)
.hidden(false)
@@ -290,7 +207,7 @@ mod tests {
touch(&root, f);
}
std::fs::write(root.join(".gitignore"), "build/\n").unwrap();
let filter = PathFilter::new(&root, &[], &["**/node_modules".into(), "target".into(), "docs/**".into()]);
let filter = PathFilter::new(&root, &["**/node_modules".into(), "target".into(), "docs/**".into()]);
let mut found: Vec<String> =
filter.walk(&root, &AtomicBool::new(false)).iter().filter_map(|f| filter.rel(&f.path)).collect();
found.sort();
@@ -303,31 +220,4 @@ mod tests {
assert!(filter.is_excluded(Path::new("/elsewhere/x.rs"), false));
assert!(!filter.is_excluded(&root.join("src/new.rs"), false));
}
#[test]
fn extra_content_roots_are_walked_and_prefixed() {
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let (root, shared) = (base.join("app"), base.join("shared-lib"));
for f in ["app/src/a.rs", "shared-lib/src/b.rs", "shared-lib/target/gen.rs", "shared-lib/out/x.rs"] {
touch(&base, f);
}
std::fs::write(shared.join(".gitignore"), "out/\n").unwrap();
let filter = PathFilter::new(&root, &[shared.clone(), root.join("src")], &["target".into()]);
assert_eq!(filter.roots().count(), 2, "roots inside the project are not extra roots");
let mut found: Vec<String> = filter
.roots()
.flat_map(|r| filter.walk(r, &AtomicBool::new(false)))
.filter_map(|f| filter.rel(&f.path))
.collect();
found.sort();
assert_eq!(found, ["shared-lib/.gitignore", "shared-lib/src/b.rs", "src/a.rs"]);
assert_eq!(filter.store_key(&shared.join("src/b.rs")), None, "extra roots are not persisted");
assert_eq!(filter.store_key(&root.join("src/a.rs")).as_deref(), Some("src/a.rs"));
assert!(!filter.is_excluded(&shared.join("src/new.rs"), false));
assert!(filter.is_excluded(&shared.join("target/y.rs"), false));
assert!(filter.is_excluded(&shared.join("out/y.rs"), false));
assert!(filter.same_config(&[shared.clone(), root.join("src")], &["target".into()]));
assert!(!filter.same_config(&[shared], &["target".into()]));
}
}
+7 -54
Переглянути файл
@@ -67,17 +67,14 @@ pub struct IndexStatus {
pub struct ProjectIndex {
shared: Arc<Shared>,
worker: Mutex<Option<JoinHandle<()>>>,
root: PathBuf,
}
impl ProjectIndex {
/// Opens (or creates) the persistent index at `cache_dir` and starts a
/// background full scan that skips files whose content hash is unchanged.
/// `content_roots` are folders outside `root` indexed with it (not persisted).
pub fn open(
root: &Path,
cache_dir: &Path,
content_roots: Vec<PathBuf>,
excludes: Vec<String>,
languages: Arc<LanguageRegistry>,
syntax: Arc<Syntax>,
@@ -88,7 +85,7 @@ impl ProjectIndex {
return Err(ide_core::IdeError::not_found(format!("{} is not a directory", root.display())));
}
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
let filter = filter::PathFilter::new(&root, &excludes);
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
let worker = {
let shared = shared.clone();
@@ -97,25 +94,7 @@ impl ProjectIndex {
.spawn(move || shared.run())
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
};
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)), root }))
}
/// Changes what is indexed besides the root (content roots) and the exclude
/// globs, rescanning in the background (unchanged files are not re-read).
/// Returns whether anything changed.
pub fn set_scope(&self, content_roots: Vec<PathBuf>, excludes: Vec<String>) -> bool {
if self.shared.filter().same_config(&content_roots, &excludes) {
return false;
}
self.shared.set_filter(filter::PathFilter::new(&self.root, &content_roots, &excludes));
self.shared.enqueue(Job::Rescan);
true
}
/// File types changed (the registry the index shares was updated): re-parses
/// the files whose language under `before` differs from the current one.
pub fn languages_changed(&self, before: Arc<LanguageRegistry>) {
self.shared.enqueue(Job::Reparse(before));
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)) }))
}
pub fn status(&self) -> IndexStatus {
@@ -142,11 +121,6 @@ impl ProjectIndex {
matching::find_symbols(&d, &matching::Recents { paths: &recent }, query, filter, limit)
}
/// Symbols named exactly `name` (of `kind`, if given): `.card` selectors for `class="card"`.
pub fn symbols_named(&self, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
matching::symbols_named(&self.shared.data.read(), name, kind, limit)
}
/// Incrementally re-indexes changed paths (called from the vfs watcher).
/// Cheap: the work is queued for the indexing thread.
pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) {
@@ -180,26 +154,6 @@ impl ProjectIndex {
self.shared.enqueue(Job::SaveRecent);
}
/// Drops a file from Recent Files (Delete in the ⌘E popup).
pub fn remove_recent(&self, path: &Path) {
let path = match path.to_str() {
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
_ => match self.normalize(path) {
Some(p) => p,
None => return,
},
};
{
let mut r = self.shared.recent.lock();
let before = r.len();
r.retain(|p| p != &path);
if r.len() == before {
return;
}
}
self.shared.enqueue(Job::SaveRecent);
}
/// Recently opened files, most recent first.
pub fn recent_files(&self) -> Vec<PathBuf> {
self.shared.recent.lock().clone()
@@ -223,15 +177,14 @@ impl ProjectIndex {
}
pub fn root(&self) -> &Path {
&self.root
self.shared.filter.root()
}
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
/// Absolute path inside the root, or `None` for paths outside the project / excluded.
fn normalize(&self, path: &Path) -> Option<PathBuf> {
let filter = self.shared.filter();
let root = &self.root;
let root = self.shared.filter.root();
let path = if path.is_absolute() { path.to_owned() } else { root.join(path) };
let path = if filter.contains(&path) {
let path = if path.starts_with(root) {
path
} else {
// Watchers / the UI may report non-canonical spellings (`/tmp` vs `/private/tmp`).
@@ -243,7 +196,7 @@ impl ProjectIndex {
}
}
};
(filter.contains(&path) && filter.rel(&path).is_some()).then_some(path)
(path.starts_with(root) && path != root).then_some(path)
}
}
-28
Переглянути файл
@@ -7,7 +7,6 @@
use crate::data::{FileEntry, IndexData, char_mask};
use crate::{FileMatch, SymbolFilter, SymbolMatch};
use ide_core::SymbolKind;
use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
use rayon::prelude::*;
use std::cell::RefCell;
@@ -420,33 +419,6 @@ pub(crate) fn find_symbols(
.collect()
}
/// Symbols named exactly `name` (and of `kind`, when given), by path then position.
pub(crate) fn symbols_named(data: &IndexData, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
let mask = char_mask(name);
let mut out: Vec<SymbolMatch> = data
.files
.iter()
.flatten()
.flat_map(|e| {
e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map(
move |s| SymbolMatch {
name: s.name.to_string(),
kind: s.kind,
container: s.container.as_deref().map(str::to_owned),
path: e.path.clone().into(),
rel_path: e.rel.to_string(),
range: s.range,
score: 0,
indices: Vec::new(),
},
)
})
.collect();
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
out.truncate(limit);
out
}
#[cfg(test)]
mod tests {
use super::*;
-92
Переглянути файл
@@ -37,7 +37,6 @@ impl Fixture {
let idx = ProjectIndex::open(
&self.root,
&self.cache,
Vec::new(),
vec!["**/node_modules".into(), "**/target".into()],
languages,
syntax,
@@ -193,11 +192,7 @@ fn persistence_skips_unchanged_files_on_reopen() {
assert_eq!(idx.status().files, 8);
assert_eq!(symbols(&idx, "OrderController", SymbolFilter::Types)[0], "OrderController");
assert_eq!(idx.recent_files(), vec![fx.root.join("web/app.py")]);
idx.remove_recent(&fx.root.join("web/app.py"));
assert!(idx.recent_files().is_empty());
assert!(idx.wait_idle(WAIT));
}
assert!(fx.open().recent_files().is_empty(), "removal is persisted");
std::thread::sleep(Duration::from_millis(20));
fx.write("src/main.rs", "fn main() {}\nfn renamed_fn() {}\n");
std::fs::remove_file(fx.root.join("docs/maintenance.md")).unwrap();
@@ -386,90 +381,3 @@ fn synthetic_index_answers_queries() {
assert!(!s.find_symbols("PaySe", SymbolFilter::All, 20).is_empty());
assert!(s.find_symbols("PaySe", SymbolFilter::Types, 20).iter().all(|m| m.kind == SymbolKind::Class));
}
#[test]
fn css_selectors_are_found_by_exact_name() {
let f = Fixture::new(&[
("web/a.css", ".card { --gap: 1px }\n.cardigan {}\n"),
("web/b.scss", ".list { .card { } }\n"),
("web/index.html", "<style>.card{}</style>\n<div class=\"card\"></div>\n"),
]);
let idx = f.open();
let found: Vec<(String, u32)> = idx
.symbols_named(".card", Some(SymbolKind::Class), 10)
.into_iter()
.map(|m| (m.rel_path, m.range.start.line))
.collect();
assert_eq!(found, vec![("web/a.css".into(), 0), ("web/b.scss".into(), 0), ("web/index.html".into(), 0)]);
assert_eq!(idx.symbols_named("--gap", None, 10).len(), 1);
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
}
#[test]
fn content_roots_and_excludes_change_without_reopening() {
let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/gen/out.rs", "fn generated() {}\n")]);
let shared = fx._dir.path().join("shared-lib");
std::fs::create_dir_all(shared.join("src")).unwrap();
std::fs::write(shared.join("src/lib.rs"), "fn gamma() {}\n").unwrap();
let idx = fx.open();
assert!(files(&idx, "lib.rs").is_empty());
let excludes = vec!["**/node_modules".to_owned(), "**/target".to_owned()];
assert!(idx.set_scope(vec![shared.clone()], excludes.clone()));
assert!(!idx.set_scope(vec![shared.clone()], excludes.clone()), "unchanged scope");
assert!(idx.wait_idle(WAIT));
assert_eq!(files(&idx, "lib.rs"), ["shared-lib/src/lib.rs"]);
let gamma = &idx.find_symbols("gamma", SymbolFilter::All, 5)[0];
assert_eq!(gamma.path, dunce::canonicalize(shared.join("src/lib.rs")).unwrap());
// Files created in a content root are picked up incrementally.
std::fs::write(shared.join("src/more.rs"), "fn delta() {}\n").unwrap();
idx.update(&[shared.join("src/more.rs")], &[]);
assert!(idx.wait_idle(WAIT));
assert_eq!(symbols(&idx, "delta", SymbolFilter::All), ["delta"]);
// A new exclude drops what it matches; removing the root drops its files.
let mut more = excludes.clone();
more.push("gen".into());
idx.set_scope(Vec::new(), more);
assert!(idx.wait_idle(WAIT));
assert!(files(&idx, "out.rs").is_empty());
assert!(files(&idx, "lib.rs").is_empty());
assert_eq!(idx.status().files, 1);
drop(idx);
// Extra roots are not persisted: reopening without them lists only the project.
let idx = fx.open();
assert!(symbols(&idx, "gamma", SymbolFilter::All).is_empty());
}
#[test]
fn file_type_changes_reparse_affected_files() {
let fx = Fixture::new(&[("src/main.rs", "fn alpha() {}\n"), ("src/legacy.inc", "fn beta() {}\n")]);
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
let idx = ProjectIndex::open(
&fx.root,
&fx.cache,
Vec::new(),
Vec::new(),
languages.clone(),
Arc::new(Syntax::new()),
Arc::new(NullSink),
)
.unwrap();
assert!(idx.wait_idle(WAIT));
assert!(symbols(&idx, "beta", SymbolFilter::All).is_empty(), "plain text has no symbols");
let parsed = idx.shared.parsed.load(Ordering::SeqCst);
let before = Arc::new(languages.snapshot());
let mut ft = ide_language::FileTypes::default();
ft.associations.insert(
"rust".into(),
ide_core::settings::FileTypeAssociation { patterns: vec!["*.inc".into()], ..Default::default() },
);
assert!(languages.set_file_types(ft));
idx.languages_changed(before);
assert!(idx.wait_idle(WAIT));
assert_eq!(symbols(&idx, "beta", SymbolFilter::All), ["beta"]);
assert_eq!(idx.shared.parsed.load(Ordering::SeqCst), parsed + 1, "only the affected file is re-parsed");
}
+22 -74
Переглянути файл
@@ -24,11 +24,6 @@ pub(crate) enum Job {
Changed(Vec<PathBuf>),
Removed(Vec<PathBuf>),
SaveRecent,
/// The roots or excludes changed: scan again (unchanged files are kept).
Rescan,
/// File types changed: re-parse the indexed files whose language under the
/// previous registry differs from the current one.
Reparse(std::sync::Arc<LanguageRegistry>),
}
#[derive(Default)]
@@ -39,7 +34,7 @@ struct Queue {
}
pub(crate) struct Shared {
filter: RwLock<std::sync::Arc<PathFilter>>,
pub filter: PathFilter,
pub languages: std::sync::Arc<LanguageRegistry>,
pub syntax: std::sync::Arc<Syntax>,
pub sink: SharedSink,
@@ -65,7 +60,7 @@ impl Shared {
store: Option<Store>,
) -> Self {
Self {
filter: RwLock::new(std::sync::Arc::new(filter)),
filter,
languages,
syntax,
sink,
@@ -81,14 +76,6 @@ impl Shared {
}
}
pub(crate) fn filter(&self) -> std::sync::Arc<PathFilter> {
self.filter.read().clone()
}
pub(crate) fn set_filter(&self, filter: PathFilter) {
*self.filter.write() = std::sync::Arc::new(filter);
}
pub(crate) fn enqueue(&self, job: Job) {
self.queue.lock().jobs.push_back(job);
self.wake.notify_one();
@@ -163,7 +150,7 @@ impl Shared {
fn load_persisted(&self) {
let Some(store) = &self.store else { return };
let root = self.filter().root().to_owned();
let root = self.filter.root().to_owned();
match store.load() {
Ok(records) => {
let entries: Vec<FileEntry> =
@@ -211,31 +198,26 @@ impl Shared {
done: false,
});
let filter = self.filter();
let mut found = Vec::new();
for root in filter.roots() {
found.extend(filter.walk(root, &self.cancelled));
}
let found = self.filter.walk(self.filter.root(), &self.cancelled);
if self.is_cancelled() {
return self.end_scan(task);
}
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
let (todo, stale): (Vec<&Found>, Vec<PathBuf>) = {
let (todo, stale): (Vec<&Found>, Vec<String>) = {
let d = self.data.read();
let todo = found
.iter()
.filter(|f| d.get(&f.path).is_none_or(|e| e.mtime != f.mtime || e.size != f.size))
.collect();
let stale = d.paths().filter(|p| !seen.contains(p.as_path())).cloned().collect();
let stale = d.paths().filter(|p| !seen.contains(p.as_path())).filter_map(|p| self.filter.rel(p)).collect();
(todo, stale)
};
if !stale.is_empty() {
let mut d = self.data.write();
for path in &stale {
d.remove(path);
for rel in &stale {
d.remove(&self.filter.root().join(rel));
}
}
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
self.persist(&[], &stale, false);
let total = todo.len();
@@ -245,7 +227,7 @@ impl Shared {
if self.is_cancelled() {
return self.end_scan(task);
}
self.index_files(chunk.iter().copied(), false);
self.index_files(chunk.iter().copied());
done += chunk.len();
if last_progress.elapsed() >= PROGRESS_EVERY {
last_progress = Instant::now();
@@ -279,18 +261,16 @@ impl Shared {
}
/// Extracts records in parallel, then publishes them to memory and disk.
/// `force` re-parses files whose content is unchanged (their language changed).
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>, force: bool) {
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>) {
let files: Vec<&Found> = files.collect();
let filter = self.filter();
let extracted: Vec<(String, FileRecord, PathBuf)> = files
.par_iter()
.filter_map(|f| {
if self.is_cancelled() {
return None;
}
let rel = filter.rel(&f.path)?;
let prev_hash = if force { None } else { self.data.read().get(&f.path).map(|e| e.hash) };
let rel = self.filter.rel(&f.path)?;
let prev_hash = self.data.read().get(&f.path).map(|e| e.hash);
match self.extract(f, prev_hash) {
Extracted::Unchanged => {
// Same content, new mtime: keep the symbols, refresh metadata.
@@ -308,7 +288,7 @@ impl Shared {
return;
}
let puts: Vec<(String, FileRecord)> =
extracted.iter().filter_map(|(_, rec, path)| Some((filter.store_key(path)?, rec.clone()))).collect();
extracted.iter().map(|(rel, rec, _)| (rel.clone(), rec.clone())).collect();
{
let entries: Vec<FileEntry> =
extracted.into_iter().map(|(rel, rec, path)| FileEntry::new(path, rel, rec)).collect();
@@ -366,24 +346,13 @@ impl Shared {
let mut changed: Vec<PathBuf> = Vec::new();
let mut removed: Vec<PathBuf> = Vec::new();
let mut save_recent = false;
let mut rescan = false;
let mut reparse: Vec<std::sync::Arc<LanguageRegistry>> = Vec::new();
for job in jobs {
match job {
Job::Changed(p) => changed.extend(p),
Job::Removed(p) => removed.extend(p),
Job::SaveRecent => save_recent = true,
Job::Rescan => rescan = true,
Job::Reparse(before) => reparse.push(before),
}
}
if rescan {
// The scan also picks up whatever `changed` / `removed` reported.
self.full_scan();
changed.clear();
removed.clear();
}
let filter = self.filter();
let mut touched = false;
// Removals first; a path removed then re-created shows up in `changed` too.
@@ -394,11 +363,11 @@ impl Shared {
continue;
}
let mut d = self.data.write();
let gone = match d.remove(&path) {
Some(_) => vec![path],
None => d.remove_tree(&path),
};
deletes.extend(gone.iter().filter_map(|p| filter.store_key(p)));
if let Some(e) = d.remove(&path) {
deletes.push(e.rel.into_string());
} else {
deletes.extend(d.remove_tree(&path));
}
}
if !deletes.is_empty() {
touched = true;
@@ -412,11 +381,11 @@ impl Shared {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
if filter.is_excluded(&path, meta.is_dir()) {
if self.filter.is_excluded(&path, meta.is_dir()) {
continue;
}
if meta.is_dir() {
files.extend(filter.walk(&path, &self.cancelled));
files.extend(self.filter.walk(&path, &self.cancelled));
} else if meta.is_file() {
files.push(Found { mtime: mtime_of(&meta), size: meta.len(), path });
}
@@ -434,32 +403,11 @@ impl Shared {
if self.is_cancelled() {
return;
}
self.index_files(chunk.iter(), false);
}
}
for before in reparse {
let affected: Vec<Found> = {
let d = self.data.read();
d.paths()
.filter(|p| before.detect(p, None) != self.languages.detect(p, None))
.filter_map(|p| {
let e = d.get(p)?;
Some(Found { path: p.clone(), mtime: e.mtime, size: e.size })
})
.collect()
};
if !affected.is_empty() {
touched = true;
for chunk in affected.chunks(CHUNK) {
if self.is_cancelled() {
return;
}
self.index_files(chunk.iter(), true);
}
self.index_files(chunk.iter());
}
}
if save_recent && let Some(store) = &self.store {
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| self.filter.rel(p)).collect();
if let Err(e) = store.save_recent(&rels) {
tracing::warn!("index cache: saving recent files failed: {e}");
}
+8 -118
Переглянути файл
@@ -1,8 +1,7 @@
//! Transport shared by the LSP and DAP clients.
//!
//! * [`framing`]: `Content-Length` header framing over any async byte stream
//! (used by both protocols), and newline-delimited JSON ([`Framing::Lines`],
//! the Agent Client Protocol).
//! (used by both protocols).
//! * [`Peer`]: a JSON-RPC 2.0 endpoint with request/response correlation,
//! cancellation (`$/cancelRequest`) and handlers for server→client traffic.
@@ -89,34 +88,6 @@ pub mod framing {
writer.write_all(&buf).await?;
writer.flush().await
}
/// Reads one newline-terminated message, skipping blank lines.
pub async fn read_line_message<R: AsyncBufRead + Unpin>(reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
let mut line = Vec::new();
loop {
line.clear();
let n = (&mut *reader).take(MAX_MESSAGE_LEN as u64 + 1).read_until(b'\n', &mut line).await?;
if n == 0 {
return Ok(None);
}
if line.len() > MAX_MESSAGE_LEN {
return Err(Error::new(ErrorKind::InvalidData, "message too large"));
}
let text = trim_line(&line);
if !text.iter().all(u8::is_ascii_whitespace) {
return Ok(Some(text.to_vec()));
}
}
}
/// Writes one message followed by `\n` and flushes once.
pub async fn write_line_message<W: AsyncWrite + Unpin>(writer: &mut W, body: &[u8]) -> std::io::Result<()> {
let mut buf = Vec::with_capacity(body.len() + 1);
buf.extend_from_slice(body);
buf.push(b'\n');
writer.write_all(&buf).await?;
writer.flush().await
}
}
use parking_lot::Mutex;
@@ -239,32 +210,6 @@ impl Inner {
}
}
/// How messages are delimited on the wire.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Framing {
/// `Content-Length` headers (LSP, DAP).
#[default]
ContentLength,
/// One JSON message per line (Agent Client Protocol).
Lines,
}
impl Framing {
async fn read<R: tokio::io::AsyncBufRead + Unpin>(self, reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
match self {
Framing::ContentLength => framing::read_message(reader).await,
Framing::Lines => framing::read_line_message(reader).await,
}
}
async fn write<W: AsyncWrite + Unpin>(self, writer: &mut W, body: &[u8]) -> std::io::Result<()> {
match self {
Framing::ContentLength => framing::write_message(writer, body).await,
Framing::Lines => framing::write_line_message(writer, body).await,
}
}
}
/// A connected JSON-RPC peer. Cloning shares the connection.
#[derive(Clone)]
pub struct Peer {
@@ -293,26 +238,11 @@ impl Peer {
env: &[(String, String)],
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Self> {
Self::spawn_framed(command, args, cwd, env, handler, on_stderr, Framing::ContentLength)
}
/// [`spawn`](Self::spawn) with the given wire framing.
pub fn spawn_framed(
command: &str,
args: &[String],
cwd: &std::path::Path,
env: &[(String, String)],
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
framing: Framing,
) -> std::io::Result<Self> {
use std::process::Stdio;
let mut cmd = tokio::process::Command::new(command);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(ide_core::process::shell_env())
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -324,7 +254,7 @@ impl Peer {
let stderr = child.stderr.take();
let pid = child.id();
let peer = Self::start(stdout, stdin, handler, false, pid, framing);
let peer = Self::start(stdout, stdin, handler, false, pid);
if let Some(stderr) = stderr {
let name = command.to_owned();
@@ -345,13 +275,7 @@ impl Peer {
});
}
peer.supervise(child);
Ok(peer)
}
/// Kills `child` when the connection is torn down; closes the connection when it exits.
fn supervise(&self, mut child: tokio::process::Child) {
let inner = self.inner.clone();
let inner = peer.inner.clone();
tokio::spawn(async move {
let status = tokio::select! {
status = child.wait() => status.ok(),
@@ -362,6 +286,7 @@ impl Peer {
};
inner.mark_closed(status.and_then(|s| s.code()));
});
Ok(peer)
}
/// Speaks JSON-RPC over arbitrary byte streams (in-memory pipes in tests, TCP sockets).
@@ -373,45 +298,10 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, Framing::ContentLength)
Self::start(reader, writer, handler, true, None)
}
/// [`connect`](Self::connect) with the given wire framing.
pub fn connect_framed<R, W>(reader: R, writer: W, handler: Arc<dyn Handler>, framing: Framing) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, framing)
}
/// [`Peer::connect`] over streams served by `child` (a server reached over a socket
/// it listens on): the child is killed with the connection, and its exit closes it.
///
/// Must be called from within a Tokio runtime.
pub fn connect_with_child<R, W>(
reader: R,
writer: W,
handler: Arc<dyn Handler>,
child: tokio::process::Child,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let peer = Self::start(reader, writer, handler, true, child.id(), Framing::ContentLength);
peer.supervise(child);
peer
}
fn start<R, W>(
reader: R,
mut writer: W,
handler: Arc<dyn Handler>,
close_on_eof: bool,
pid: Option<u32>,
framing: Framing,
) -> Self
fn start<R, W>(reader: R, mut writer: W, handler: Arc<dyn Handler>, close_on_eof: bool, pid: Option<u32>) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
@@ -439,7 +329,7 @@ impl Peer {
_ = kill.cancelled() => None,
};
let Some(body) = body else { break };
if let Err(e) = framing.write(&mut writer, &body).await {
if let Err(e) = framing::write_message(&mut writer, &body).await {
tracing::debug!("jsonrpc write failed: {e}");
if let Some(inner) = weak.upgrade() {
inner.close_transport();
@@ -478,7 +368,7 @@ impl Peer {
let mut reader = BufReader::new(reader);
loop {
let msg = tokio::select! {
msg = framing.read(&mut reader) => msg,
msg = framing::read_message(&mut reader) => msg,
_ = inner.kill.cancelled() => break,
};
match msg {
-22
Переглянути файл
@@ -120,28 +120,6 @@ async fn request_response_and_errors() {
assert!(matches!(err, RpcError::Protocol(_)));
}
#[tokio::test]
async fn line_framing_round_trips_and_skips_blank_lines() {
let mut buf = Vec::new();
framing::write_line_message(&mut buf, br#"{"a":1}"#).await.unwrap();
buf.extend_from_slice(b"\r\n\n{\"b\":2}\r\n");
let mut reader = tokio::io::BufReader::new(&buf[..]);
assert_eq!(framing::read_line_message(&mut reader).await.unwrap().unwrap(), br#"{"a":1}"#);
assert_eq!(framing::read_line_message(&mut reader).await.unwrap().unwrap(), br#"{"b":2}"#);
assert!(framing::read_line_message(&mut reader).await.unwrap().is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn line_framed_peers_talk() {
let (a_io, b_io) = duplex(64 * 1024);
let (ar, aw) = tokio::io::split(a_io);
let (br, bw) = tokio::io::split(b_io);
let client = Peer::connect_framed(ar, aw, Arc::new(NoopHandler), Framing::Lines);
let _server = Peer::connect_framed(br, bw, Arc::new(Recorder::default()), Framing::Lines);
let v: Value = client.request("echo", json!({"x": "line\nbreak"}), None).await.unwrap();
assert_eq!(v, json!({"x": "line\nbreak"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn notifications_arrive_in_order() {
let rec = Arc::new(Recorder::default());
-1
Переглянути файл
@@ -53,7 +53,6 @@ tree-sitter-xml = "0.7.0"
tree-sitter-haskell = "0.23.1"
tree-sitter-dart = "0.2.0"
tree-sitter-graphql = "0.3.0"
tree-sitter-gdscript = "6.1.0"
[dev-dependencies]
criterion = { version = "0.5", default-features = false }
-60
Переглянути файл
@@ -1,60 +0,0 @@
; GDScript highlighting (the grammar crate ships no query). Later patterns win.
(identifier) @variable
(name) @variable
(comment) @comment
[(region_start) (region_end)] @comment
(string) @string
(escape_sequence) @string.escape
[(string_name) (node_path) (get_node)] @string.special
(integer) @number
(float) @number
[(true) (false) (null)] @constant.builtin
(type) @type
(type (identifier) @type)
(extends_statement (type) @type)
(class_name_statement name: (name) @type)
(class_definition name: (name) @type)
(enum_definition name: (name) @type)
(enumerator left: (identifier) @constant)
(function_definition name: (name) @function.definition)
(constructor_definition "_init" @function.definition)
(lambda name: (name) @function.definition)
(signal_statement name: (name) @function.definition)
(call (identifier) @function)
(attribute_call (identifier) @function)
(base_call (identifier) @function)
(attribute (identifier) (identifier) @variable.member)
((identifier) @constant
(#lua-match? @constant "^[A-Z][A-Z_0-9]*$"))
((identifier) @variable.builtin
(#lua-match? @variable.builtin "^self$"))
(const_statement name: (name) @constant)
(typed_parameter (identifier) @variable.parameter)
(default_parameter (identifier) @variable.parameter)
(typed_default_parameter (identifier) @variable.parameter)
(annotation "@" @attribute (identifier) @attribute)
[(remote_keyword) (static_keyword)] @keyword
[(breakpoint_statement) (pass_statement) (break_statement) (continue_statement)] @keyword
[
"if" "elif" "else" "for" "while" "match" "when" "return" "await"
"func" "class" "class_name" "extends" "signal" "enum" "const" "var"
"set" "get" "setget" "onready" "export" "in" "is" "as" "and" "or" "not"
] @keyword
[
"+" "-" "*" "/" "%" "**" "<<" ">>" "&" "|" "^" "~" "!" "&&" "||"
"==" "!=" "<" "<=" ">" ">=" "=" ":=" "+=" "-=" "*=" "/=" "%=" "**="
"<<=" ">>=" "&=" "|=" "^=" "->"
] @operator
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
["," "." ":" ";"] @punctuation.delimiter
-14
Переглянути файл
@@ -1,14 +0,0 @@
(class_name_statement name: (name) @name) @def.class
(class_definition name: (name) @name) @def.class
(function_definition name: (name) @name parameters: (parameters) @detail) @def.function
(constructor_definition "_init" @name parameters: (parameters) @detail) @def.constructor
(signal_statement name: (name) @name) @def.event
(enum_definition name: (name) @name) @def.enum
(enumerator left: (identifier) @name) @def.enum_member
(const_statement name: (name) @name) @def.constant
(source (variable_statement name: (name) @name) @def.field)
(source (export_variable_statement name: (name) @name) @def.field)
(source (onready_variable_statement name: (name) @name) @def.field)
(class_body (variable_statement name: (name) @name) @def.field)
(class_body (export_variable_statement name: (name) @name) @def.field)
(class_body (onready_variable_statement name: (name) @name) @def.field)
-49
Переглянути файл
@@ -1,49 +0,0 @@
; GraphQL highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(description (string_value) @comment.doc)
(string_value) @string
(int_value) @number
(float_value) @number
[(boolean_value) (null_value)] @keyword
(enum_value (name) @constant)
(variable) @variable
(argument (name) @variable.parameter)
(input_value_definition (name) @variable.parameter)
(object_field (name) @property)
(field (name) @property)
(alias (name) @property)
(field_definition (name) @property)
(enum_value_definition (enum_value (name) @constant))
(named_type (name) @type)
(object_type_definition (name) @type)
(interface_type_definition (name) @type)
(union_type_definition (name) @type)
(enum_type_definition (name) @type)
(input_object_type_definition (name) @type)
(scalar_type_definition (name) @type)
(object_type_extension (name) @type)
(interface_type_extension (name) @type)
(union_type_extension (name) @type)
(enum_type_extension (name) @type)
(input_object_type_extension (name) @type)
(scalar_type_extension (name) @type)
(operation_definition (name) @function)
(fragment_name (name) @function)
(directive_definition (name) @attribute)
(directive (name) @attribute)
"@" @attribute
(directive_location) @constant
(operation_type) @keyword
[
"query" "mutation" "subscription" "fragment" "on" "type" "interface" "union"
"enum" "input" "scalar" "schema" "extend" "implements" "directive" "repeatable"
] @keyword
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
[":" "=" "|" "&" "!" "..."] @punctuation.delimiter
-29
Переглянути файл
@@ -1,29 +0,0 @@
; HCL / Terraform highlighting (the grammar crate ships no query). Later patterns win.
(comment) @comment
(string_lit) @string
(quoted_template) @string
(heredoc_template) @string
[(heredoc_start) (heredoc_identifier)] @string.special
(template_literal) @string
(numeric_lit) @number
[(bool_lit) (null_lit)] @keyword
(identifier) @variable
(attribute (identifier) @property)
(object_elem key: (expression (variable_expr (identifier) @property)))
(get_attr (identifier) @property)
(function_call (identifier) @function)
; `resource "aws_instance" "web" {`
(block (identifier) @keyword)
(block (string_lit (template_literal) @type))
(template_interpolation) @embedded
[(template_interpolation_start) (template_interpolation_end)] @punctuation.special
[(template_directive_start) (template_directive_end) (strip_marker)] @punctuation.special
["for" "in" "if" "else" "endfor" "endif"] @keyword
(operation) @operator
["!" "!=" "%" "&&" "*" "+" "-" "/" "<" "<=" "==" ">" ">=" "||" "?" "=>"] @operator
["=" ":" "," "."] @punctuation.delimiter
["(" ")" "[" "]" "{" "}" "[*]" ".*"] @punctuation.bracket
+2 -33
Переглянути файл
@@ -11,12 +11,8 @@ use std::collections::BTreeMap;
mod registry;
mod syntax;
pub use registry::{FileTypes, LanguageRegistry};
pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
};
pub use registry::LanguageRegistry;
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -75,14 +71,6 @@ pub struct LanguageServerConfig {
/// Human hint shown when the binary is missing.
#[serde(default)]
pub install_hint: Option<String>,
/// `host:port` of a server that speaks LSP over TCP (Godot's editor). Connects
/// there when something listens; otherwise starts `command` (when installed)
/// and connects once it accepts: to `127.0.0.1:${port}` when the arguments
/// contain `${port}` (a free port), else to this address. `${root}` in the
/// arguments is the workspace root. A server reached without starting it is
/// never shut down or killed by the IDE.
#[serde(default)]
pub connect: Option<String>,
/// An alternative to the servers listed before it (pyright after
/// basedpyright): only used while none of those is installed.
#[serde(default)]
@@ -104,10 +92,6 @@ pub struct DebuggerConfig {
/// `stdio` or `tcp`.
#[serde(default = "default_transport")]
pub transport: String,
/// `tcp` only: `host:port` of an adapter running inside another program (the
/// Godot editor). Used when it accepts connections; otherwise `command` is started.
#[serde(default)]
pub connect: Option<String>,
#[serde(default)]
pub install_hint: Option<String>,
}
@@ -131,18 +115,6 @@ pub struct LanguageInfo {
#[serde(default)]
#[specta(optional)]
pub debuggable: bool,
/// Names of the configured language servers (Settings › Inspections).
#[serde(default)]
#[specta(optional)]
pub language_servers: Vec<String>,
/// Exact file names and file-name patterns of the definition (Settings › File Types).
#[serde(default)]
#[specta(optional)]
pub filenames: Vec<String>,
/// First-line regex of the definition (shebangs, `<?php`).
#[serde(default)]
#[specta(optional)]
pub first_line: Option<String>,
}
impl From<&LanguageConfig> for LanguageInfo {
@@ -156,9 +128,6 @@ impl From<&LanguageConfig> for LanguageInfo {
block_comment: c.block_comment.clone(),
indent: c.indent,
debuggable: c.debugger.is_some(),
language_servers: c.language_servers.iter().map(|s| s.name.clone()).collect(),
filenames: c.filenames.clone(),
first_line: c.first_line.clone(),
}
}
}
+48 -281
Переглянути файл
@@ -1,10 +1,7 @@
use crate::LanguageConfig;
use ide_core::settings::{FileSettings, FileTypeAssociation};
use ide_core::{IdeError, IdeResult, LanguageId};
use parking_lot::RwLock;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::collections::HashMap;
use std::path::Path;
/// Built-in definitions, embedded at compile time. Add new languages here.
const BUILTIN: &[(&str, &str)] = &[
@@ -22,12 +19,9 @@ const BUILTIN: &[(&str, &str)] = &[
("erlang", include_str!("../../../languages/erlang.toml")),
("fsharp", include_str!("../../../languages/fsharp.toml")),
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
("godot-resource", include_str!("../../../languages/godot-resource.toml")),
("graphql", include_str!("../../../languages/graphql.toml")),
("groovy", include_str!("../../../languages/groovy.toml")),
("haskell", include_str!("../../../languages/haskell.toml")),
@@ -84,130 +78,11 @@ const BUILTIN: &[(&str, &str)] = &[
pub struct LanguageRegistry {
languages: Vec<LanguageConfig>,
/// Lookup tables of the definitions with the user's file types applied.
tables: RwLock<Arc<Tables>>,
file_types: RwLock<FileTypes>,
}
/// The user's file type associations (Settings › Editor › File Types) and
/// per-file overrides (Override File Type), resolved for one project.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FileTypes {
/// Language id → patterns added to / removed from its definition.
pub associations: BTreeMap<String, FileTypeAssociation>,
/// Absolute path → language id.
pub overrides: HashMap<PathBuf, LanguageId>,
}
impl FileTypes {
/// From `files.fileTypes` / `files.fileTypeOverrides`; relative override paths resolve against `root`.
pub fn from_settings(files: &FileSettings, root: Option<&Path>) -> Self {
let overrides = files
.file_type_overrides
.iter()
.filter(|(_, lang)| !lang.trim().is_empty())
.filter_map(|(path, lang)| {
let p = Path::new(path.as_str());
let abs = if p.is_absolute() { p.to_path_buf() } else { root?.join(p) };
Some((abs, LanguageId::new(lang.trim())))
})
.collect();
Self { associations: files.file_types.clone(), overrides }
}
}
#[derive(Default)]
struct Tables {
by_ext: HashMap<String, usize>,
by_name: HashMap<String, usize>,
/// File-name patterns with wildcards, e.g. `Dockerfile.*`, `tsconfig.*.json`; the user's first.
/// File-name patterns containing `*`, e.g. `Dockerfile.*`, `tsconfig.*.json`.
name_globs: Vec<(String, usize)>,
/// Interpreter names of user hashbang patterns.
hashbangs: Vec<(String, usize)>,
first_line: Vec<(regex_lite::Regex, usize)>,
overrides: HashMap<PathBuf, usize>,
}
/// How a file name pattern is looked up.
enum Pattern<'a> {
/// `*.ext` (lower-cased).
Ext(String),
Name(&'a str),
Glob(&'a str),
}
fn classify(pattern: &str) -> Pattern<'_> {
let wild = |s: &str| s.contains(['*', '?']);
match pattern.strip_prefix("*.") {
Some(ext) if !ext.is_empty() && !wild(ext) => Pattern::Ext(ext.to_ascii_lowercase()),
_ if wild(pattern) => Pattern::Glob(pattern),
_ => Pattern::Name(pattern),
}
}
impl Tables {
fn build(languages: &[LanguageConfig], file_types: &FileTypes) -> Self {
let mut t = Tables::default();
let index_of = |id: &str| languages.iter().position(|l| l.id.as_str() == id);
let removed = |l: &LanguageConfig, pattern: &str| {
file_types.associations.get(l.id.as_str()).is_some_and(|a| {
a.removed_patterns.iter().any(|r| r.trim() == pattern || r.trim().eq_ignore_ascii_case(pattern))
})
};
let mut builtin_globs = Vec::new();
for (i, l) in languages.iter().enumerate() {
for ext in &l.extensions {
if !removed(l, &format!("*.{ext}")) {
t.by_ext.insert(ext.to_ascii_lowercase(), i);
}
}
for name in l.filenames.iter().filter(|n| !removed(l, n)) {
if name.contains(['*', '?']) {
builtin_globs.push((name.clone(), i));
} else {
t.by_name.insert(name.clone(), i);
}
}
if let Some(pattern) = l.first_line.as_deref() {
match regex_lite::Regex::new(pattern) {
Ok(re) => t.first_line.push((re, i)),
Err(e) => tracing::warn!("language {}: invalid first-line pattern: {e}", l.id),
}
}
}
// The user's patterns win over the definitions'.
let mut user_globs = Vec::new();
for (id, assoc) in &file_types.associations {
let Some(i) = index_of(id) else { continue };
for pattern in assoc.patterns.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
match classify(pattern) {
Pattern::Ext(ext) => {
t.by_ext.insert(ext, i);
}
Pattern::Name(name) => {
t.by_name.insert(name.to_owned(), i);
}
Pattern::Glob(glob) => user_globs.push((glob.to_owned(), i)),
}
}
for h in assoc.hashbangs.iter().map(|h| h.trim()).filter(|h| !h.is_empty()) {
t.hashbangs.push((h.to_owned(), i));
}
}
// More specific (longer) patterns first: `tsconfig.*.json` before `*.json`-like ones.
user_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
builtin_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
t.name_globs = user_globs.into_iter().chain(builtin_globs).collect();
t.overrides =
file_types.overrides.iter().filter_map(|(p, id)| Some((p.clone(), index_of(id.as_str())?))).collect();
t
}
}
/// Whether the `#!` line runs `interpreter` (`#!/usr/bin/env node`, `#!/bin/node -x` for `node`).
fn hashbang_runs(line: &str, interpreter: &str) -> bool {
let Some(rest) = line.strip_prefix("#!") else { return false };
rest.split(|c: char| c.is_whitespace() || c == '/').any(|token| token == interpreter)
}
impl LanguageRegistry {
@@ -241,31 +116,31 @@ impl LanguageRegistry {
None => languages.push(cfg),
}
}
let tables = Tables::build(&languages, &FileTypes::default());
Self { languages, tables: RwLock::new(Arc::new(tables)), file_types: RwLock::default() }
}
/// A registry with the same definitions and no user file types (one per project).
pub fn fork(&self) -> Self {
Self::from_configs(self.languages.clone())
}
/// A copy with the same definitions and file types (to compare detection before / after a change).
pub fn snapshot(&self) -> Self {
let copy = self.fork();
copy.set_file_types(self.file_types.read().clone());
copy
}
/// Applies the user's file types; returns whether they changed.
pub fn set_file_types(&self, file_types: FileTypes) -> bool {
let mut current = self.file_types.write();
if *current == file_types {
return false;
let mut by_ext = HashMap::new();
let mut by_name = HashMap::new();
let mut name_globs = Vec::new();
let mut first_line = Vec::new();
for (i, l) in languages.iter().enumerate() {
for ext in &l.extensions {
by_ext.insert(ext.to_ascii_lowercase(), i);
}
for name in &l.filenames {
if name.contains('*') {
name_globs.push((name.clone(), i));
} else {
by_name.insert(name.clone(), i);
}
}
if let Some(pattern) = l.first_line.as_deref() {
match regex_lite::Regex::new(pattern) {
Ok(re) => first_line.push((re, i)),
Err(e) => tracing::warn!("language {}: invalid first-line pattern: {e}", l.id),
}
}
}
*self.tables.write() = Arc::new(Tables::build(&self.languages, &file_types));
*current = file_types;
true
// More specific (longer) patterns first: `tsconfig.*.json` before `*.json`-like ones.
name_globs.sort_by_key(|(p, _): &(String, usize)| std::cmp::Reverse(p.len()));
Self { languages, by_ext, by_name, name_globs, first_line }
}
pub fn all(&self) -> Vec<LanguageConfig> {
@@ -276,67 +151,48 @@ impl LanguageRegistry {
self.languages.iter().find(|l| &l.id == id).cloned()
}
/// Detects by Override File Type, exact file name, then file-name pattern
/// (`Dockerfile.*`), then extension (longest compound first, e.g. `d.ts`),
/// then hashbang / first line; falls back to plaintext. The user's patterns
/// win over the definitions'.
/// Detects by exact file name, then file-name pattern (`Dockerfile.*`), then
/// extension (longest compound first, e.g. `d.ts`), then first line; falls
/// back to plaintext.
pub fn detect(&self, path: &Path, first_line: Option<&str>) -> LanguageId {
let t = self.tables.read().clone();
if !t.overrides.is_empty()
&& let Some(&i) = t.overrides.get(path)
{
return self.languages[i].id.clone();
}
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
if let Some(&i) = t.by_name.get(file_name) {
if let Some(&i) = self.by_name.get(file_name) {
return self.languages[i].id.clone();
}
if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
if let Some((_, i)) = self.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
return self.languages[*i].id.clone();
}
let lower = file_name.to_ascii_lowercase();
let mut rest = lower.as_str();
while let Some(dot) = rest.find('.') {
rest = &rest[dot + 1..];
if let Some(&i) = t.by_ext.get(rest) {
if let Some(&i) = self.by_ext.get(rest) {
return self.languages[i].id.clone();
}
}
if let Some(line) = first_line {
if let Some((_, i)) = t.hashbangs.iter().find(|(h, _)| hashbang_runs(line, h)) {
return self.languages[*i].id.clone();
}
if let Some((_, i)) = t.first_line.iter().find(|(re, _)| re.is_match(line)) {
return self.languages[*i].id.clone();
}
if let Some(line) = first_line
&& let Some((_, i)) = self.first_line.iter().find(|(re, _)| re.is_match(line))
{
return self.languages[*i].id.clone();
}
LanguageId::plain_text()
}
}
/// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal.
/// `*` matches any (possibly empty) run of characters; everything else is literal.
fn wildcard_match(pattern: &str, name: &str) -> bool {
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
let (mut pi, mut ni) = (0, 0);
// Position after the last `*` and the name position it is matched up to.
let mut star: Option<(usize, usize)> = None;
while ni < n.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
pi += 1;
ni += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi + 1, ni));
pi += 1;
} else if let Some((sp, sn)) = star {
pi = sp;
ni = sn + 1;
star = Some((sp, sn + 1));
} else {
return false;
let mut parts = pattern.split('*');
let first = parts.next().unwrap_or_default();
let Some(mut rest) = name.strip_prefix(first) else { return false };
let parts: Vec<&str> = parts.collect();
let Some((last, middle)) = parts.split_last() else { return rest.is_empty() };
for part in middle {
match rest.find(part) {
Some(i) => rest = &rest[i + part.len()..],
None => return false,
}
}
p[pi..].iter().all(|&c| c == '*')
rest.len() >= last.len() && rest.ends_with(last)
}
fn parse(src: &str) -> Result<LanguageConfig, String> {
@@ -545,17 +401,10 @@ mod tests {
}
for ls in &cfg.language_servers {
assert!(!ls.command.is_empty() && ls.install_hint.is_some(), "{name}: {} incomplete", ls.name);
if let Some(addr) = &ls.connect {
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
if let Some(d) = &cfg.debugger {
assert!(matches!(d.transport.as_str(), "stdio" | "tcp"), "{name}: bad transport");
assert!(d.install_hint.is_some(), "{name}: debugger without install hint");
if let Some(addr) = &d.connect {
assert_eq!(d.transport, "tcp", "{name}: `connect` needs the tcp transport");
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
for ext in &cfg.extensions {
assert_eq!(ext, &ext.to_ascii_lowercase(), "{name}: extensions must be lower case");
@@ -689,13 +538,6 @@ mod tests {
(".gitignore", "ignore"),
(".gitattributes", "gitattributes"),
("server.log", "log"),
("player.gd", "gdscript"),
("main.tscn", "godot-resource"),
("theme.tres", "godot-resource"),
("project.godot", "godot-resource"),
("icon.svg.import", "godot-resource"),
("export_presets.cfg", "godot-resource"),
("water.gdshader", "gdshader"),
("notes.txt", "plaintext"),
];
for (path, id) in cases {
@@ -703,27 +545,6 @@ mod tests {
}
}
#[test]
fn gdscript_definition() {
let reg = reg();
let gd = reg.get(&LanguageId::new("gdscript")).unwrap();
assert_eq!(gd.line_comment.as_deref(), Some("#"));
let indent = gd.indent.unwrap();
assert!(!indent.insert_spaces, "Godot indents with tabs");
assert_eq!(gd.tree_sitter.as_deref(), Some("gdscript"));
let ls = &gd.language_servers[0];
assert_eq!((ls.name.as_str(), ls.command.as_str()), ("godot", "godot"));
assert_eq!(ls.connect.as_deref(), Some("127.0.0.1:6005"));
assert_eq!(ls.root_markers, ["project.godot"]);
assert!(ls.args.iter().any(|a| a == "${port}") && ls.args.iter().any(|a| a == "${root}"));
let dbg = gd.debugger.as_ref().unwrap();
assert_eq!((dbg.adapter.as_str(), dbg.transport.as_str()), ("godot", "tcp"));
assert_eq!(dbg.connect.as_deref(), Some("127.0.0.1:6006"));
assert!(dbg.args.iter().any(|a| a == "--dap-port"));
let res = reg.get(&LanguageId::new("godot-resource")).unwrap();
assert_eq!(res.line_comment.as_deref(), Some(";"));
}
#[test]
fn detects_shebangs() {
let reg = reg();
@@ -752,60 +573,6 @@ mod tests {
assert!(wildcard_match("*.Dockerfile", "web.Dockerfile"));
assert!(wildcard_match("a*b*c", "aXbYc"));
assert!(!wildcard_match("a*b*c", "aXcYb"));
assert!(wildcard_match("file?.txt", "file1.txt"));
assert!(!wildcard_match("file?.txt", "file.txt"));
assert!(wildcard_match("*", ""));
assert!(wildcard_match("a**", "abc"));
}
fn assoc(patterns: &[&str], removed: &[&str], hashbangs: &[&str]) -> FileTypeAssociation {
let v = |xs: &[&str]| xs.iter().map(|s| (*s).to_owned()).collect();
FileTypeAssociation { patterns: v(patterns), removed_patterns: v(removed), hashbangs: v(hashbangs) }
}
#[test]
fn user_file_types_add_remove_and_win() {
let reg = reg();
let mut ft = FileTypes::default();
ft.associations
.insert("python".into(), assoc(&["*.foo", "Pipfile.lock", "build_*.cfg", "*.LOG"], &[], &["mypy"]));
ft.associations.insert("groovy".into(), assoc(&[], &["Jenkinsfile"], &[]));
ft.associations.insert("shellscript".into(), assoc(&["Jenkinsfile"], &[], &[]));
ft.associations.insert("rust".into(), assoc(&[], &["*.rs"], &[]));
assert!(reg.set_file_types(ft.clone()));
assert!(!reg.set_file_types(ft), "unchanged file types report no change");
assert_eq!(detect(&reg, "a/x.foo"), "python");
assert_eq!(detect(&reg, "x.FOO"), "python");
assert_eq!(detect(&reg, "Pipfile.lock"), "python");
assert_eq!(detect(&reg, "build_dev.cfg"), "python");
assert_eq!(detect(&reg, "setup.cfg"), "ini");
assert_eq!(detect(&reg, "server.log"), "python", "a user extension overrides a built-in one");
assert_eq!(detect(&reg, "Jenkinsfile"), "shellscript");
assert_eq!(detect(&reg, "main.rs"), "plaintext");
assert_eq!(reg.detect(Path::new("tool"), Some("#!/usr/bin/env mypy --strict")).as_str(), "python");
assert_eq!(reg.detect(Path::new("tool"), Some("#!/usr/bin/env mypyc")).as_str(), "plaintext");
reg.set_file_types(FileTypes::default());
assert_eq!(detect(&reg, "main.rs"), "rust");
assert_eq!(detect(&reg, "x.foo"), "plaintext");
}
#[test]
fn override_file_type_per_file() {
let reg = reg().fork();
let files = FileSettings {
file_type_overrides: [
("notes.txt".to_owned(), "markdown".to_owned()),
("/abs/run".to_owned(), "python".to_owned()),
("bad.txt".to_owned(), "no-such-language".to_owned()),
]
.into(),
..Default::default()
};
reg.set_file_types(FileTypes::from_settings(&files, Some(Path::new("/proj"))));
assert_eq!(detect(&reg, "/proj/notes.txt"), "markdown");
assert_eq!(detect(&reg, "/other/notes.txt"), "plaintext");
assert_eq!(detect(&reg, "/abs/run"), "python");
assert_eq!(detect(&reg, "/proj/bad.txt"), "plaintext");
}
#[test]
+1 -20
Переглянути файл
@@ -5,10 +5,7 @@
//! Structure / folding / Extend Selection on a large file cost an incremental
//! parse instead of a full one.
use super::{
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
parse_cancellable, selection,
};
use super::{Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, TreeError, folding, outline, parse_cancellable, selection};
use crate::FoldRange;
use ide_core::{DocId, LanguageId, OutlineItem, Range};
use ide_text::ByteEdit;
@@ -62,7 +59,6 @@ struct Memo {
key: Option<(u32, LanguageId)>,
outline: Option<Arc<Vec<OutlineItem>>>,
folding: Option<Arc<Vec<FoldRange>>>,
highlights: Option<Arc<Vec<u32>>>,
}
impl Memo {
@@ -215,21 +211,6 @@ impl SyntaxCache {
)
}
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
doc,
lang,
version,
|m| &mut m.highlights,
|| {
self.with_tree(doc, lang, version, text, |g, tree, text| {
Some(highlight::highlights(g.highlight_query()?, tree, text))
})
},
))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
fn memoized<T: Clone>(
&self,
-63
Переглянути файл
@@ -9,8 +9,6 @@ pub(crate) struct Spec {
pub language: LanguageFn,
/// `queries/<name>/outline.scm`; see `queries/README.md` for the capture vocabulary.
pub outline: &'static str,
/// The grammar's `highlights.scm`, for languages without a CodeMirror mode.
pub highlights: Option<Highlights>,
/// Node kinds folded when they span several lines (in addition to every
/// bracket-delimited node, which is folded generically).
pub fold_nodes: &'static [&'static str],
@@ -22,21 +20,6 @@ pub(crate) struct Spec {
pub constructors: &'static [&'static str],
}
/// A highlights query and how its patterns rank against each other.
pub(crate) struct Highlights {
pub query: &'static str,
/// For the same node, the first matching pattern wins (tree-sitter CLI /
/// GitHub queries) instead of the last one (nvim / Zed queries).
pub first_wins: bool,
}
/// Our own `queries/<name>/highlights.scm`, for grammars that ship none.
macro_rules! highlights {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/highlights.scm"))
};
}
macro_rules! outline {
($name:literal) => {
include_str!(concat!("../../queries/", $name, "/outline.scm"))
@@ -50,7 +33,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "rust",
language: tree_sitter_rust::LANGUAGE,
outline: outline!("rust"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["use_declaration", "extern_crate_declaration"],
@@ -60,7 +42,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "typescript",
language: tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -70,7 +51,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "tsx",
language: tree_sitter_typescript::LANGUAGE_TSX,
outline: outline!("typescript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -80,7 +60,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "javascript",
language: tree_sitter_javascript::LANGUAGE,
outline: outline!("javascript"),
highlights: None,
fold_nodes: &["template_string", "jsx_element"],
fold_bodies: NONE,
imports: &["import_statement"],
@@ -90,7 +69,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "python",
language: tree_sitter_python::LANGUAGE,
outline: outline!("python"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["block"],
imports: &["import_statement", "import_from_statement", "future_import_statement"],
@@ -100,7 +78,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "go",
language: tree_sitter_go::LANGUAGE,
outline: outline!("go"),
highlights: None,
fold_nodes: &["raw_string_literal"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -110,7 +87,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "java",
language: tree_sitter_java::LANGUAGE,
outline: outline!("java"),
highlights: None,
fold_nodes: &["text_block"],
fold_bodies: NONE,
imports: &["import_declaration"],
@@ -120,7 +96,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "kotlin",
language: tree_sitter_kotlin_ng::LANGUAGE,
outline: outline!("kotlin"),
highlights: None,
fold_nodes: &["string_literal"],
fold_bodies: NONE,
imports: &["import"],
@@ -130,7 +105,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "scala",
language: tree_sitter_scala::LANGUAGE,
outline: outline!("scala"),
highlights: None,
fold_nodes: &["string"],
fold_bodies: &["indented_block", "template_body"],
imports: &["import_declaration"],
@@ -140,7 +114,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "c",
language: tree_sitter_c::LANGUAGE,
outline: outline!("c"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def"],
fold_bodies: NONE,
imports: &["preproc_include"],
@@ -150,7 +123,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cpp",
language: tree_sitter_cpp::LANGUAGE,
outline: outline!("cpp"),
highlights: None,
fold_nodes: &["preproc_if", "preproc_ifdef", "preproc_function_def", "raw_string_literal"],
fold_bodies: NONE,
imports: &["preproc_include", "using_declaration"],
@@ -160,7 +132,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "csharp",
language: tree_sitter_c_sharp::LANGUAGE,
outline: outline!("csharp"),
highlights: None,
fold_nodes: &["preproc_region", "raw_string_literal", "verbatim_string_literal"],
fold_bodies: NONE,
imports: &["using_directive"],
@@ -170,7 +141,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "swift",
language: tree_sitter_swift::LANGUAGE,
outline: outline!("swift"),
highlights: None,
// Control-flow statements hold `{ statements }` without a block node of their own.
fold_nodes: &[
"multi_line_string_literal",
@@ -190,7 +160,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ruby",
language: tree_sitter_ruby::LANGUAGE,
outline: outline!("ruby"),
highlights: None,
fold_nodes: &[
"method",
"singleton_method",
@@ -216,7 +185,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "php",
language: tree_sitter_php::LANGUAGE_PHP,
outline: outline!("php"),
highlights: None,
fold_nodes: &["heredoc", "nowdoc"],
fold_bodies: NONE,
imports: &["namespace_use_declaration"],
@@ -226,7 +194,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "lua",
language: tree_sitter_lua::LANGUAGE,
outline: outline!("lua"),
highlights: None,
fold_nodes: &[
"function_declaration",
"function_definition",
@@ -245,7 +212,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "dart",
language: tree_sitter_dart::LANGUAGE,
outline: outline!("dart"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_or_export", "library_name", "part_directive", "part_of_directive"],
@@ -255,7 +221,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "zig",
language: tree_sitter_zig::LANGUAGE,
outline: outline!("zig"),
highlights: Some(Highlights { query: tree_sitter_zig::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -265,7 +230,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "elixir",
language: tree_sitter_elixir::LANGUAGE,
outline: outline!("elixir"),
highlights: Some(Highlights { query: tree_sitter_elixir::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["do_block", "anonymous_function", "string", "sigil"],
fold_bodies: NONE,
imports: NONE,
@@ -275,7 +239,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "haskell",
language: tree_sitter_haskell::LANGUAGE,
outline: outline!("haskell"),
highlights: None,
// `bind`: equations without arguments (`main = do …`).
fold_nodes: &["function", "bind", "data_type", "newtype", "class", "instance", "signature"],
fold_bodies: NONE,
@@ -286,7 +249,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml",
language: tree_sitter_ocaml::LANGUAGE_OCAML,
outline: outline!("ocaml"),
highlights: None,
fold_nodes: &[
"value_definition",
"type_definition",
@@ -304,7 +266,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "ocaml_interface",
language: tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE,
outline: outline!("ocaml_interface"),
highlights: None,
fold_nodes: &["module_definition", "module_type_definition", "signature", "type_definition"],
fold_bodies: NONE,
imports: &["open_module"],
@@ -314,7 +275,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "bash",
language: tree_sitter_bash::LANGUAGE,
outline: outline!("bash"),
highlights: None,
fold_nodes: &["do_group", "if_statement", "case_statement", "heredoc_body"],
fold_bodies: NONE,
imports: NONE,
@@ -324,7 +284,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "html",
language: tree_sitter_html::LANGUAGE,
outline: outline!("html"),
highlights: None,
fold_nodes: &["element", "script_element", "style_element"],
fold_bodies: NONE,
imports: NONE,
@@ -334,7 +293,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "xml",
language: tree_sitter_xml::LANGUAGE_XML,
outline: outline!("xml"),
highlights: None,
fold_nodes: &["element", "CDSect"],
fold_bodies: NONE,
imports: NONE,
@@ -344,7 +302,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "css",
language: tree_sitter_css::LANGUAGE,
outline: outline!("css"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_statement"],
@@ -354,7 +311,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "json",
language: tree_sitter_json::LANGUAGE,
outline: outline!("json"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -364,7 +320,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "yaml",
language: tree_sitter_yaml::LANGUAGE,
outline: outline!("yaml"),
highlights: None,
fold_nodes: &["block_mapping_pair", "block_sequence_item", "block_scalar"],
fold_bodies: NONE,
imports: NONE,
@@ -374,7 +329,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "toml",
language: tree_sitter_toml_ng::LANGUAGE,
outline: outline!("toml"),
highlights: None,
fold_nodes: &["table", "table_array_element", "string"],
fold_bodies: NONE,
imports: NONE,
@@ -384,7 +338,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "markdown",
language: tree_sitter_md::LANGUAGE,
outline: outline!("markdown"),
highlights: None,
fold_nodes: &["section", "fenced_code_block", "list", "block_quote", "html_block"],
fold_bodies: NONE,
imports: NONE,
@@ -394,7 +347,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "hcl",
language: tree_sitter_hcl::LANGUAGE,
outline: outline!("hcl"),
highlights: Some(Highlights { query: highlights!("hcl"), first_wins: false }),
fold_nodes: &["block", "heredoc_template"],
fold_bodies: NONE,
imports: NONE,
@@ -404,7 +356,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "nix",
language: tree_sitter_nix::LANGUAGE,
outline: outline!("nix"),
highlights: Some(Highlights { query: tree_sitter_nix::HIGHLIGHTS_QUERY, first_wins: true }),
fold_nodes: &["let_expression", "indented_string_expression"],
fold_bodies: NONE,
imports: NONE,
@@ -414,7 +365,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "proto",
language: tree_sitter_proto::LANGUAGE,
outline: outline!("proto"),
highlights: None,
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import"],
@@ -424,7 +374,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "graphql",
language: tree_sitter_graphql::LANGUAGE,
outline: outline!("graphql"),
highlights: Some(Highlights { query: highlights!("graphql"), first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
@@ -434,7 +383,6 @@ pub(crate) static SPECS: &[Spec] = &[
name: "make",
language: tree_sitter_make::LANGUAGE,
outline: outline!("make"),
highlights: Some(Highlights { query: tree_sitter_make::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: &["rule", "conditional", "define_directive"],
fold_bodies: NONE,
imports: &["include_directive"],
@@ -444,20 +392,9 @@ pub(crate) static SPECS: &[Spec] = &[
name: "cmake",
language: tree_sitter_cmake::LANGUAGE,
outline: outline!("cmake"),
highlights: None,
fold_nodes: &["function_def", "macro_def", "if_condition", "foreach_loop", "while_loop", "block_def"],
fold_bodies: NONE,
imports: NONE,
constructors: NONE,
},
Spec {
name: "gdscript",
language: tree_sitter_gdscript::LANGUAGE,
outline: outline!("gdscript"),
highlights: Some(Highlights { query: highlights!("gdscript"), first_wins: false }),
fold_nodes: &["string"],
fold_bodies: &["body", "class_body", "match_body"],
imports: NONE,
constructors: &["_init"],
},
];
-508
Переглянути файл
@@ -1,508 +0,0 @@
//! Syntax highlighting from a grammar's own `highlights.scm`, for languages the
//! UI has no CodeMirror mode for.
//!
//! Capture names follow the nvim-treesitter / Zed conventions (`@keyword`,
//! `@string.special.symbol`, ...) and are folded into [`SyntaxHighlightKind`] by
//! their longest known dotted prefix. Overlaps resolve the way those editors
//! do: a smaller node wins over the node containing it, and for the same node
//! the later pattern wins (the first one for tree-sitter CLI style queries). `@embedded` (string interpolation) clears the
//! surrounding colour. Besides tree-sitter's own text predicates, nvim's
//! `#lua-match?` is understood; patterns with other predicates never match.
use super::lines::LineIndex;
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Language, Query, QueryCursor, QueryMatch, QueryPredicateArg, StreamingIterator, Tree};
/// Highlight classes sent to the UI, which maps each onto a Lezer tag.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SyntaxHighlightKind {
Keyword,
String,
StringSpecial,
Escape,
Regexp,
Atom,
Number,
Constant,
Comment,
DocComment,
Function,
FunctionCall,
Builtin,
Type,
Namespace,
Variable,
SelfVariable,
Property,
Attribute,
Macro,
Label,
Tag,
Operator,
Punctuation,
}
impl SyntaxHighlightKind {
/// Every kind, in `as u32` order: the legend for [`SyntaxHighlights::data`].
pub const ALL: [Self; 24] = [
Self::Keyword,
Self::String,
Self::StringSpecial,
Self::Escape,
Self::Regexp,
Self::Atom,
Self::Number,
Self::Constant,
Self::Comment,
Self::DocComment,
Self::Function,
Self::FunctionCall,
Self::Builtin,
Self::Type,
Self::Namespace,
Self::Variable,
Self::SelfVariable,
Self::Property,
Self::Attribute,
Self::Macro,
Self::Label,
Self::Tag,
Self::Operator,
Self::Punctuation,
];
}
/// Highlighted ranges of a whole document, packed like LSP semantic tokens.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyntaxHighlights {
/// Legend: `data` kind `i` is `kinds[i]`.
pub kinds: Vec<SyntaxHighlightKind>,
/// `[from, to, kind]` triples: sorted, non-overlapping UTF-16 offsets.
pub data: Vec<u32>,
}
impl SyntaxHighlights {
pub(crate) fn new(data: Vec<u32>) -> Self {
Self { kinds: SyntaxHighlightKind::ALL.to_vec(), data }
}
}
/// What a capture paints over its node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Paint {
Kind(SyntaxHighlightKind),
/// `@embedded`: code inside a string, uncoloured unless captured itself.
Clear,
}
/// Capture name prefixes, most specific first within each family.
const CAPTURES: &[(&str, Paint)] = {
use Paint::{Clear, Kind};
use SyntaxHighlightKind as K;
&[
("embedded", Clear),
("keyword", Kind(K::Keyword)),
("include", Kind(K::Keyword)),
("import", Kind(K::Keyword)),
("conditional", Kind(K::Keyword)),
("repeat", Kind(K::Keyword)),
("exception", Kind(K::Keyword)),
("boolean", Kind(K::Keyword)),
("string.escape", Kind(K::Escape)),
("escape", Kind(K::Escape)),
("string.regex", Kind(K::Regexp)),
("string.regexp", Kind(K::Regexp)),
("string.special.symbol", Kind(K::Atom)),
("symbol", Kind(K::Atom)),
("string.special", Kind(K::StringSpecial)),
("string", Kind(K::String)),
("character", Kind(K::String)),
("number", Kind(K::Number)),
("float", Kind(K::Number)),
("constant.builtin", Kind(K::Constant)),
("constant.macro", Kind(K::Macro)),
("constant", Kind(K::Constant)),
// nvim greys out unused bindings (`_acc`); IDEA shows them as variables.
("comment.unused", Kind(K::Variable)),
("comment.doc", Kind(K::DocComment)),
("comment.documentation", Kind(K::DocComment)),
("comment", Kind(K::Comment)),
("function.builtin", Kind(K::Builtin)),
("function.macro", Kind(K::Macro)),
("function.definition", Kind(K::Function)),
("function", Kind(K::FunctionCall)),
("method", Kind(K::FunctionCall)),
("constructor", Kind(K::Type)),
("type.builtin", Kind(K::Builtin)),
("type", Kind(K::Type)),
("module", Kind(K::Namespace)),
("namespace", Kind(K::Namespace)),
("variable.builtin", Kind(K::SelfVariable)),
("variable.member", Kind(K::Property)),
("variable.field", Kind(K::Property)),
("variable", Kind(K::Variable)),
("parameter", Kind(K::Variable)),
("property", Kind(K::Property)),
("field", Kind(K::Property)),
("attribute", Kind(K::Attribute)),
("label", Kind(K::Label)),
("tag", Kind(K::Tag)),
("operator", Kind(K::Operator)),
("punctuation", Kind(K::Punctuation)),
]
};
/// The paint for a capture name: its longest prefix (on `.` boundaries) in
/// [`CAPTURES`]. Private captures (`@__name__`) and unknown names paint nothing.
fn paint_for(name: &str) -> Option<Paint> {
if name.starts_with('_') {
return None;
}
let mut prefix = name;
loop {
if let Some((_, p)) = CAPTURES.iter().find(|(n, _)| *n == prefix) {
return Some(*p);
}
prefix = &prefix[..prefix.rfind('.')?];
}
}
/// A predicate tree-sitter leaves to the caller.
enum Check {
/// `#lua-match?` / `#not-lua-match?` on a capture's text.
Matches {
capture: u32,
regex: regex_lite::Regex,
negate: bool,
},
Unsupported,
}
pub(crate) struct HighlightQuery {
query: Query,
/// By capture index.
paints: Vec<Option<Paint>>,
/// By pattern index.
checks: Vec<Vec<Check>>,
first_wins: bool,
}
impl HighlightQuery {
pub(crate) fn new(language: &Language, source: &str, first_wins: bool) -> Result<Self, tree_sitter::QueryError> {
let query = Query::new(language, source)?;
let paints = query.capture_names().iter().map(|n| paint_for(n)).collect();
let checks = (0..query.pattern_count())
.map(|i| {
query
.general_predicates(i)
.iter()
.filter_map(|p| match (&*p.operator, &*p.args) {
// Locals are not tracked: builtins are assumed not to be shadowed.
("is-not?", [QueryPredicateArg::String(s)]) if &**s == "local" => None,
(
op @ ("lua-match?" | "not-lua-match?"),
[QueryPredicateArg::Capture(c), QueryPredicateArg::String(pat)],
) => Some(match regex_lite::Regex::new(&lua_pattern_to_regex(pat)) {
Ok(regex) => Check::Matches { capture: *c, regex, negate: op.starts_with("not-") },
Err(_) => Check::Unsupported,
}),
_ => Some(Check::Unsupported),
})
.collect()
})
.collect();
Ok(Self { query, paints, checks, first_wins })
}
fn accepts(&self, m: &QueryMatch<'_, '_>, text: &str) -> bool {
self.checks[m.pattern_index].iter().all(|check| match check {
Check::Matches { capture, regex, negate } => m
.captures
.iter()
.filter(|c| c.index == *capture)
.all(|c| regex.is_match(&text[c.node.byte_range()]) != *negate),
Check::Unsupported => false,
})
}
}
/// Translates the Lua patterns used by nvim queries (`^[A-Z][A-Z_0-9]+$`, `^//!`) to regex syntax.
fn lua_pattern_to_regex(pat: &str) -> String {
let class = |c: char| match c {
'a' => Some("A-Za-z"),
'd' => Some("0-9"),
'l' => Some("a-z"),
'u' => Some("A-Z"),
'w' => Some("A-Za-z0-9"),
's' => Some("\\s"),
'x' => Some("0-9A-Fa-f"),
'p' => Some("[:punct:]"),
_ => None,
};
let mut out = String::with_capacity(pat.len() + 8);
let mut in_set = false;
let mut chars = pat.chars();
while let Some(c) = chars.next() {
match c {
'%' => {
let Some(next) = chars.next() else { break };
match class(next) {
Some(set) if in_set => out.push_str(set),
Some(set) => {
out.push('[');
out.push_str(set);
out.push(']');
}
None => out.push_str(&regex_lite::escape(&next.to_string())),
}
}
'[' if !in_set => {
in_set = true;
out.push(c);
}
']' if in_set => {
in_set = false;
out.push(c);
}
// Lua's lazy `*` (inside a set, `-` is a range).
'-' if !in_set => out.push_str("*?"),
'\\' | '{' | '}' | '|' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out
}
/// Byte value for "no colour" in the paint buffer; kinds are `1 + index`.
const NONE: u8 = 0;
/// `[from, to, kind]` UTF-16 triples for `text`; see [`SyntaxHighlights::data`].
pub(crate) fn highlights(q: &HighlightQuery, tree: &Tree, text: &str) -> Vec<u32> {
// (byte len, rank, start, end, paint): painted largest first, then by rank,
// so inner nodes and winning patterns overwrite.
let mut captures: Vec<(usize, usize, usize, usize, Paint)> = Vec::new();
let mut cursor = QueryCursor::new();
let mut matches = cursor.matches(&q.query, tree.root_node(), text.as_bytes());
while let Some(m) = matches.next() {
if !q.accepts(m, text) {
continue;
}
for c in m.captures {
if let Some(paint) = q.paints[c.index as usize] {
let r = c.node.byte_range();
if r.start < r.end {
let rank = if q.first_wins { usize::MAX - m.pattern_index } else { m.pattern_index };
captures.push((r.end - r.start, rank, r.start, r.end, paint));
}
}
}
}
captures.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let mut painted = vec![NONE; text.len()];
for &(_, _, start, end, paint) in &captures {
let v = match paint {
Paint::Kind(k) => 1 + k as u8,
Paint::Clear => NONE,
};
painted[start..end].fill(v);
}
let lines = LineIndex::new(text);
let mut data = Vec::new();
let mut i = 0;
while i < painted.len() {
let v = painted[i];
let start = i;
while i < painted.len() && painted[i] == v {
i += 1;
}
// Node boundaries are char boundaries; whitespace-only runs stay uncoloured.
if v != NONE && text.is_char_boundary(start) && text.is_char_boundary(i) && !text[start..i].trim().is_empty() {
data.extend([lines.utf16_at(start) as u32, lines.utf16_at(i) as u32, (v - 1) as u32]);
}
}
data
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_names_fold_to_the_longest_known_prefix() {
use SyntaxHighlightKind as K;
assert_eq!(paint_for("keyword.function"), Some(Paint::Kind(K::Keyword)));
assert_eq!(paint_for("string.special.symbol"), Some(Paint::Kind(K::Atom)));
assert_eq!(paint_for("string.special.path"), Some(Paint::Kind(K::StringSpecial)));
assert_eq!(paint_for("comment.doc.__attribute__"), Some(Paint::Kind(K::DocComment)));
assert_eq!(paint_for("punctuation.bracket"), Some(Paint::Kind(K::Punctuation)));
assert_eq!(paint_for("embedded"), Some(Paint::Clear));
assert_eq!(paint_for("__name__"), None);
assert_eq!(paint_for("spell"), None);
}
/// `(text, kind)` of every highlighted range.
fn spans(lang: &str, text: &str) -> Vec<(String, SyntaxHighlightKind)> {
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new(lang), text).unwrap();
let units: Vec<u16> = text.encode_utf16().collect();
h.data
.chunks(3)
.map(|t| (String::from_utf16(&units[t[0] as usize..t[1] as usize]).unwrap(), h.kinds[t[2] as usize]))
.collect()
}
#[test]
fn highlights_elixir() {
use SyntaxHighlightKind as K;
let src = "defmodule Greeter do\n @moduledoc \"Hi\"\n # 😀 note\n def hello(name, _opts) do\n IO.puts(\"Hello #{name}\")\n :ok\n end\nend\n";
let got = spans("elixir", src);
let kind = |t: &str| got.iter().find(|(s, _)| s == t).map(|(_, k)| *k);
assert_eq!(kind("defmodule"), Some(K::Keyword));
assert_eq!(kind("Greeter"), Some(K::Namespace));
assert_eq!(kind("\"Hi\""), Some(K::DocComment));
assert_eq!(kind("# 😀 note"), Some(K::Comment));
assert_eq!(kind("def"), Some(K::Keyword));
assert_eq!(kind("hello"), Some(K::FunctionCall));
assert_eq!(kind("_opts"), Some(K::Variable));
assert_eq!(kind("puts"), Some(K::FunctionCall));
// Interpolation clears the string colour; its contents are coloured on their own.
assert_eq!(kind("\"Hello "), Some(K::String));
assert_eq!(kind("#{"), Some(K::Punctuation));
assert_eq!(kind(":ok"), Some(K::Atom));
assert_eq!(kind("end"), Some(K::Keyword));
// Sorted and non-overlapping.
let h = crate::Syntax::new().highlights(&ide_core::LanguageId::new("elixir"), src).unwrap();
assert!(h.data.chunks(3).zip(h.data.chunks(3).skip(1)).all(|(a, b)| a[0] < a[1] && a[1] <= b[0]));
}
#[test]
fn highlights_other_grammar_only_languages() {
use SyntaxHighlightKind as K;
type Expect<'a> = &'a [(&'a str, SyntaxHighlightKind)];
let cases: &[(&str, &str, Expect)] = &[
(
"zig",
"const std = @import(\"std\");\n// hi\npub fn main() void {\n var x: u32 = 42;\n _ = x;\n}\n",
&[
("const", K::Keyword),
("\"std\"", K::String),
("// hi", K::Comment),
("42", K::Number),
("u32", K::Builtin),
],
),
(
"nix",
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
&[
("let", K::Keyword),
("# hi", K::Comment),
("1", K::Number),
("\"dev\"", K::String),
("import", K::Builtin),
],
),
(
"graphql",
"# hi\nquery Hero($id: ID!) @cached {\n hero(id: $id) { name ...Friends }\n}\nenum Episode { NEWHOPE }\n",
&[
("# hi", K::Comment),
("query", K::Keyword),
("Hero", K::FunctionCall),
("$id", K::Variable),
("ID", K::Type),
("@cached", K::Attribute),
("name", K::Property),
("Friends", K::FunctionCall),
("NEWHOPE", K::Constant),
],
),
(
"hcl",
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
&[
("# hi", K::Comment),
("resource", K::Keyword),
("aws_instance", K::Type),
("ami", K::Property),
("2", K::Number),
("upper", K::FunctionCall),
("\"web-", K::String),
("env", K::Property),
("var", K::Variable),
],
),
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
(
"gdscript",
"extends Node2D\nclass_name Player\n# hi\n@export var speed: float = 1.5\nconst MAX_HP = 10\nsignal died(cause)\n\nfunc _ready() -> void:\n\tvar label = $Label\n\tself.position.x += speed\n\tprint(\"ready\", &\"name\", 3)\n",
&[
("extends", K::Keyword),
("Node2D", K::Type),
("class_name", K::Keyword),
("Player", K::Type),
("# hi", K::Comment),
("@export", K::Attribute),
("var", K::Keyword),
("float", K::Type),
("1.5", K::Number),
("MAX_HP", K::Constant),
("signal", K::Keyword),
("func", K::Keyword),
("_ready", K::Function),
("$Label", K::StringSpecial),
("self", K::SelfVariable),
("print", K::FunctionCall),
("\"ready\"", K::String),
("&\"name\"", K::StringSpecial),
("3", K::Number),
],
),
];
for (lang, src, expect) in cases {
let got = spans(lang, src);
for (text, kind) in *expect {
assert!(got.iter().any(|(s, k)| s == text && k == kind), "{lang}: {text:?} as {kind:?} in {got:?}");
}
}
}
#[test]
fn languages_without_a_query_have_none() {
assert_eq!(crate::Syntax::new().highlights(&ide_core::LanguageId::new("rust"), "fn a() {}"), None);
}
#[test]
fn every_highlights_query_compiles() {
for spec in super::super::grammars::SPECS {
if let Some(h) = &spec.highlights {
let lang = Language::new(spec.language);
if let Err(e) = HighlightQuery::new(&lang, h.query, h.first_wins) {
panic!("{}: {e}", spec.name);
}
}
}
}
#[test]
fn lua_patterns_translate() {
assert_eq!(lua_pattern_to_regex("^[A-Z][A-Z_0-9]+$"), "^[A-Z][A-Z_0-9]+$");
assert_eq!(lua_pattern_to_regex("^//!"), "^//!");
assert_eq!(lua_pattern_to_regex("^%u[%w_]*$"), "^[A-Z][A-Za-z0-9_]*$");
assert_eq!(lua_pattern_to_regex("a.-b%."), "a.*?b\\.");
}
#[test]
fn legend_matches_discriminants() {
for (i, k) in SyntaxHighlightKind::ALL.iter().enumerate() {
assert_eq!(*k as usize, i);
}
}
}
+1 -1
Переглянути файл
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
}
/// UTF-16 offset of a char-boundary byte offset.
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
fn utf16_at(&self, byte: usize) -> usize {
if self.checkpoints.is_empty() {
return byte;
}
-126
Переглянути файл
@@ -1,126 +0,0 @@
//! Comments and string literals of a text, for Find in Files' search context
//! filter ("In comments", "Except string literals", …).
use super::folding::is_comment;
use tree_sitter::{Node, Tree, TreeCursor};
/// What a [`Literal`] range is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiteralKind {
Comment,
String,
}
/// A comment or string literal: byte range of the outermost node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Literal {
pub start: usize,
pub end: usize,
pub kind: LiteralKind,
}
fn kind_of(node: &Node<'_>) -> Option<LiteralKind> {
if !node.is_named() {
return None;
}
let kind = node.kind();
if is_comment(kind) {
Some(LiteralKind::Comment)
} else if kind.contains("string") || matches!(kind, "char_literal" | "character_literal" | "rune_literal") {
Some(LiteralKind::String)
} else {
None
}
}
/// Comments and string literals in document order; nested ones (a string in a
/// comment, interpolations) are covered by the outermost.
pub(crate) fn literals(tree: &Tree) -> Vec<Literal> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let kind = kind_of(&node);
if let Some(kind) = kind {
out.push(Literal { start: node.start_byte(), end: node.end_byte(), kind });
}
if kind.is_none() && cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return out;
}
}
}
}
/// What a [`SpellingRegion`] covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpellingKind {
Comment,
String,
/// The name a declaration introduces (not its uses).
Name,
}
/// Text the Typo inspection checks: byte range in document order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpellingRegion {
pub start: usize,
pub end: usize,
pub kind: SpellingKind,
}
fn is_name_leaf(kind: &str) -> bool {
kind.contains("identifier") || kind == "name"
}
/// Whether the identifier leaf under `cursor` is the name a declaration
/// introduces (`fn name`, `let pattern`, `int *declarator`, parameters,
/// `name = …` assignments) rather than a use of one.
fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
let parent = node.parent().map(|p| p.kind()).unwrap_or_default();
match cursor.field_name() {
Some("name" | "pattern" | "declarator") => true,
Some("left") => parent.contains("assignment") || parent.contains("declarator"),
_ => parent.contains("parameter"),
}
}
/// Comments, string literals and declared names, for spell checking.
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let literal = kind_of(&node);
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
match literal {
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
None if node.is_named()
&& node.child_count() == 0
&& is_name_leaf(node.kind())
&& declares(&cursor, &node) =>
{
out.push(region(SpellingKind::Name))
}
None => {}
}
if literal.is_none() && cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return out;
}
}
}
}
+6 -98
Переглянути файл
@@ -1,27 +1,20 @@
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
mod cache;
mod folding;
mod grammars;
mod highlight;
pub(crate) mod lines;
mod literals;
mod outline;
mod selection;
mod web;
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
use grammars::{SPECS, Spec};
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
use ide_core::{LanguageId, OutlineItem, Range};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
use tree_sitter::{Language, Parser, Tree};
pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind};
/// Texts larger than this are not parsed (minified bundles, generated dumps).
pub const MAX_PARSE_BYTES: usize = 16 * 1024 * 1024;
@@ -38,7 +31,6 @@ pub(crate) struct Grammar {
pub(crate) spec: &'static Spec,
pub(crate) language: Language,
outline: OnceLock<Option<outline::OutlineQuery>>,
highlights: OnceLock<Option<highlight::HighlightQuery>>,
kinds: OnceLock<folding::KindTable>,
}
@@ -58,17 +50,6 @@ impl Grammar {
})
.as_ref()
}
fn highlight_query(&self) -> Option<&highlight::HighlightQuery> {
self.highlights
.get_or_init(|| {
let h = self.spec.highlights.as_ref()?;
highlight::HighlightQuery::new(&self.language, h.query, h.first_wins)
.inspect_err(|e| tracing::error!("highlights query for {} is invalid: {e}", self.spec.name))
.ok()
})
.as_ref()
}
}
thread_local! {
@@ -91,7 +72,6 @@ impl Syntax {
spec,
language: Language::new(spec.language),
outline: OnceLock::new(),
highlights: OnceLock::new(),
kinds: OnceLock::new(),
})
.collect();
@@ -122,8 +102,6 @@ impl Syntax {
FP.get_or_init(|| {
let mut h = blake3::Hasher::new();
h.update(env!("CARGO_PKG_VERSION").as_bytes());
// Bump when web definitions (`.class`, `#id`, `--var` tags) change.
h.update(b"web-definitions-1");
for s in SPECS {
h.update(s.name.as_bytes());
h.update(&Language::new(s.language).abi_version().to_le_bytes());
@@ -148,8 +126,7 @@ impl Syntax {
/// Whether [`Syntax::tags`] can return anything for this language (data
/// formats such as JSON only have an outline). Lets indexers skip parsing.
pub fn has_symbols(&self, lang: &LanguageId) -> bool {
self.web_grammar(lang).is_some()
|| self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
}
pub fn outline(&self, lang: &LanguageId, text: &str) -> Vec<OutlineItem> {
@@ -166,80 +143,11 @@ impl Syntax {
}
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
let mut tags = self
.analyze(lang, text, |g, tree, text| {
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
})
.unwrap_or_default();
tags.extend(self.web_definitions(lang, text));
tags
}
/// The grammar web features parse `lang` with: its own for HTML and CSS, the
/// CSS grammar for SCSS / Less (selectors and custom properties parse alike),
/// HTML for Vue / Svelte single-file components.
fn web_grammar(&self, lang: &LanguageId) -> Option<&Grammar> {
let name = match lang.as_str() {
"scss" | "less" => "css",
"vue" | "svelte" => "html",
_ => self.grammar(lang).map(|g| g.spec.name)?,
};
web::is_web_grammar(name).then(|| self.grammar(&LanguageId::new(name))).flatten()
}
fn with_web_tree<R>(
&self,
lang: &LanguageId,
text: &str,
f: impl FnOnce(&Grammar, Option<&Grammar>, &Tree) -> R,
) -> Option<R> {
let g = self.web_grammar(lang)?;
if text.len() > MAX_PARSE_BYTES {
return None;
}
let tree = parse(&g.language, text, None)?;
Some(f(g, self.grammar(&LanguageId::new("css")), &tree))
}
/// CSS class (`.card`), id (`#main`) and custom property (`--accent`)
/// definitions of a stylesheet or of the `<style>` elements of a document.
pub fn web_definitions(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
self.with_web_tree(lang, text, |g, css, tree| web::definitions(g, css, tree, text)).unwrap_or_default()
}
/// The `class` / `id` / `href="#…"` / `var(--…)` reference at `pos`.
pub fn web_reference_at(&self, lang: &LanguageId, text: &str, pos: Pos) -> Option<WebReference> {
self.with_web_tree(lang, text, |g, css, tree| web::reference_at(g, css, tree, text, pos)).flatten()
}
/// File paths written in an HTML document or stylesheet (`href`, `src`, `srcset`, `url()`, `@import`).
pub fn web_file_references(&self, lang: &LanguageId, text: &str) -> Vec<FileReference> {
self.with_web_tree(lang, text, |g, css, tree| web::file_references(g, css, tree, text)).unwrap_or_default()
}
/// Value ranges of the `id="name"` / `name="name"` attributes in an HTML document.
pub fn web_anchors(&self, lang: &LanguageId, text: &str, name: &str) -> Vec<Range> {
self.with_web_tree(lang, text, |_, _, tree| web::anchors(tree, text, name)).unwrap_or_default()
}
/// Highlighting from the grammar's own query; `None` without one.
pub fn highlights(&self, lang: &LanguageId, text: &str) -> Option<SyntaxHighlights> {
self.analyze(lang, text, |g, tree, text| {
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
})
}
/// Comments and string literals of `text` (byte ranges, document order);
/// `None` without a grammar for `lang` or for texts too large to parse.
pub fn literals(&self, lang: &LanguageId, text: &str) -> Option<Vec<Literal>> {
self.analyze(lang, text, |_, tree, _| Some(literals::literals(tree)))
}
/// Comments, string literals and declared names (byte ranges, document
/// order) for the Typo inspection; `None` like [`Self::literals`].
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
.unwrap_or_default()
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
+2 -116
Переглянути файл
@@ -15,7 +15,7 @@
use super::Grammar;
use super::lines::LineIndex;
use crate::SymbolTag;
use ide_core::{OutlineItem, SymbolKind, Visibility};
use ide_core::{OutlineItem, SymbolKind};
use std::collections::HashMap;
use tree_sitter::{Node, Query, QueryCursor, StreamingIterator, Tree};
@@ -139,16 +139,11 @@ struct Raw {
container_name: String,
explicit_container: Option<String>,
detail: Option<String>,
/// From a modifier keyword in the declaration (`pub`, `private`, ...).
visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: members take the trait's visibility.
trait_impl: bool,
}
struct Built {
raw: Raw,
kind: SymbolKind,
visibility: Option<Visibility>,
children: Vec<Built>,
}
@@ -193,7 +188,6 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
base = last.to_owned();
kind = ItemKind::Symbol(SymbolKind::Method);
}
let trait_impl = kind == ItemKind::Impl && trait_.is_some();
let name = match (kind, trait_) {
(ItemKind::Impl, Some(t)) => format!("impl {} for {base}", clean(node_text(&t, text), 120)),
(ItemKind::Impl, None) => format!("impl {base}"),
@@ -219,8 +213,6 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
container_name,
explicit_container: container,
detail: detail.map(|d| clean(node_text(&d, text), 80)).filter(|d| !d.is_empty()),
visibility: explicit_visibility(&node, text),
trait_impl,
};
match by_node.get(&raw.node_id) {
Some(existing) if existing.pattern <= raw.pattern => {}
@@ -247,7 +239,6 @@ fn build_tree(g: &Grammar, raws: Vec<Raw>) -> Vec<Built> {
push_child(&mut stack, &mut roots, done);
}
let parent_kind = stack.last().map(|p| p.raw.kind);
let parent_trait_impl = stack.last().is_some_and(|p| p.raw.trait_impl);
let mut kind = raw.kind.symbol_kind();
if kind == SymbolKind::Function && parent_kind.is_some_and(ItemKind::holds_methods) {
kind = SymbolKind::Method;
@@ -259,10 +250,7 @@ fn build_tree(g: &Grammar, raws: Vec<Raw>) -> Vec<Built> {
kind = SymbolKind::Constructor;
}
}
let visibility = raw
.visibility
.or_else(|| implicit_visibility(g.spec.name, raw.kind, kind, &raw.name, parent_kind, parent_trait_impl));
stack.push(Built { raw, kind, visibility, children: Vec::new() });
stack.push(Built { raw, kind, children: Vec::new() });
}
while let Some(done) = stack.pop() {
push_child(&mut stack, &mut roots, done);
@@ -290,7 +278,6 @@ pub(crate) fn outline(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) ->
range: b.raw.range,
selection_range: b.raw.sel,
children: b.children.into_iter().map(convert).collect(),
visibility: b.visibility,
}
}
collect(g, q, tree, text).into_iter().map(convert).collect()
@@ -321,107 +308,6 @@ pub(crate) fn tags(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Ve
out
}
/// Visibility spelled out by a modifier child (`visibility_modifier`, `modifiers`,
/// `accessibility_modifier`, ...) of the declaration.
fn explicit_visibility(node: &Node, text: &str) -> Option<Visibility> {
let mut cursor = node.walk();
let mut found: Option<Visibility> = None;
for child in node.children(&mut cursor) {
if !child.kind().contains("modifier") {
continue;
}
let t = node_text(&child, text);
if child.kind() == "visibility_modifier" && t.starts_with("pub") {
// Rust: `pub` / `pub(crate)` / `pub(super)` / `pub(in path)`.
let v = if t.trim() == "pub" { Visibility::Public } else { Visibility::Package };
found = Some(found.map_or(v, |f| narrower(f, v)));
continue;
}
for word in t.split(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
let v = match word {
"public" | "open" => Visibility::Public,
"protected" => Visibility::Protected,
"internal" | "fileprivate" => Visibility::Package,
"private" => Visibility::Private,
_ => continue,
};
found = Some(found.map_or(v, |f| narrower(f, v)));
}
}
found
}
/// Several keywords (C# `private protected`): the narrower one wins.
fn narrower(a: Visibility, b: Visibility) -> Visibility {
let rank = |v: Visibility| match v {
Visibility::Public => 0,
Visibility::Protected => 1,
Visibility::Package => 2,
Visibility::Private => 3,
};
if rank(a) >= rank(b) { a } else { b }
}
/// The language's default when no modifier is written.
fn implicit_visibility(
lang: &str,
item: ItemKind,
kind: SymbolKind,
name: &str,
parent: Option<ItemKind>,
parent_trait_impl: bool,
) -> Option<Visibility> {
use SymbolKind as K;
if matches!(item, ItemKind::Impl | ItemKind::Extension | ItemKind::Heading)
|| matches!(kind, K::EnumMember | K::Package | K::Namespace)
{
return None;
}
let in_interface = matches!(parent, Some(ItemKind::Symbol(K::Interface | K::Trait)));
match lang {
"rust" => (!in_interface && !parent_trait_impl && kind != K::Macro).then_some(Visibility::Private),
"java" => (!in_interface).then_some(Visibility::Package),
"csharp" => match parent {
_ if in_interface => None,
Some(ItemKind::Symbol(K::Class | K::Struct | K::Enum)) => Some(Visibility::Private),
_ => Some(Visibility::Package),
},
"go" => name.starts_with(|c: char| c.is_lowercase() || c == '_').then_some(Visibility::Package),
"python" => {
(name.starts_with('_') && !(name.starts_with("__") && name.ends_with("__"))).then_some(Visibility::Private)
}
"dart" => name.starts_with('_').then_some(Visibility::Private),
"typescript" | "tsx" | "javascript" => name.starts_with('#').then_some(Visibility::Private),
_ => None,
}
}
/// Copies tree-sitter visibility onto language-server symbols (which carry none),
/// matching by name and identifier start.
pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), Visibility>) {
for i in items {
if let Some(v) = i.visibility {
out.insert((i.selection_range.start, i.name.clone()), v);
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), Visibility>) {
for i in items {
if i.visibility.is_none() {
i.visibility = map.get(&(i.selection_range.start, i.name.clone())).copied();
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// End of `node` without trailing whitespace (C macros and others include the newline).
fn trimmed_end(node: &Node, text: &str) -> usize {
let (s, e) = (node.start_byte(), node.end_byte());
+1 -227
Переглянути файл
@@ -1,6 +1,6 @@
use super::*;
use crate::FoldKind;
use ide_core::{OutlineItem, Pos, SymbolKind, Visibility};
use ide_core::{OutlineItem, Pos, SymbolKind};
fn syntax() -> &'static Syntax {
static S: OnceLock<Syntax> = OnceLock::new();
@@ -902,24 +902,6 @@ fn outline_more_languages() {
Function build
",
);
check_outline(
"gdscript",
"class_name Player\nextends Node\n\nsignal died\nenum State { IDLE, RUN }\nconst SPEED = 2\n@export var hp := 3\n\nfunc _init(a):\n\tpass\n\nfunc jump(height: float) -> void:\n\tvar local = 1\n\nclass Inner:\n\tvar x = 0\n\tfunc go():\n\t\tpass\n",
"
Class Player
Event died
Enum State
EnumMember IDLE
EnumMember RUN
Constant SPEED
Field hp
Constructor _init
Function jump
Class Inner
Field x
Method go
",
);
check_outline(
"cmake",
"project(Foo)\nfunction(my_fn arg)\n message(${arg})\nendfunction()\nadd_executable(app main.c)\n",
@@ -1103,211 +1085,3 @@ fn large_input_is_not_parsed() {
let big = "a".repeat(MAX_PARSE_BYTES + 1);
assert!(syntax().outline(&lang("rust"), &big).is_empty());
}
// --- web references -------------------------------------------------------------
fn web_defs(id: &str, src: &str) -> Vec<(String, SymbolKind, u32, u32)> {
syntax()
.web_definitions(&lang(id), src)
.into_iter()
.map(|t| (t.name, t.kind, t.range.start.line, t.range.start.col))
.collect()
}
fn web_ref(id: &str, src: &str) -> Option<(WebReferenceKind, String, u32, u32)> {
let at = src.find('|').expect("caret marker");
let text = src.replace('|', "");
let line = text[..at].matches('\n').count() as u32;
let col = (at - text[..at].rfind('\n').map_or(0, |i| i + 1)) as u32;
syntax()
.web_reference_at(&lang(id), &text, Pos::new(line, col))
.map(|r| (r.kind, r.name, r.range.start.col, r.range.end.col))
}
#[test]
fn web_definitions_of_stylesheets_and_style_elements() {
let css = ".a.b, div#main > .c:hover { color: var(--x); --y: 1px; }\n@media (x) { .d {} }\n";
assert_eq!(
web_defs("css", css),
vec![
(".a".into(), CSS_CLASS, 0, 1),
(".b".into(), CSS_CLASS, 0, 3),
("#main".into(), CSS_ID, 0, 10),
(".c".into(), CSS_CLASS, 0, 18),
("--y".into(), CSS_VARIABLE, 0, 45),
(".d".into(), CSS_CLASS, 1, 14),
]
);
// Pseudo-classes (`:hover`) are not classes; nested SCSS rules parse with the CSS grammar.
assert!(!web_defs("css", css).iter().any(|d| d.0 == ".hover"));
assert!(web_defs("scss", ".card { &:hover { } .title { } }").iter().any(|d| d.0 == ".title"));
let html = "<p class=\"x\">\n<style>\n .card { --gap: 2px }\n</style>";
assert_eq!(web_defs("html", html), vec![(".card".into(), CSS_CLASS, 2, 3), ("--gap".into(), CSS_VARIABLE, 2, 10)]);
assert!(syntax().tags(&lang("css"), css).iter().any(|t| t.name == ".a"));
assert!(syntax().has_symbols(&lang("css")) && syntax().has_symbols(&lang("vue")));
}
#[test]
fn web_references_in_attributes_and_stylesheets() {
use WebReferenceKind::*;
assert_eq!(web_ref("html", r##"<div class="card bi|g">"##), Some((Class, "big".into(), 17, 20)));
assert_eq!(web_ref("html", r##"<div class="|card big">"##), Some((Class, "card".into(), 12, 16)));
assert_eq!(web_ref("html", r##"<div id="ma|in">"##), Some((Id, "main".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="#to|p">"##), Some((Anchor, "top".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="page.ht|ml">"##), None);
assert_eq!(
web_ref("html", r##"<p style="color: var(--ac|cent)">"##),
Some((CssVariable, "--accent".into(), 21, 29))
);
assert_eq!(web_ref("html", "<style>\n.a { color: var(--x|) }\n</style>").map(|r| r.1), Some("--x".into()));
assert_eq!(web_ref("css", ".a { color: var(--a|ccent, red) }"), Some((CssVariable, "--accent".into(), 16, 24)));
assert_eq!(web_ref("css", ".a { color: re|d }"), None);
assert_eq!(web_ref("vue", r##"<template><div class="ti|tle"/></template>"##).map(|r| r.0), Some(Class));
}
#[test]
fn web_anchors_find_ids_and_names() {
let html = "<h2 id=\"top\">x</h2>\n<a name=\"top\"></a>\n<p class=\"top\">";
let found: Vec<(u32, u32)> =
syntax().web_anchors(&lang("html"), html, "top").into_iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(found, vec![(0, 8), (1, 9)]);
}
#[test]
fn web_file_references_in_attributes_and_stylesheets() {
let refs = |id: &str, src: &str| -> Vec<String> {
syntax().web_file_references(&lang(id), src).into_iter().map(|r| r.value).collect()
};
let html = concat!(
"<link href=\"css/a.css\"><img srcset=\"a.png 1x, b.png 2x\" src=img/c.png alt=\"x\">\n",
"<a href=\"#top\" class=\"k\">t</a><div style=\"background: url(d.svg)\"></div>\n",
"<style>@import \"e.css\"; .x { background: url('f.png') }</style>",
);
assert_eq!(refs("html", html), ["css/a.css", "a.png", "b.png", "img/c.png", "#top", "d.svg", "e.css", "f.png"]);
assert_eq!(refs("css", "@import url(g.css);\n.y { mask: url(\"h.svg#i\") }"), ["g.css", "h.svg#i"]);
let first = &syntax().web_file_references(&lang("html"), html)[0];
assert_eq!((first.range.start.col, first.range.end.col), (12, 21));
}
#[test]
fn literals_are_outermost_comments_and_strings() {
let src = "// note \"q\"\nfn main() { let s = \"a // b\"; /* c */ let c = 'x'; }\n";
let found: Vec<(&str, LiteralKind)> =
syntax().literals(&lang("rust"), src).unwrap().iter().map(|l| (&src[l.start..l.end], l.kind)).collect();
assert_eq!(
found,
vec![
("// note \"q\"", LiteralKind::Comment),
("\"a // b\"", LiteralKind::String),
("/* c */", LiteralKind::Comment),
("'x'", LiteralKind::String),
]
);
assert!(syntax().literals(&lang("plaintext"), "// x").is_none());
}
/// `name: visibility` for every outline item, depth-first.
fn visibilities(id: &str, src: &str) -> Vec<(String, Option<Visibility>)> {
fn go(items: &[OutlineItem], out: &mut Vec<(String, Option<Visibility>)>) {
for i in items {
out.push((i.name.clone(), i.visibility));
go(&i.children, out);
}
}
let mut out = Vec::new();
go(&syntax().outline(&lang(id), src), &mut out);
out
}
fn vis_of(list: &[(String, Option<Visibility>)], name: &str) -> Option<Visibility> {
list.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no {name} in {list:?}")).1
}
#[test]
fn outline_visibility_rust() {
let src = "pub struct S { a: i32, pub b: i32, pub(crate) c: i32 }\n\
trait T { fn req(&self); }\n\
impl T for S { fn req(&self) {} }\n\
impl S { pub fn new() {} fn helper() {} }\n\
fn main() {}\n";
let v = visibilities("rust", src);
assert_eq!(vis_of(&v, "S"), Some(Visibility::Public));
assert_eq!(vis_of(&v, "a"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "b"), Some(Visibility::Public));
assert_eq!(vis_of(&v, "c"), Some(Visibility::Package));
assert_eq!(vis_of(&v, "new"), Some(Visibility::Public));
assert_eq!(vis_of(&v, "helper"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "main"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "impl T for S"), None);
// Trait members and trait impl members follow the trait.
assert!(v.iter().filter(|(n, _)| n == "req").all(|(_, vis)| vis.is_none()));
}
#[test]
fn outline_visibility_java_ts_python() {
let java = "public class A {\n private int x;\n protected void p() {}\n void pkg() {}\n public A() {}\n}\ninterface I { void m(); }\n";
let v = visibilities("java", java);
assert_eq!(vis_of(&v, "x"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "p"), Some(Visibility::Protected));
assert_eq!(vis_of(&v, "pkg"), Some(Visibility::Package));
assert_eq!(vis_of(&v, "A"), Some(Visibility::Public));
assert_eq!(vis_of(&v, "m"), None);
let ts = "class C {\n private a = 1;\n protected b(): void {}\n c(): void {}\n #d = 2;\n}\n";
let v = visibilities("typescript", ts);
assert_eq!(vis_of(&v, "a"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "b"), Some(Visibility::Protected));
assert_eq!(vis_of(&v, "c"), None);
assert_eq!(vis_of(&v, "#d"), Some(Visibility::Private));
let py = "class K:\n def _hidden(self): pass\n def __init__(self): pass\n def shown(self): pass\n";
let v = visibilities("python", py);
assert_eq!(vis_of(&v, "_hidden"), Some(Visibility::Private));
assert_eq!(vis_of(&v, "__init__"), None);
assert_eq!(vis_of(&v, "shown"), None);
}
#[test]
fn merge_visibility_matches_by_name_and_position() {
fn clear(items: &mut [OutlineItem]) {
for i in items {
i.visibility = None;
clear(&mut i.children);
}
}
let src = "struct S { a: i32 }\nfn f() {}\n";
let ts = syntax().outline(&lang("rust"), src);
let mut lsp = ts.clone();
clear(&mut lsp);
lsp[1].name = "renamed".into();
crate::merge_visibility(&mut lsp, &ts);
assert_eq!(lsp[0].visibility, Some(Visibility::Private));
assert_eq!(lsp[0].children[0].visibility, Some(Visibility::Private));
assert_eq!(lsp[1].visibility, None);
}
#[test]
fn spelling_regions_cover_declared_names_only() {
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
let found: Vec<(&str, SpellingKind)> =
syntax().spelling_regions(&lang("rust"), src).unwrap().iter().map(|r| (&src[r.start..r.end], r.kind)).collect();
assert_eq!(
found,
vec![
("// note", SpellingKind::Comment),
("parse_input", SpellingKind::Name),
("raw_text", SpellingKind::Name),
("counter", SpellingKind::Name),
("\"hi\"", SpellingKind::String),
]
);
let py = "def load_config(path, retries=3):\n \"\"\"Doc.\"\"\"\n total = 0\n";
let names: Vec<&str> = syntax()
.spelling_regions(&lang("python"), py)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::Name)
.map(|r| &py[r.start..r.end])
.collect();
assert_eq!(names, ["load_config", "path", "retries", "total"]);
}
-374
Переглянути файл
@@ -1,374 +0,0 @@
//! Web references that no language server resolves: HTML `class` / `id`
//! attributes to the CSS selectors that style them, `href="#id"` to the element
//! with that id, and `var(--x)` to the custom property's declarations.
//!
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
//! `<style>` elements of HTML documents and feed the symbol index (see
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
use super::lines::{LineIndex, utf16_to_byte};
use super::{Grammar, parse};
use crate::SymbolTag;
use ide_core::{Pos, Range, SymbolKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Node, Tree};
/// Index symbol kinds of web definitions; names carry the CSS sigil.
pub const CSS_CLASS: SymbolKind = SymbolKind::Class;
pub const CSS_ID: SymbolKind = SymbolKind::Field;
pub const CSS_VARIABLE: SymbolKind = SymbolKind::Variable;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum WebReferenceKind {
/// A class in a `class` / `className` attribute: `.name` selectors.
Class,
/// An `id` attribute value: `#name` selectors.
Id,
/// `href="#name"`: the element with that id in the same document.
Anchor,
/// `var(--name)`: the custom property's declarations.
CssVariable,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebReference {
pub kind: WebReferenceKind,
/// Without sigil: `card`, `main`, `--accent`.
pub name: String,
pub range: Range,
}
impl WebReference {
/// The index symbol a reference resolves to: `.card`, `#main`, `--accent`.
pub fn symbol(&self) -> Option<(String, SymbolKind)> {
match self.kind {
WebReferenceKind::Class => Some((format!(".{}", self.name), CSS_CLASS)),
WebReferenceKind::Id => Some((format!("#{}", self.name), CSS_ID)),
WebReferenceKind::CssVariable => Some((self.name.clone(), CSS_VARIABLE)),
WebReferenceKind::Anchor => None,
}
}
}
/// Grammars whose documents carry web definitions and references.
pub(crate) fn is_web_grammar(name: &str) -> bool {
matches!(name, "css" | "html")
}
/// Stylesheet text embedded in a document: `(byte offset, text)`.
fn css_regions<'t>(grammar: &str, tree: &Tree, text: &'t str) -> Vec<(usize, &'t str)> {
match grammar {
"css" => vec![(0, text)],
"html" => {
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "style_element" {
let mut c = n.walk();
for raw in n.children(&mut c).filter(|c| c.kind() == "raw_text") {
out.push((raw.start_byte(), &text[raw.start_byte()..raw.end_byte()]));
}
return false;
}
true
});
out
}
_ => Vec::new(),
}
}
/// Pre-order walk; `f` returns whether to descend.
fn walk<'t>(n: Node<'t>, f: &mut dyn FnMut(Node<'t>) -> bool) {
if !f(n) {
return;
}
let mut c = n.walk();
for child in n.children(&mut c) {
walk(child, f);
}
}
fn text_of<'t>(n: Node, text: &'t str) -> &'t str {
text.get(n.start_byte()..n.end_byte()).unwrap_or_default()
}
/// `.name`, `#name` and `--name` definitions in `text` (a stylesheet, or a document with `<style>`).
pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<SymbolTag> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if base == 0 && g.spec.name == "css" {
tree
} else {
let Some(css) = css else { continue };
let Some(t) = parse(&css.language, css_text, None) else { continue };
parsed = t;
&parsed
};
walk(css_tree.root_node(), &mut |n| {
let def = match n.kind() {
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
}
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
"property_name" if text_of(n, css_text).starts_with("--") => {
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
}
_ => None,
};
if let Some((name, kind)) = def {
let range = idx.range(base + n.start_byte(), base + n.end_byte());
out.push(SymbolTag { name, kind, container: None, range });
}
true
});
}
out
}
fn byte_at(text: &str, pos: Pos) -> Option<usize> {
let mut start = 0;
for _ in 0..pos.line {
start += text[start..].find('\n')? + 1;
}
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
}
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
let rel = at.checked_sub(base)?;
let start = value[..rel.min(value.len())].rfind(char::is_whitespace).map_or(0, |i| i + 1);
let end = value[rel.min(value.len())..].find(char::is_whitespace).map_or(value.len(), |i| rel + i);
(start < end).then(|| (base + start, &value[start..end]))
}
/// `var(--name)` around byte `at` of a stylesheet tree.
fn css_variable_at(tree: &Tree, css_text: &str, at: usize) -> Option<(usize, usize, String)> {
let mut n = tree.root_node().descendant_for_byte_range(at, at)?;
if n.kind() != "plain_value" {
// The caret right after `--x` in `var(--x)`.
n = tree.root_node().descendant_for_byte_range(at.saturating_sub(1), at.saturating_sub(1))?;
}
let name = text_of(n, css_text);
let call = n.parent()?.parent()?;
let is_var = call.kind() == "call_expression"
&& call
.child_by_field_name("function_name")
.or_else(|| call.child(0))
.is_some_and(|f| text_of(f, css_text) == "var");
(n.kind() == "plain_value" && name.starts_with("--") && is_var)
.then(|| (n.start_byte(), n.end_byte(), name.to_owned()))
}
/// The web reference at `pos` of a document parsed as `tree`.
pub(crate) fn reference_at(
g: &Grammar,
css: Option<&Grammar>,
tree: &Tree,
text: &str,
pos: Pos,
) -> Option<WebReference> {
let at = byte_at(text, pos)?;
let idx = LineIndex::new(text);
let make = |kind, from: usize, to: usize, name: String| WebReference { kind, name, range: idx.range(from, to) };
// Stylesheet regions: `var(--x)`.
for (base, css_text) in css_regions(g.spec.name, tree, text) {
if at < base || at > base + css_text.len() {
continue;
}
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
parsed = parse(&css?.language, css_text, None)?;
&parsed
};
let (from, to, name) = css_variable_at(css_tree, css_text, at - base)?;
return Some(make(WebReferenceKind::CssVariable, base + from, base + to, name));
}
if g.spec.name != "html" {
return None;
}
// HTML attribute values.
let node = tree.root_node().descendant_for_byte_range(at, at)?;
let value = std::iter::successors(Some(node), |n| n.parent()).find(|n| n.kind() == "attribute_value")?;
let attribute = std::iter::successors(value.parent(), |n| n.parent()).find(|n| n.kind() == "attribute")?;
let attr_name = attribute.child(0).map(|n| text_of(n, text).to_ascii_lowercase())?;
let (vs, vtext) = (value.start_byte(), text_of(value, text));
match attr_name.as_str() {
"class" | "classname" | "class:list" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Class, from, from + token.len(), token.to_owned()))
}
"id" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Id, from, from + token.len(), token.to_owned()))
}
"href" | "xlink:href" if vtext.len() > 1 && vtext.starts_with('#') => {
Some(make(WebReferenceKind::Anchor, vs, vs + vtext.len(), vtext[1..].to_owned()))
}
"style" => {
// An inline declaration list: parse it as the block of a rule.
let wrapped = format!("x{{{vtext}}}");
let t = parse(&css?.language, &wrapped, None)?;
let (from, to, name) = css_variable_at(&t, &wrapped, at - vs + 2)?;
Some(make(WebReferenceKind::CssVariable, vs + from - 2, vs + to - 2, name))
}
_ => None,
}
}
/// Elements whose `id` (or `<a name>`) is `name`: the targets of `href="#name"`.
pub(crate) fn anchors(tree: &Tree, text: &str, name: &str) -> Vec<Range> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "attribute" {
let attr = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase());
if matches!(attr.as_deref(), Some("id" | "name")) {
let mut found = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" && text_of(v, text) == name {
found = Some(v);
}
found.is_none()
});
if let Some(v) = found {
out.push(idx.range(v.start_byte(), v.end_byte()));
}
}
return false;
}
true
});
out
}
/// A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileReference {
pub range: Range,
pub value: String,
}
/// HTML attributes whose value is a URL.
const URL_ATTRIBUTES: &[&str] = &[
"href",
"src",
"srcset",
"action",
"formaction",
"poster",
"data",
"cite",
"background",
"manifest",
"xlink:href",
"longdesc",
"icon",
];
/// `url(…)` arguments and `@import` targets of a stylesheet: `(start, end)` byte ranges.
fn css_paths(tree: &Tree, css_text: &str, out: &mut Vec<(usize, usize)>) {
let target = |n: Node| -> Option<(usize, usize)> {
let n =
if n.kind() == "string_value" { n.named_child(0).filter(|c| c.kind() == "string_content")? } else { n };
matches!(n.kind(), "plain_value" | "string_content").then(|| (n.start_byte(), n.end_byte()))
};
walk(tree.root_node(), &mut |n| {
match n.kind() {
"import_statement" => {
if let Some(first) = n.named_child(0)
&& first.kind() == "string_value"
{
out.extend(target(first));
}
}
"call_expression" => {
let is_url =
n.named_child(0).is_some_and(|f| f.kind() == "function_name" && text_of(f, css_text) == "url");
if is_url
&& let Some(args) = n.child_by_field_name("arguments").or_else(|| n.named_child(1))
&& let Some(arg) = args.named_child(0)
{
out.extend(target(arg));
}
}
_ => {}
}
true
});
}
/// File paths written in an HTML document or a stylesheet.
pub(crate) fn file_references(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<FileReference> {
let idx = LineIndex::new(text);
let mut spans: Vec<(usize, usize)> = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
let Some(t) = css.and_then(|c| parse(&c.language, css_text, None)) else { continue };
parsed = t;
&parsed
};
let mut found = Vec::new();
css_paths(css_tree, css_text, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (base + s, base + e)));
}
if g.spec.name == "html" {
walk(tree.root_node(), &mut |n| {
if n.kind() != "attribute" {
return true;
}
let name = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase()).unwrap_or_default();
let mut value = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" {
value = Some(v);
}
value.is_none()
});
let Some(v) = value else { return false };
let (vs, vtext) = (v.start_byte(), text_of(v, text));
match name.as_str() {
"srcset" => {
// `a.png 1x, b.png 2x`: the URL of each candidate.
let mut at = 0;
for part in vtext.split(',') {
let lead = part.len() - part.trim_start().len();
let url = part.split_whitespace().next().unwrap_or_default();
if !url.is_empty() {
spans.push((vs + at + lead, vs + at + lead + url.len()));
}
at += part.len() + 1;
}
}
"style" => {
let wrapped = format!("x{{{vtext}}}");
if let Some(t) = css.and_then(|c| parse(&c.language, &wrapped, None)) {
let mut found = Vec::new();
css_paths(&t, &wrapped, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (vs + s - 2, vs + e - 2)));
}
}
_ if URL_ATTRIBUTES.contains(&name.as_str()) && !vtext.trim().is_empty() => {
spans.push((vs, vs + vtext.len()));
}
_ => {}
}
false
});
}
spans.sort_unstable();
spans.into_iter().map(|(s, e)| FileReference { range: idx.range(s, e), value: text[s..e].to_owned() }).collect()
}
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ lsp-types.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tokio = { workspace = true, features = ["net"] }
tokio.workspace = true
parking_lot.workspace = true
tracing.workspace = true
futures.workspace = true
-4
Переглянути файл
@@ -121,7 +121,6 @@ pub fn client_capabilities() -> Value {
"honorsChangeAnnotations": false
},
"codeLens": { "dynamicRegistration": false },
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
"formatting": { "dynamicRegistration": false },
"rangeFormatting": { "dynamicRegistration": false },
"rename": {
@@ -157,7 +156,6 @@ pub fn client_capabilities() -> Value {
"augmentsSyntaxTokens": true
},
"inlayHint": { "dynamicRegistration": false },
"inlineCompletion": { "dynamicRegistration": true },
"callHierarchy": { "dynamicRegistration": false },
"typeHierarchy": { "dynamicRegistration": false }
},
@@ -205,10 +203,8 @@ pub fn capability_key(method: &str) -> Option<&'static str> {
"textDocument/formatting" => "documentFormattingProvider",
"textDocument/rangeFormatting" => "documentRangeFormattingProvider",
"textDocument/inlayHint" => "inlayHintProvider",
"textDocument/inlineCompletion" => "inlineCompletionProvider",
"textDocument/semanticTokens" | "textDocument/semanticTokens/full" => "semanticTokensProvider",
"textDocument/codeLens" => "codeLensProvider",
"textDocument/documentLink" => "documentLinkProvider",
"textDocument/prepareCallHierarchy" => "callHierarchyProvider",
"textDocument/prepareTypeHierarchy" => "typeHierarchyProvider",
_ => return None,
+7 -208
Переглянути файл
@@ -434,101 +434,6 @@ pub fn lsp_completion_item(text: &DocText, enc: Encoding, item: &CompletionItem)
}
}
// ---------------------------------------------------------------- inline completion
/// `InlineCompletionList | InlineCompletionItem[] | null` → items (malformed ones skipped).
pub fn inline_completion_items(conv: &Conv, path: &Path, v: Value, server: ServerId) -> Vec<InlineCompletionItem> {
let items = match v {
Value::Array(a) => a,
Value::Object(mut o) => match o.remove("items") {
Some(Value::Array(a)) => a,
_ => Vec::new(),
},
_ => Vec::new(),
};
items
.into_iter()
.filter_map(|it| {
let insert_text = match it.get("insertText")? {
Value::String(s) => s.clone(),
Value::Object(o) if o.get("kind").and_then(Value::as_str) == Some("snippet") => {
snippet_text(o.get("value")?.as_str()?)
}
_ => return None,
};
let range = it
.get("range")
.and_then(|r| serde_json::from_value::<lsp::Range>(r.clone()).ok())
.map(|r| conv.range(path, r));
let filter_text = it.get("filterText").and_then(Value::as_str).map(str::to_owned);
let cmd = it.get("command").and_then(|c| serde_json::from_value::<lsp::Command>(c.clone()).ok());
Some(InlineCompletionItem { insert_text, range, filter_text, command: cmd.map(command), server })
})
.filter(|i| !i.insert_text.is_empty())
.collect()
}
/// The text a snippet inserts with every placeholder at its default:
/// `foo(${1:a}, $2)$0` → `foo(a, )`; a choice takes its first option.
pub fn snippet_text(snippet: &str) -> String {
fn parse(chars: &[char], i: &mut usize, out: &mut String, nested: bool) {
while let Some(&ch) = chars.get(*i) {
let next = chars.get(*i + 1).copied();
match ch {
'\\' if next.is_some() => {
out.extend(next);
*i += 2;
}
'}' if nested => {
*i += 1;
return;
}
'$' if next.is_some_and(|c| c.is_ascii_digit()) => {
*i += 1;
while chars.get(*i).is_some_and(char::is_ascii_digit) {
*i += 1;
}
}
'$' if next == Some('{') => {
*i += 2;
while chars.get(*i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_') {
*i += 1;
}
match chars.get(*i) {
Some(':') => {
*i += 1;
parse(chars, i, out, true);
}
Some('|') => {
*i += 1;
let mut first = true;
while let Some(&c) = chars.get(*i).filter(|c| **c != '|') {
first &= c != ',';
if first {
out.push(c);
}
*i += 1;
}
*i = (*i + 2).min(chars.len());
}
// `${1}`, or a variable without a default.
Some('}') => *i += 1,
_ => {}
}
}
_ => {
out.push(ch);
*i += 1;
}
}
}
}
let chars: Vec<char> = snippet.chars().collect();
let mut out = String::new();
parse(&chars, &mut 0, &mut out, false);
out
}
// ---------------------------------------------------------------- commands & actions
pub fn command(c: lsp::Command) -> Command {
@@ -709,7 +614,6 @@ pub fn document_symbols(conv: &Conv, path: &Path, r: lsp::DocumentSymbolResponse
range,
selection_range: range,
children: Vec::new(),
visibility: None,
}
})
.collect();
@@ -728,7 +632,6 @@ fn document_symbol(conv: &Conv, path: &Path, s: lsp::DocumentSymbol) -> OutlineI
range: conv.range(path, s.range),
selection_range: conv.range(path, s.selection_range),
children: s.children.unwrap_or_default().into_iter().map(|c| document_symbol(conv, path, c)).collect(),
visibility: None,
}
}
@@ -830,34 +733,19 @@ pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<Signa
// ---------------------------------------------------------------- decorations
pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
let tooltip_text = |t: lsp::InlayHintTooltip| match t {
lsp::InlayHintTooltip::String(s) => s,
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
};
let (label, parts) = match h.label {
lsp::InlayHintLabel::String(s) => (s, Vec::new()),
lsp::InlayHintLabel::LabelParts(parts) => {
let label = parts.iter().map(|p| p.value.as_str()).collect();
let parts = parts
.into_iter()
.map(|p| InlayLabelPart {
value: p.value,
tooltip: p.tooltip.map(|t| match t {
lsp::InlayHintLabelPartTooltip::String(s) => s,
lsp::InlayHintLabelPartTooltip::MarkupContent(m) => m.value,
}),
location: p.location.as_ref().and_then(|l| conv.location(l)),
})
.collect();
(label, parts)
}
let label = match h.label {
lsp::InlayHintLabel::String(s) => s,
lsp::InlayHintLabel::LabelParts(parts) => parts.into_iter().map(|p| p.value).collect(),
};
let kind = match h.kind {
Some(lsp::InlayHintKind::TYPE) => InlayKind::Type,
Some(lsp::InlayHintKind::PARAMETER) => InlayKind::Parameter,
_ => InlayKind::Other,
};
let tooltip = h.tooltip.map(tooltip_text);
let tooltip = h.tooltip.map(|t| match t {
lsp::InlayHintTooltip::String(s) => s,
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
});
InlayHint {
position: conv.pos(path, h.position),
label,
@@ -865,7 +753,6 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
padding_left: h.padding_left.unwrap_or(false),
padding_right: h.padding_right.unwrap_or(false),
tooltip,
parts,
}
}
@@ -896,27 +783,6 @@ pub fn code_lens(conv: &Conv, path: &Path, l: lsp::CodeLens) -> CodeLens {
CodeLens { range: conv.range(path, l.range), command: l.command.map(command) }
}
pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<DocumentLink> {
let target = l.target?;
let target = target.as_str();
let (file, url) = match uri_to_path(target) {
Some(p) => (Some(p), None),
None => (None, Some(target.to_owned())),
};
let fragment = file
.as_ref()
.and_then(|_| target.split_once('#'))
.map(|(_, f)| percent_encoding::percent_decode_str(f).decode_utf8_lossy().into_owned())
.filter(|f| !f.is_empty());
Some(DocumentLink {
range: conv.range(path, l.range),
path: file.map(Into::into),
fragment,
url,
tooltip: l.tooltip,
})
}
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
let (path, uri) = uri_target(item.uri.as_str());
Some(HierarchyItem {
@@ -976,7 +842,6 @@ pub fn diagnostic(conv: &Conv, path: &Path, d: lsp::Diagnostic, server_name: &st
}),
unnecessary: tags.contains(&lsp::DiagnosticTag::UNNECESSARY),
deprecated: tags.contains(&lsp::DiagnosticTag::DEPRECATED),
server: Some(server_name.to_owned()),
}
}
@@ -990,25 +855,6 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn snippet_text_takes_placeholder_defaults() {
assert_eq!(snippet_text("foo(${1:a}, $2)$0"), "foo(a, )");
assert_eq!(snippet_text("${1:outer ${2:inner}} \\$x ${3|one,two|}${TM_FILENAME}"), "outer inner $x one");
assert_eq!(snippet_text("plain"), "plain");
}
#[test]
fn inline_completion_shapes() {
let conv = Conv::utf16();
let path = Path::new("/a.rs");
let list = inline_completion_items(&conv, path, json!([{ "insertText": "x" }]), ServerId(1));
assert_eq!(list.len(), 1);
assert!(inline_completion_items(&conv, path, Value::Null, ServerId(1)).is_empty());
assert!(
inline_completion_items(&conv, path, json!({ "items": [{ "label": "no text" }] }), ServerId(1)).is_empty()
);
}
fn p(l: u32, c: u32) -> Pos {
Pos::new(l, c)
}
@@ -1265,52 +1111,5 @@ mod tests {
assert_eq!(h.label, ": Vec<u8>");
assert_eq!(h.kind, InlayKind::Type);
assert!(h.padding_left && !h.padding_right);
assert_eq!(h.parts.len(), 2);
assert!(h.parts.iter().all(|p| p.location.is_none()));
}
#[cfg(unix)]
#[test]
fn inlay_label_parts_keep_locations() {
let conv = Conv::utf16();
let h: lsp::InlayHint = serde_json::from_value(json!({
"position": {"line": 0, "character": 3},
"label": [
{"value": ": "},
{"value": "Foo", "tooltip": "struct Foo",
"location": {"uri": "file:///p/foo.rs", "range": {"start": {"line": 4, "character": 7}, "end": {"line": 4, "character": 10}}}}
]
}))
.unwrap();
let h = inlay_hint(&conv, Path::new("/a"), h);
assert_eq!(h.label, ": Foo");
let part = &h.parts[1];
assert_eq!(part.value, "Foo");
assert_eq!(part.tooltip.as_deref(), Some("struct Foo"));
let loc = part.location.as_ref().unwrap();
assert_eq!(loc.path, PathBuf::from("/p/foo.rs"));
assert_eq!(loc.range.start, p(4, 7));
assert_eq!(h.kind, InlayKind::Other);
}
#[cfg(unix)]
#[test]
fn document_links_split_file_targets_and_urls() {
let conv = Conv::utf16();
let link = |target: Option<&str>| {
serde_json::from_value::<lsp::DocumentLink>(json!({
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 } },
"target": target,
}))
.unwrap()
};
let here = Path::new("/p/index.html");
let file = document_link(&conv, here, link(Some("file:///p/a%20b.md#L12"))).unwrap();
assert_eq!(file.path.as_deref(), Some(Path::new("/p/a b.md")));
assert_eq!(file.fragment.as_deref(), Some("L12"));
assert_eq!(file.range, Range::new(p(0, 6), p(0, 15)));
let web = document_link(&conv, here, link(Some("https://example.com/#top"))).unwrap();
assert_eq!((web.path, web.url.as_deref(), web.fragment), (None, Some("https://example.com/#top"), None));
assert!(document_link(&conv, here, link(None)).is_none());
}
}
+1 -11
Переглянути файл
@@ -75,12 +75,8 @@ impl ClientHandler {
_ => return,
}
};
let ended = matches!(&event, IdeEvent::Task { done: true, .. });
mgr.sink().emit(event);
self.server.refresh_busy_status(mgr.sink());
if ended {
self.server.progress_ended();
}
}
fn publish_diagnostics(&self, mgr: &LspManager, params: Value) {
@@ -92,10 +88,6 @@ impl ClientHandler {
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
// Files opened only for a request (references search) are not the user's problems.
if self.server.suppresses_diagnostics(&path) {
return;
}
let conv = mgr.conv(self.encoding());
let items = params
.diagnostics
@@ -136,8 +128,7 @@ impl ClientHandler {
Value::Array(
items
.iter()
// vtsls asks for the whole configuration as section `""`.
.map(|item| match item.get("section").and_then(Value::as_str).filter(|s| !s.is_empty()) {
.map(|item| match item.get("section").and_then(Value::as_str) {
Some(section) if section == self.server.name => options.clone(),
// Servers that take settings under `initializationOptions.settings`
// (jdtls) ask for the same sections later.
@@ -202,7 +193,6 @@ impl Handler for ClientHandler {
_ => tracing::debug!("[{}] {text}", self.server.name),
}
}
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
"telemetry/event" | "$/logTrace" | "$/cancelRequest" => {}
other => tracing::trace!("[{}] unhandled notification {other}", self.server.name),
}
-89
Переглянути файл
@@ -24,10 +24,6 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(300);
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
/// How long to retry while the project is still being imported.
const IMPORT_WAIT: Duration = Duration::from_secs(90);
/// Compile errors listed with a launch; the rest are only counted.
const MAX_LAUNCH_ERRORS: usize = 10;
/// Build markers can be published just after `java/buildWorkspace` answers.
const ERRORS_WAIT: Duration = Duration::from_secs(2);
/// Result of `java/buildWorkspace` (jdtls `BuildWorkspaceStatus`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -74,46 +70,6 @@ pub struct JavaLaunchInfo {
pub java_home: Option<ide_core::IpcPath>,
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
pub java_exec: Option<String>,
/// How a launcher that builds the command line itself must shorten it (java-debug's
/// `shortenCommandLine`: `none` | `jarmanifest` | `argfile`; filled in by the caller).
pub shorten_command_line: Option<String>,
/// First compile errors of the workspace when the build had errors.
pub errors: Vec<JavaCompileError>,
/// All compile errors (`errors` is capped).
pub error_count: u32,
/// Likely causes of the errors worth telling the user (e.g. a missing Lombok agent).
pub hints: Vec<String>,
}
/// One error diagnostic; `line` / `column` are 1-based for display.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JavaCompileError {
pub path: ide_core::IpcPath,
pub line: u32,
pub column: u32,
pub message: String,
}
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
pub fn compile_errors(
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
limit: usize,
) -> (Vec<JavaCompileError>, u32) {
let mut errors: Vec<JavaCompileError> = diagnostics
.into_iter()
.filter(|(_, d)| d.severity == Some(lsp_types::DiagnosticSeverity::ERROR))
.map(|(path, d)| JavaCompileError {
path: path.into(),
line: d.range.start.line + 1,
column: d.range.start.character + 1,
message: d.message.lines().next().unwrap_or_default().to_owned(),
})
.collect();
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
let count = u32::try_from(errors.len()).unwrap_or(u32::MAX);
errors.truncate(limit);
(errors, count)
}
/// `java.project.getClasspaths` result.
@@ -182,9 +138,6 @@ impl LspManager {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}))
}
@@ -257,10 +210,6 @@ impl LspManager {
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
pub async fn java_launch(&self, module: &Path, test: bool, build: bool) -> IdeResult<JavaLaunchInfo> {
let build = if build { Some(self.java_build(module).await?) } else { None };
let (errors, error_count) = match build {
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => self.java_compile_errors(module).await,
_ => (Vec::new(), 0),
};
let cp = self.java_classpath(module, test).await?;
let java_home = match self.java_vm_location(module).await {
Ok(home) => home,
@@ -276,25 +225,9 @@ impl LspManager {
module_paths: cp.module_paths,
java_home: java_home.map(Into::into),
java_exec: None,
shorten_command_line: None,
errors,
error_count,
hints: Vec::new(),
})
}
/// Compile errors jdtls reports for its workspace (all modules it imported).
async fn java_compile_errors(&self, module: &Path) -> (Vec<JavaCompileError>, u32) {
let Ok((server, _)) = self.jdtls(module).await else { return (Vec::new(), 0) };
let collect = || compile_errors(server.diagnostics_snapshot(), MAX_LAUNCH_ERRORS);
let found = collect();
if found.1 > 0 {
return found;
}
let _ = tokio::time::timeout(ERRORS_WAIT, server.published_notify.notified()).await;
collect()
}
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
pub async fn java_debug_server(&self, path: &Path) -> IdeResult<u16> {
let v = self.jdtls_command(path, "vscode.java.startDebugSession", Vec::new()).await.map_err(|e| {
@@ -323,28 +256,6 @@ impl LspManager {
mod tests {
use super::*;
#[test]
fn launch_errors_are_sorted_and_capped() {
let diag = |line: u32, severity, message: &str| lsp_types::Diagnostic {
range: lsp_types::Range::new(lsp_types::Position::new(line, 4), lsp_types::Position::new(line, 9)),
severity: Some(severity),
message: message.into(),
..Default::default()
};
let (errors, count) = compile_errors(
vec![
(PathBuf::from("/p/B.java"), diag(1, lsp_types::DiagnosticSeverity::ERROR, "b")),
(PathBuf::from("/p/A.java"), diag(9, lsp_types::DiagnosticSeverity::ERROR, "a2\nmore")),
(PathBuf::from("/p/A.java"), diag(2, lsp_types::DiagnosticSeverity::WARNING, "warning")),
(PathBuf::from("/p/A.java"), diag(3, lsp_types::DiagnosticSeverity::ERROR, "a1")),
],
2,
);
assert_eq!(count, 3);
let shown: Vec<(u32, u32, &str)> = errors.iter().map(|e| (e.line, e.column, e.message.as_str())).collect();
assert_eq!(shown, [(4, 5, "a1"), (10, 5, "a2")]);
}
#[test]
fn classpaths() {
let v = json!({
+4 -47
Переглянути файл
@@ -1,6 +1,5 @@
//! Starting server processes: binary resolution and the [`Launcher`] seam.
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use std::ffi::OsString;
@@ -11,8 +10,6 @@ use std::sync::{Arc, OnceLock};
pub enum LaunchError {
/// The server binary is not installed / not on `PATH`.
Missing,
/// The configuration can't be launched (`LanguageServerConfig::launch_error`).
Config(String),
Failed(String),
}
@@ -28,28 +25,13 @@ pub trait Launcher: Send + Sync + 'static {
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError>;
/// [`Launcher::launch`] that gives up once `cancel` fires (the server was stopped
/// while still starting). Launchers that return at once need not override it.
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let _ = cancel;
self.launch(config, root, handler, on_stderr)
}
/// Whether `config` could start without a `Missing` error.
fn available(&self, _config: &LanguageServerConfig, _root: &Path) -> bool {
true
}
}
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport,
/// or for a `connect` server reaches it over TCP (see [`crate::tcp`]).
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport.
pub struct ProcessLauncher;
impl Launcher for ProcessLauncher {
@@ -59,37 +41,12 @@ impl Launcher for ProcessLauncher {
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError> {
self.launch_cancellable(config, root, handler, on_stderr, &CancellationToken::new())
}
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let search = server_search_path(config);
let binary = which::which_in(&config.command, Some(&search), root)
.ok()
.map(|b| resolve_rustup_proxy(&config.command, b));
let binary = which::which_in(&config.command, Some(&search), root).map_err(|_| LaunchError::Missing)?;
let binary = resolve_rustup_proxy(&config.command, binary);
let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())];
env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone())));
if let Some(addr) = &config.connect {
return crate::tcp::connect_or_start(
config,
addr,
binary.as_deref(),
&env,
root,
handler,
on_stderr,
cancel,
);
}
let binary = binary.ok_or(LaunchError::Missing)?;
Peer::spawn(&binary.to_string_lossy(), &config.args, root, &env, handler, on_stderr)
.map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))
}
@@ -115,7 +72,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
if !is_proxy || command.contains('/') {
return binary;
}
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
let works = std::process::Command::new(&binary)
.arg("--version")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
+81 -253
Переглянути файл
@@ -13,18 +13,14 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod scope;
mod server;
mod tcp;
mod text;
mod tsserver_bridge;
pub mod types;
mod uri;
mod virtual_doc;
pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
use caps::{ServerCaps, SyncKind};
@@ -145,7 +141,6 @@ pub struct LspManager {
docs: Mutex<HashMap<DocId, DocState>>,
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
config_hook: RwLock<Option<ConfigHook>>,
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
shutting_down: AtomicBool,
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
shown_messages: Mutex<HashSet<(String, String)>>,
@@ -186,19 +181,6 @@ fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
}
}
/// Sends the user's `didOpen` for `path`, closing a transient copy of the file
/// first (one a references search opened).
fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, params: Value) {
if server.take_transient(path, run.generation)
&& let Err(e) = run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", server.name);
}
if let Err(e) = run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
}
fn unsupported(feature: &str) -> IdeError {
IdeError::unavailable(format!("no running language server supports {feature}"))
}
@@ -251,7 +233,6 @@ impl LspManager {
docs: Mutex::new(HashMap::new()),
apply_edit_hook: RwLock::new(None),
config_hook: RwLock::new(None),
candidates_hook: RwLock::new(None),
shutting_down: AtomicBool::new(false),
shown_messages: Mutex::new(HashSet::new()),
virtual_origins: Mutex::new(HashMap::new()),
@@ -316,8 +297,10 @@ impl LspManager {
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close {
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", d.did_open_params())
{
tracing::debug!("{}: didOpen: {e}", server.name);
}
attached.opened_gen = Some(run.generation);
}
@@ -348,9 +331,7 @@ impl LspManager {
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
let me = self.clone();
let tail = server.clone();
let cancel = server.start_token();
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
// servers may take a while to start listening.
// The settings hook may touch the filesystem (e.g. scanning for JDKs).
let launched = tokio::task::spawn_blocking(move || {
let cfg = me.configured(&tail);
tail.set_effective_config(cfg.clone());
@@ -358,9 +339,9 @@ impl LspManager {
if let Some(message) = &cfg.launch_error {
// A missing binary still asks to be installed first.
let missing = !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
return Err(if missing { LaunchError::Missing } else { LaunchError::Failed(message.clone()) });
}
me.launcher.launch_cancellable(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
})
.await
.unwrap_or_else(|e| Err(LaunchError::Failed(e.to_string())));
@@ -377,13 +358,6 @@ impl LspManager {
}
return;
}
Err(LaunchError::Config(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
server.set_status(&self.sink, ide_core::event::ServerStatus::Misconfigured, Some(message));
}
return;
}
Err(LaunchError::Failed(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
@@ -462,11 +436,9 @@ impl LspManager {
return;
}
let tail = server.stderr_tail(5);
let cfg = server.effective_config();
let mut message = match (code, &cfg.connect) {
(Some(c), _) => format!("{} exited with code {c}", server.name),
(None, Some(addr)) => format!("{}: the connection to the server ({addr}) closed", server.name),
(None, None) => format!("{} terminated unexpectedly", server.name),
let mut message = match code {
Some(c) => format!("{} exited with code {c}", server.name),
None => format!("{} terminated unexpectedly", server.name),
};
if !tail.is_empty() {
message.push_str(":\n");
@@ -496,7 +468,6 @@ impl LspManager {
for (id, title) in server.take_progress() {
self.sink.emit(ide_core::IdeEvent::Task { id, title, message: None, fraction: None, done: true });
}
server.progress_ended();
for path in server.take_diagnostic_paths() {
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.into(),
@@ -612,8 +583,10 @@ impl LspManager {
let params = state.did_open_params();
for a in &mut state.servers {
if let Some(run) = a.server.running() {
if run.caps.read().open_close {
user_did_open(&a.server, &run, &state.path, &state.uri, params.clone());
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", params.clone())
{
tracing::debug!("{}: didOpen: {e}", a.server.name);
}
a.opened_gen = Some(run.generation);
}
@@ -824,40 +797,6 @@ impl LspManager {
out.finish(CompletionList { is_incomplete: false, items: Vec::new() })
}
/// LSP 3.18 `textDocument/inlineCompletion` from every server advertising
/// `inlineCompletionProvider` (`automatic`: triggered by typing, not explicitly).
pub async fn inline_completion(
&self,
doc: DocId,
pos: Pos,
automatic: bool,
cancel: CancellationToken,
) -> IdeResult<Vec<InlineCompletionItem>> {
let (snap, targets) = self.doc_targets(doc, "inline completion", |c| c.has("inlineCompletionProvider")).await?;
let requests = targets.iter().map(|t| {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "triggerKind": if automatic { 2 } else { 1 } });
let cancel = &cancel;
async move {
let r =
self.call::<_, Value>(t, "textDocument/inlineCompletion", params, Some(cancel), COMPLETION_TIMEOUT);
(t, r.await)
}
});
let mut out = Outcome::new();
for (t, result) in join_all(requests).await {
match result {
Ok(v) => {
let conv = self.conv(t.enc());
let items = convert::inline_completion_items(&conv, &snap.path, v, t.server.id);
out.value.get_or_insert_with(Vec::new).extend(items);
}
Err(e) => out.fail(e),
}
}
out.finish(Vec::new())
}
pub async fn resolve_completion(&self, doc: DocId, item: CompletionItem) -> IdeResult<CompletionItem> {
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == item.server) else { return Ok(item) };
@@ -959,61 +898,40 @@ impl LspManager {
out.finish(Vec::new())
}
/// References of the symbol at `pos`. With `project_wide`, files outside
/// the servers' analysis scope that mention the name are opened for the
/// search (see [`scope`]); without, only what the servers analyse counts
/// (cheap, for bulk scans over many symbols).
pub async fn references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
pub async fn references(&self, doc: DocId, pos: Pos, include_declaration: bool) -> IdeResult<Vec<Location>> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
let requests = targets.iter().map(|t| {
let (snap, cancel) = (&snap, &cancel);
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
async move {
let query = || async move {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let locs: Option<Vec<lsp::Location>> =
self.call(t, "textDocument/references", params, Some(cancel), LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
Ok(locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect::<Vec<Location>>())
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
let result = if project_wide {
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
})
};
(t, result)
(
t,
self.call::<_, Option<Vec<lsp::Location>>>(
t,
"textDocument/references",
params,
None,
LONG_TIMEOUT,
)
.await,
)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(w) => {
let acc = out.value.get_or_insert_with(References::default);
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
Ok(locs) => {
let conv = self.conv(t.enc());
let locs: Vec<Location> =
locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect();
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
acc.locations.extend(locs);
acc.incomplete = acc.incomplete.or(w.incomplete);
out.value.get_or_insert_with(Vec::new).extend(locs);
}
Err(e) => out.fail(e),
}
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut v = out.finish(References::default())?;
convert::dedup_locations(&mut v.locations);
let mut v = out.finish(Vec::new())?;
convert::dedup_locations(&mut v);
Ok(v)
}
@@ -1243,29 +1161,13 @@ impl LspManager {
})
}
/// Renames across the project: like [`Self::references`], files outside the
/// server's analysis scope that mention the name are opened for the request.
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let query = || async {
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
};
let files = |e: &WorkspaceEdit| {
e.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(path.to_path_buf()),
_ => None,
})
.collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(w.second.unwrap_or(w.first))
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
}
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
@@ -1314,17 +1216,16 @@ impl LspManager {
/// Some servers (tsserver) only answer for files of a loaded project: when
/// `t` has no document open, one moved file of its languages is opened for the request.
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> scope::TransientFiles<'_> {
let mut opened = scope::TransientFiles::empty(self, t);
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> Option<lsp::Uri> {
if !t.caps().open_close {
return opened;
return None;
}
let busy =
self.docs.lock().values().any(|d| {
d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation))
});
let docs = self.docs.lock();
let busy = docs
.values()
.any(|d| d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation)));
if busy {
return opened;
return None;
}
let languages = t.server.languages();
let candidate =
@@ -1339,10 +1240,14 @@ impl LspManager {
continue;
}
let Ok(text) = std::fs::read_to_string(&file) else { continue };
opened.hold(&file, &language, &text);
break;
let uri = uri::path_to_uri(&file);
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if t.run.peer.notify("textDocument/didOpen", params).is_ok() {
return Some(uri);
}
}
opened
None
}
/// Asks the servers for the edits that keep references intact when files or
@@ -1368,7 +1273,9 @@ impl LspManager {
let opened = self.open_for_file_op(&t, &moves);
let r: IdeResult<Option<lsp::WorkspaceEdit>> =
self.call(&t, "workspace/willRenameFiles", params, Some(&cancel), LONG_TIMEOUT).await;
drop(opened);
if let Some(uri) = opened {
let _ = t.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }));
}
match r {
Ok(Some(edit)) => out.edit.files.extend(convert::workspace_edit(&self.conv(t.enc()), edit).files),
Ok(None) => {}
@@ -1508,52 +1415,6 @@ impl LspManager {
out.finish(Vec::new())
}
/// The document's links; ones without a target are resolved when the server can.
pub async fn document_links(&self, doc: DocId) -> IdeResult<Vec<DocumentLink>> {
let (snap, targets) = self.doc_targets(doc, "document links", |c| c.has("documentLinkProvider")).await?;
let requests = targets.iter().map(|t| {
let params = json!({ "textDocument": snap.ident() });
async move {
let links = self
.call::<_, Option<Vec<lsp::DocumentLink>>>(
t,
"textDocument/documentLink",
params,
None,
DEFAULT_TIMEOUT,
)
.await?
.unwrap_or_default();
if !t.caps().has_sub("documentLinkProvider", "resolveProvider") {
return Ok::<_, IdeError>((t, links));
}
let resolved = join_all(links.into_iter().map(|l| async move {
if l.target.is_some() {
return l;
}
let original = l.clone();
self.call::<_, lsp::DocumentLink>(t, "documentLink/resolve", l, None, DEFAULT_TIMEOUT)
.await
.unwrap_or(original)
}))
.await;
Ok((t, resolved))
}
});
let mut out = Outcome::new();
for r in join_all(requests).await {
match r {
Ok((t, links)) => {
let conv = self.conv(t.enc());
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(links.into_iter().filter_map(|l| convert::document_link(&conv, &snap.path, l)));
}
Err(e) => out.fail(e),
}
}
out.finish(Vec::new())
}
pub async fn call_hierarchy(
&self,
doc: DocId,
@@ -1564,47 +1425,32 @@ impl LspManager {
let t = &targets[0];
let items: Option<Vec<lsp::CallHierarchyItem>> =
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let query = || async {
let mut out = Vec::new();
for item in &items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
let mut out = Vec::new();
for item in items.unwrap_or_default() {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
}
Ok(out)
};
let out = match direction {
// Callers are references: they may sit in files outside the server's scope.
HierarchyDirection::Incoming => {
let files = |v: &Vec<HierarchyItem>| {
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
w.second.unwrap_or(w.first)
}
HierarchyDirection::Outgoing => query().await?,
};
}
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
Ok(out)
}
@@ -1621,13 +1467,12 @@ impl LspManager {
// and lsp-types mistypes `tags` (jdtls sends an array).
let items: Option<Vec<serde_json::Value>> =
self.call(t, "textDocument/prepareTypeHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let method = match direction {
HierarchyDirection::Incoming => "typeHierarchy/supertypes",
HierarchyDirection::Outgoing => "typeHierarchy/subtypes",
};
let mut out = Vec::new();
for item in items {
for item in items.unwrap_or_default() {
let related: Option<Vec<serde_json::Value>> =
self.call(t, method, json!({ "item": item }), None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
@@ -1759,10 +1604,8 @@ impl LspManager {
s.reset_for_restart();
self.ensure_started(&s);
}
// Missing / crashed / misconfigured servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing
| ide_core::event::ServerStatus::Crashed
| ide_core::event::ServerStatus::Misconfigured => {
// Missing / crashed servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing | ide_core::event::ServerStatus::Crashed => {
s.reset_for_restart();
self.ensure_started(&s);
}
@@ -1818,15 +1661,6 @@ impl LspManager {
return;
};
let peer = run.peer.clone();
// A server we connected to without starting it (an open Godot editor) is not
// ours to shut down: only the connection closes.
if peer.pid().is_none() && server.effective_config().connect.is_some() {
peer.kill();
server.end_stop(run.generation);
self.clear_server_state(server);
server.set_status(&self.sink, ide_core::event::ServerStatus::Stopped, None);
return;
}
let graceful = async {
peer.request::<_, Value>("shutdown", (), None).await.ok();
peer.notify("exit", ()).ok();
@@ -1892,12 +1726,6 @@ fn source_actions_only(only: &[String]) -> bool {
!only.is_empty() && only.iter().all(|k| k == "source" || k.starts_with("source."))
}
/// Preparing a call / type hierarchy found no symbol at the position: the UI
/// then retries at the enclosing declaration.
fn no_hierarchy_target() -> IdeError {
IdeError::not_found("No symbol to show the hierarchy of at the caret")
}
#[cfg(test)]
mod send_check {
use super::*;
-248
Переглянути файл
@@ -1,248 +0,0 @@
//! Reference searches beyond a server's analysis scope.
//!
//! Servers answer `textDocument/references` (and rename, incoming calls) from
//! the files they analyse: their configured scope (Pyright's `include`, a
//! `tsconfig.json`, a compilation database) plus the open documents. Usages in
//! other project files are silently missing. So, as a word index would, the
//! project files of the server's languages that contain the symbol's name as a
//! whole word (found through the host's [`CandidateFn`]) and that the first
//! answer did not cover are opened on the server for a second request, then
//! closed again. Diagnostics the server publishes for them are dropped.
use crate::server::{Running, Server};
use crate::types::ReferencesIncomplete;
use crate::{DocSnap, LspManager, Target};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos};
use lsp_types as lsp;
use serde_json::json;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
pub struct CandidateQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Only files under this directory (the server's workspace root).
pub root: PathBuf,
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
}
#[derive(Clone, Debug, Default)]
pub struct CandidateFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`.
pub limit_hit: bool,
}
/// Finds [`CandidateFiles`] (honouring the project's ignore rules); runs on a
/// blocking thread and should stop early when cancelled.
pub type CandidateFn = dyn Fn(&CandidateQuery, &CancellationToken) -> CandidateFiles + Send + Sync;
/// A reference-based answer and, when files were opened for it, the second one.
pub(crate) struct Widened<R> {
pub first: R,
pub second: Option<R>,
pub incomplete: Option<ReferencesIncomplete>,
}
impl<R> Widened<R> {
/// An answer from the server's analysis scope alone; `empty`: it found nothing.
pub fn only(first: R, empty: bool, server: &Server) -> Self {
let incomplete = (empty && server.is_busy()).then_some(ReferencesIncomplete::Indexing);
Self { first, second: None, incomplete }
}
}
/// The name a search is about: the word at `pos` (a PHP `$` sigil dropped).
fn search_word(snap: &DocSnap, pos: Pos) -> Option<String> {
let r = snap.text.word_range_at(pos)?;
let text = snap.text.as_str();
let word = text.get(snap.text.byte_offset(r.start)..snap.text.byte_offset(r.end))?.trim_start_matches('$');
(!word.is_empty() && !word.chars().all(|c| c.is_ascii_digit())).then(|| word.to_owned())
}
impl LspManager {
/// Finds the project files a references search may open (see the module docs).
pub fn set_candidates_hook(&self, hook: Box<CandidateFn>) {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
/// Runs `query` on `t`; then again with the project files that mention the
/// symbol at `pos` and are not in `covered(first)` opened on the server.
/// A first answer that is empty while the server indexes is retried once
/// indexing ends.
pub(crate) async fn widened<R, F, Fut>(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
cancel: &CancellationToken,
query: F,
covered: impl Fn(&R) -> Vec<PathBuf>,
) -> IdeResult<Widened<R>>
where
F: Fn() -> Fut,
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let word = search_word(snap, pos).filter(|_| t.caps().open_close);
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
if busy && covered(&first).is_empty() && t.server.wait_idle(INDEX_WAIT, cancel).await {
first = query().await?;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Servers report analysis progress often; only "nothing found" while it lasts is suspect.
let mut incomplete =
(t.server.is_busy() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
let Some(candidates) = candidates else { return Ok(Widened { first, second: None, incomplete }) };
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
let opened = self.open_transient(t, files, cancel).await;
if opened.files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
tracing::debug!("{}: opened {} more files for a references search", t.server.name, opened.files.len());
let second = query().await;
drop(opened);
match second {
Ok(second) => {
if !covered(&second).is_empty() && incomplete == Some(ReferencesIncomplete::Indexing) {
incomplete = None;
}
Ok(Widened { first, second: Some(second), incomplete })
}
Err(e) if cancel.is_cancelled() => Err(e),
Err(e) => {
tracing::debug!("{}: widened references search: {}", t.server.name, e.message);
Ok(Widened { first, second: None, incomplete })
}
}
}
/// Opens `files` on `t` (read from disk) unless the user has them open;
/// they are closed when the returned guard drops.
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
let read = {
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
files
.into_iter()
.take_while(|_| !cancel.is_cancelled())
.filter(|f| std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() <= MAX_CANDIDATE_BYTES))
.filter_map(|f| std::fs::read_to_string(&f).ok().map(|text| (f, text)))
.collect::<Vec<_>>()
})
.await
.unwrap_or_default()
};
let mut guard = TransientFiles { mgr: self, server: t.server.clone(), run: t.run.clone(), files: Vec::new() };
if cancel.is_cancelled() {
return guard;
}
let docs = self.docs.lock();
for (path, text) in read {
if docs.values().any(|d| d.path == path) {
continue;
}
let uri = crate::uri::path_to_uri(&path);
if t.server.hold_transient(&path, t.run.generation) {
let language = self.languages.detect(&path, text.lines().next());
let params = json!({
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
});
if let Err(e) = t.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", t.server.name);
}
}
guard.files.push((path, uri));
}
guard
}
}
/// Files opened by [`LspManager::open_transient`]; closed on drop.
pub(crate) struct TransientFiles<'a> {
mgr: &'a LspManager,
server: Arc<Server>,
run: Running,
pub files: Vec<(PathBuf, lsp::Uri)>,
}
impl TransientFiles<'_> {
/// Opens one file outside a references search (a file operation needs a loaded project).
pub(crate) fn hold(&mut self, path: &Path, language: &LanguageId, text: &str) {
let _docs = self.mgr.docs.lock();
let uri = crate::uri::path_to_uri(path);
if self.server.hold_transient(path, self.run.generation) {
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", self.server.name);
}
}
self.files.push((path.to_owned(), uri));
}
}
impl<'a> TransientFiles<'a> {
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new() }
}
}
impl Drop for TransientFiles<'_> {
fn drop(&mut self) {
if self.files.is_empty() {
return;
}
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) = self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
}
}
}
}
+14 -239
Переглянути файл
@@ -2,7 +2,7 @@
use crate::caps::ServerCaps;
use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_core::{IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_jsonrpc::Peer;
use ide_language::LanguageServerConfig;
use lsp_types as lsp;
@@ -13,13 +13,9 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Notify, watch};
/// An instance that stayed up this long ran fine: earlier crashes no longer count.
const STABLE_UPTIME: Duration = Duration::from_secs(180);
const CRASH_WINDOW: Duration = Duration::from_secs(180);
const MAX_RESTARTS: usize = 3;
const STDERR_LINES: usize = 50;
/// Diagnostics a server publishes for a transiently opened file shortly after
/// its `didClose` (analysis that was already running) are dropped too.
const TRANSIENT_GRACE: Duration = Duration::from_secs(3);
/// A live, initialized instance.
#[derive(Clone)]
@@ -52,17 +48,6 @@ struct State {
conn: Conn,
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
/// Requests holding the file open.
holders: usize,
generation: u64,
/// The user opened the file meanwhile: its `didOpen` replaced ours.
taken: bool,
closed_at: Option<Instant>,
}
pub struct Progress {
pub task: TaskId,
pub title: String,
@@ -79,14 +64,9 @@ pub struct Server {
effective: Mutex<Option<LanguageServerConfig>>,
languages: Mutex<Vec<LanguageId>>,
state: Mutex<State>,
/// Fired when the instance being started is abandoned (stop / restart while starting).
start_cancel: Mutex<CancellationToken>,
phase: watch::Sender<Phase>,
status: Mutex<(ServerStatus, Option<String>)>,
/// Consecutive crashes of short-lived instances.
crashes: Mutex<usize>,
/// When the current instance was launched.
started: Mutex<Option<Instant>>,
crashes: Mutex<VecDeque<Instant>>,
stderr: Mutex<VecDeque<String>>,
pub progress: Mutex<HashMap<String, Progress>>,
diagnostics: Mutex<HashMap<PathBuf, Vec<lsp::Diagnostic>>>,
@@ -94,9 +74,6 @@ pub struct Server {
published: Mutex<HashMap<PathBuf, Instant>>,
/// Woken on every `publishDiagnostics` (Inspect Code waits on it).
pub published_notify: Notify,
/// Woken when the last `$/progress` task ends.
idle_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
}
impl Server {
@@ -109,18 +86,14 @@ impl Server {
effective: Mutex::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
start_cancel: Mutex::new(CancellationToken::new()),
phase: watch::channel(Phase::Down).0,
status: Mutex::new((ServerStatus::Stopped, None)),
crashes: Mutex::new(0),
started: Mutex::new(None),
crashes: Mutex::new(VecDeque::new()),
stderr: Mutex::new(VecDeque::new()),
progress: Mutex::new(HashMap::new()),
diagnostics: Mutex::new(HashMap::new()),
published: Mutex::new(HashMap::new()),
published_notify: Notify::new(),
idle_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
}
}
@@ -154,8 +127,6 @@ impl Server {
}
st.generation += 1;
st.conn = Conn::Starting;
*self.start_cancel.lock() = CancellationToken::new();
*self.started.lock() = Some(Instant::now());
self.phase.send_replace(Phase::Starting);
Some(st.generation)
}
@@ -220,7 +191,6 @@ impl Server {
}
Conn::Starting => {
st.generation += 1; // invalidates the in-flight start
self.start_cancel.lock().cancel();
self.phase.send_replace(Phase::Down);
None
}
@@ -231,11 +201,6 @@ impl Server {
}
}
/// Cancelled when the current start is abandoned.
pub fn start_token(&self) -> CancellationToken {
self.start_cancel.lock().clone()
}
pub fn end_stop(&self, generation: u64) {
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Stopping) {
@@ -272,22 +237,21 @@ impl Server {
}
}
/// Records a crash; returns the backoff before restarting, or `None` once
/// [`MAX_RESTARTS`] instances in a row died before running [`STABLE_UPTIME`]
/// (a server that crashes on every start, however slowly, is not restarted forever).
/// Records a crash; returns the backoff before restarting, or `None` when
/// the restart budget for the window is exhausted.
pub fn record_crash(&self) -> Option<Duration> {
let uptime = self.started.lock().map(|t| t.elapsed()).unwrap_or_default();
let mut crashes = self.crashes.lock();
if uptime >= STABLE_UPTIME {
*crashes = 0;
let now = Instant::now();
crashes.push_back(now);
while crashes.front().is_some_and(|t| now.duration_since(*t) > CRASH_WINDOW) {
crashes.pop_front();
}
*crashes += 1;
let n = *crashes;
let n = crashes.len();
(n <= MAX_RESTARTS).then(|| Duration::from_millis(500) * (1 << (n - 1)) as u32)
}
pub fn reset_for_restart(&self) {
*self.crashes.lock() = 0;
self.crashes.lock().clear();
let mut st = self.state.lock();
if matches!(st.conn, Conn::Missing | Conn::Failed) {
st.conn = Conn::Idle;
@@ -324,95 +288,6 @@ impl Server {
self.set_status(sink, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
}
/// Whether the server reports work in progress (indexing, analysis).
pub fn is_busy(&self) -> bool {
!self.progress.lock().is_empty()
}
/// Called after a `$/progress` task ended.
pub fn progress_ended(&self) {
if !self.is_busy() {
self.idle_notify.notify_waiters();
}
}
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let notified = self.idle_notify.notified();
if !self.is_busy() || self.running().is_none() {
return !self.is_busy();
}
tokio::select! {
() = notified => {}
() = tokio::time::sleep_until(deadline) => return !self.is_busy(),
() = cancel.cancelled() => return false,
}
}
}
// ---- transiently opened files ----
/// Registers a holder of the transient file `path` on instance `generation`;
/// true when the caller must send `didOpen` (first holder).
pub fn hold_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
map.retain(|_, t| t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE));
let t =
map.entry(path.to_owned()).or_insert(Transient { holders: 0, generation, taken: false, closed_at: None });
if t.holders == 0 || t.generation != generation {
*t = Transient { holders: 1, generation, taken: false, closed_at: None };
return true;
}
t.holders += 1;
false
}
/// Drops a holder of `path`; true when the caller must send `didClose`
/// (last holder, same instance, and the user did not open the file meanwhile).
pub fn release_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
if t.holders == 0 {
return false;
}
t.holders -= 1;
if t.holders > 0 {
return false;
}
let close = !t.taken && t.generation == generation;
if close {
t.closed_at = Some(Instant::now());
} else {
map.remove(path);
}
close
}
/// The user opens `path` on instance `generation`: true when a transient
/// copy is open there and must be closed before the user's `didOpen`.
pub fn take_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
let open = t.holders > 0 && !t.taken && t.generation == generation;
if t.holders > 0 {
t.taken = true;
} else {
map.remove(path);
}
open
}
/// Whether diagnostics published for `path` belong to a transient copy
/// and must not reach the Problems view.
pub fn suppresses_diagnostics(&self, path: &Path) -> bool {
self.transient
.lock()
.get(path)
.is_some_and(|t| !t.taken && (t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE)))
}
// ---- bookkeeping ----
pub fn push_stderr(&self, line: String) {
@@ -425,8 +300,8 @@ impl Server {
pub fn stderr_tail(&self, n: usize) -> String {
let buf = self.stderr.lock();
let lines: Vec<&str> = buf.iter().map(String::as_str).collect();
crash_excerpt(&lines, n)
let skip = buf.len().saturating_sub(n);
buf.iter().skip(skip).cloned().collect::<Vec<_>>().join("\n")
}
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
@@ -455,108 +330,8 @@ impl Server {
self.diagnostics.lock().get(path).cloned().unwrap_or_default()
}
/// Every published diagnostic, by file.
pub fn diagnostics_snapshot(&self) -> Vec<(PathBuf, lsp::Diagnostic)> {
let d = self.diagnostics.lock();
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
}
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
self.published.lock().clear();
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
}
}
/// The last `n` stderr lines, led by the exception headline: Node.js / Python /
/// JVM crashes print the error first and a stack after it, so a plain tail
/// shows frames without saying what went wrong.
pub(crate) fn crash_excerpt(lines: &[&str], n: usize) -> String {
const MAX_LINES: usize = 12;
let start = lines.len().saturating_sub(n);
let excerpt: Vec<&str> = match lines.iter().rposition(|l| is_error_headline(l)) {
Some(i) if i >= start => lines[start..].to_vec(),
Some(i) if lines.len() - i <= MAX_LINES => lines[i..].to_vec(),
Some(i) => [lines[i], "…"].into_iter().chain(lines[start..].iter().copied()).collect(),
None => lines[start..].to_vec(),
};
excerpt.join("\n")
}
fn is_error_headline(line: &str) -> bool {
let l = line.trim_start();
let head = l.split(':').next().unwrap_or_default();
let named = (head.ends_with("Error") || head.ends_with("Exception")) && !head.contains(' ') && head.len() < l.len();
named || l.starts_with("Exception in thread") || l.starts_with("thread '") && l.contains("panicked")
}
#[cfg(test)]
mod tests {
use super::*;
fn server() -> Server {
let cfg: LanguageServerConfig = toml::from_str("name = \"s\"\ncommand = \"s\"").unwrap();
Server::new(cfg, PathBuf::from("/p"), LanguageId::new("vue"))
}
#[test]
fn crashes_of_short_lived_instances_exhaust_the_budget_whatever_the_spacing() {
let s = server();
for _ in 0..MAX_RESTARTS {
// Even crashes spread minutes apart count while each instance dies young.
*s.started.lock() = Some(Instant::now());
assert!(s.record_crash().is_some());
}
*s.started.lock() = Some(Instant::now());
assert_eq!(s.record_crash(), None);
s.reset_for_restart();
assert!(s.record_crash().is_some());
}
#[test]
fn a_stable_run_resets_the_budget() {
let s = server();
for _ in 0..MAX_RESTARTS {
assert!(s.record_crash().is_some());
}
*s.started.lock() = Instant::now().checked_sub(STABLE_UPTIME);
assert_eq!(s.record_crash(), Some(Duration::from_millis(500)));
}
#[test]
fn crash_excerpt_keeps_the_exception_line() {
// Node.js 24 crash of vue-language-server (issue #25), verbatim shape.
let node = [
"C:\\tools\\node_modules\\@vue\\language-server\\lib\\server.js:40",
" projectInfoPromise = sendTsServerRequest('_vue:' + ts.server.protocol.CommandTypes.ProjectInfo, {",
" ^",
"",
"TypeError: Cannot read properties of undefined (reading 'protocol')",
" at Object.getLanguageService (C:\\tools\\node_modules\\@vue\\language-server\\lib\\server.js:40:86)",
" at Immediate.<anonymous> (C:\\tools\\node_modules\\@volar\\language-server\\lib\\features\\languageFeatures.js:744:62)",
" at process.processImmediate (node:internal/timers:504:21)",
"",
"Node.js v24.12.0",
];
let out = crash_excerpt(&node, 5);
assert!(out.starts_with("TypeError: Cannot read properties of undefined (reading 'protocol')"), "{out}");
assert!(out.ends_with("Node.js v24.12.0"));
let python = [
"Traceback (most recent call last):",
" File \"x.py\", line 1",
"ModuleNotFoundError: No module named 'jedi'",
];
assert_eq!(crash_excerpt(&python, 5), python.join("\n"));
let mut long_stack = vec!["Exception in thread \"main\" java.lang.IllegalStateException: boom"];
long_stack.extend(std::iter::repeat_n("\tat a.b.C.d(C.java:1)", 30));
let out = crash_excerpt(&long_stack, 5);
assert!(out.starts_with("Exception in thread \"main\""), "{out}");
assert_eq!(out.lines().count(), 7);
let plain = ["starting", "listening", "bye"];
assert_eq!(crash_excerpt(&plain, 2), "listening\nbye");
// "Error" in prose is not a headline.
assert_eq!(crash_excerpt(&["No Error here: fine", "a", "b"], 2), "a\nb");
}
}
-188
Переглянути файл
@@ -1,188 +0,0 @@
//! LSP over TCP, for servers living inside another program (the Godot editor's
//! GDScript server). Mirrors `ide-dap`'s `tcp` transport: connect to the
//! configured address when something listens there, else start the configured
//! command (`${port}` → a free port, `${root}` → the workspace root) and connect
//! once it accepts. The framing and session are the same as over stdio.
use crate::launch::LaunchError;
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
pub(crate) const PORT_PLACEHOLDER: &str = "${port}";
pub(crate) const ROOT_PLACEHOLDER: &str = "${root}";
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// A headless Godot editor imports the project before it listens.
const START_TIMEOUT: Duration = Duration::from_secs(120);
const POLL: Duration = Duration::from_millis(200);
const TAIL_LINES: usize = 20;
/// `${port}` / `${root}` substituted in every argument.
pub(crate) fn substitute_args(args: &[String], port: Option<u16>, root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter()
.map(|a| {
let a = a.replace(ROOT_PLACEHOLDER, &root);
match port {
Some(p) => a.replace(PORT_PLACEHOLDER, &p.to_string()),
None => a,
}
})
.collect()
}
pub(crate) fn resolve_addr(addr: &str) -> Result<SocketAddr, LaunchError> {
addr.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
.ok_or_else(|| LaunchError::Config(format!("invalid language server address `{addr}`")))
}
/// A connection to `addr` if something accepts there right now.
pub(crate) fn probe(addr: &SocketAddr) -> Option<TcpStream> {
let stream = TcpStream::connect_timeout(addr, PROBE_TIMEOUT).ok()?;
let _ = stream.set_nodelay(true);
Some(stream)
}
/// A port that was free a moment ago on the loopback interface.
pub(crate) fn free_port() -> std::io::Result<u16> {
Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
}
fn into_tokio(stream: TcpStream) -> std::io::Result<tokio::net::TcpStream> {
stream.set_nonblocking(true)?;
tokio::net::TcpStream::from_std(stream)
}
/// Connects to the server of `config` (whose `connect` is set), starting `binary` when
/// nothing listens yet. Blocking; must run on a thread inside a Tokio runtime.
#[allow(clippy::too_many_arguments)]
pub(crate) fn connect_or_start(
config: &LanguageServerConfig,
addr: &str,
binary: Option<&Path>,
env: &[(String, String)],
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let addr = resolve_addr(addr)?;
if let Some(stream) = probe(&addr) {
tracing::info!("{}: connected to the server running at {addr}", config.name);
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect(r, w, handler));
}
let binary = binary.ok_or(LaunchError::Missing)?;
let port = config
.args
.iter()
.any(|a| a.contains(PORT_PLACEHOLDER))
.then(free_port)
.transpose()
.map_err(|e| LaunchError::Failed(format!("no free port: {e}")))?;
let target = port.map_or(addr, |p| SocketAddr::from(([127, 0, 0, 1], p)));
let args = substitute_args(&config.args, port, root);
let mut cmd = tokio::process::Command::new(binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.current_dir(root)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let mut child =
cmd.spawn().map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))?;
tracing::info!("{}: started {} {}, waiting for {target}", config.name, binary.display(), args.join(" "));
let tail: Arc<Mutex<VecDeque<String>>> = Arc::default();
let on_line: Arc<dyn Fn(String) + Send + Sync> = {
let tail = tail.clone();
Arc::new(move |line: String| {
{
let mut t = tail.lock();
if t.len() == TAIL_LINES {
t.pop_front();
}
t.push_back(line.clone());
}
on_stderr(line);
})
};
if let Some(out) = child.stdout.take() {
pump_lines(out, on_line.clone());
}
if let Some(err) = child.stderr.take() {
pump_lines(err, on_line);
}
let failed = |message: String| {
let tail: Vec<String> = tail.lock().iter().cloned().collect();
LaunchError::Failed(if tail.is_empty() { message } else { format!("{message}:\n{}", tail.join("\n")) })
};
let deadline = Instant::now() + START_TIMEOUT;
loop {
if cancel.is_cancelled() {
let _ = child.start_kill();
return Err(LaunchError::Failed(format!("{}: start cancelled", config.name)));
}
if let Some(stream) = probe(&target) {
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect_with_child(r, w, handler, child));
}
if let Ok(Some(status)) = child.try_wait() {
return Err(failed(format!("{} exited before accepting connections on {target} ({status})", config.name)));
}
if Instant::now() >= deadline {
let _ = child.start_kill();
return Err(failed(format!(
"{} did not accept connections on {target} within {}s",
config.name,
START_TIMEOUT.as_secs()
)));
}
std::thread::sleep(POLL);
}
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(stream: R, on_line: Arc<dyn Fn(String) + Send + Sync>) {
tokio::spawn(async move {
let mut lines = BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
on_line(line);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placeholders_are_substituted() {
let args: Vec<String> =
["--path", "${root}", "--lsp-port", "${port}", "--x=${port}"].iter().map(|s| s.to_string()).collect();
assert_eq!(
substitute_args(&args, Some(6010), Path::new("/p/game")),
["--path", "/p/game", "--lsp-port", "6010", "--x=6010"]
);
assert_eq!(substitute_args(&args, None, Path::new("/p"))[3], "${port}");
}
#[test]
fn addresses_resolve() {
assert_eq!(resolve_addr("127.0.0.1:6005").unwrap().port(), 6005);
assert!(matches!(resolve_addr("nonsense"), Err(LaunchError::Config(_))));
}
}
-93
Переглянути файл
@@ -1,93 +0,0 @@
//! Vue Language Server (Volar 3) runs in "hybrid mode": TypeScript work goes to
//! tsserver with `@vue/typescript-plugin`, through the client. It sends
//! `tsserver/request` `[id, command, args]` and waits for `tsserver/response`
//! `[id, body]`; the client forwards the command to vtsls, whose tsserver has the
//! plugin loaded (`typescript.tsserverRequest`). Without an answer the server
//! waits forever, so every request is answered — `null` when vtsls can't.
use crate::LspManager;
use crate::server::Server;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
/// The server that hosts tsserver for the bridge.
pub(crate) const TSSERVER_HOST: &str = "vtsls";
const HOST_START_WAIT: Duration = Duration::from_secs(60);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// `[id, command, args]` items of a `tsserver/request` notification
/// (vscode-jsonrpc wraps the single array argument: `[[id, command, args]]`).
pub(crate) fn parse_requests(params: &Value) -> Vec<(Value, String, Value)> {
let one = |v: &Value| {
let a = v.as_array()?;
let command = a.get(1)?.as_str()?.to_owned();
Some((a.first()?.clone(), command, a.get(2).cloned().unwrap_or(Value::Null)))
};
match params.as_array() {
Some(items) if items.first().is_some_and(Value::is_array) => items.iter().filter_map(one).collect(),
Some(_) => one(params).into_iter().collect(),
None => Vec::new(),
}
}
impl LspManager {
/// Answers `tsserver/request`s of `from` (instance `generation`) via [`TSSERVER_HOST`].
pub(crate) fn forward_tsserver_requests(&self, from: Arc<Server>, generation: u64, params: Value) {
let Some(me) = self.me.upgrade() else { return };
for (id, command, args) in parse_requests(&params) {
let me = me.clone();
let from = from.clone();
self.runtime.spawn(async move {
let body = me.tsserver_request(&from, &command, args).await.unwrap_or(Value::Null);
if let Some(run) = from.running_gen(generation)
&& let Err(e) = run.peer.notify("tsserver/response", json!([[id, body]]))
{
tracing::debug!("{}: tsserver/response: {e}", from.name);
}
});
}
}
async fn tsserver_request(&self, from: &Server, command: &str, args: Value) -> Option<Value> {
let host = self
.servers
.lock()
.iter()
.filter(|s| s.name == TSSERVER_HOST)
.min_by_key(|s| s.root != from.root)
.cloned()?;
let run = host.wait_ready(HOST_START_WAIT).await?;
let params = json!({
"command": "typescript.tsserverRequest",
"arguments": [command, args, { "isAsync": true, "lowPriority": true }],
});
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
match tokio::time::timeout(REQUEST_TIMEOUT, request).await {
Ok(Ok(result)) => result.get("body").cloned(),
Ok(Err(e)) => {
tracing::debug!("{TSSERVER_HOST}: {command}: {e}");
None
}
Err(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_wrapped_and_bare_requests() {
let wrapped = json!([[1, "_vue:projectInfo", { "file": "/p/App.vue" }]]);
assert_eq!(
parse_requests(&wrapped),
vec![(json!(1), "_vue:projectInfo".to_owned(), json!({ "file": "/p/App.vue" }))]
);
let bare = json!([2, "_vue:getComponentNames", ["/p/App.vue"]]);
assert_eq!(parse_requests(&bare), vec![(json!(2), "_vue:getComponentNames".to_owned(), json!(["/p/App.vue"]))]);
assert!(parse_requests(&json!({ "id": 1 })).is_empty());
assert!(parse_requests(&json!([[3]])).is_empty());
}
}
-60
Переглянути файл
@@ -145,21 +145,6 @@ pub struct Command {
pub arguments: Vec<serde_json::Value>,
}
/// One `textDocument/inlineCompletion` suggestion (ghost text at the caret).
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InlineCompletionItem {
/// Text that replaces `range`; snippets arrive as their plain text.
pub insert_text: String,
/// Replaced range; `None` inserts at the caret.
pub range: Option<Range>,
/// What the typed text is matched against while the suggestion stays shown (default: `insert_text`).
pub filter_text: Option<String>,
/// Run after the suggestion is accepted.
pub command: Option<Command>,
pub server: ServerId,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CodeAction {
@@ -210,19 +195,6 @@ pub struct InlayHint {
pub padding_left: bool,
pub padding_right: bool,
pub tooltip: Option<String>,
/// The label's parts when the server split it (empty for a plain label);
/// their values concatenate to `label`.
pub parts: Vec<InlayLabelPart>,
}
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InlayLabelPart {
pub value: String,
pub tooltip: Option<String>,
/// Declaration the part stands for (⌘-click navigates there).
pub location: Option<Location>,
}
/// Decoded semantic tokens (absolute positions) with the server legend applied.
@@ -242,21 +214,6 @@ pub struct CodeLens {
pub command: Option<Command>,
}
/// A link in a document (`textDocument/documentLink`): an HTML `href`, a
/// Markdown link, an `#include`, a JSON `$schema`…
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentLink {
pub range: Range,
/// A `file:` target.
pub path: Option<ide_core::IpcPath>,
/// The `#fragment` of a `file:` target (`L12`, `L12,5`, a heading or element id).
pub fragment: Option<String>,
/// Any other target (`https:`, …).
pub url: Option<String>,
pub tooltip: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HierarchyDirection {
@@ -322,20 +279,3 @@ pub struct FileRenameEdits {
/// Servers that failed; their references are not updated.
pub errors: Vec<String>,
}
/// Why a references search may have missed usages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ReferencesIncomplete {
/// A language server was still indexing.
Indexing,
/// More project files mention the name than were checked.
TooManyFiles,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
}
+8 -431
Переглянути файл
@@ -27,13 +27,9 @@ struct MockState {
/// uri → text as reconstructed by the mock from didOpen/didChange.
docs: Mutex<HashMap<String, String>>,
responses: Mutex<HashMap<String, Value>>,
/// Computes a response from the request and the open documents (before `responses`).
responder: Mutex<Option<Responder>>,
peer: Mutex<Option<Peer>>,
}
type Responder = Arc<dyn Fn(&MockState, &str, &Value) -> Option<Value> + Send + Sync>;
impl MockState {
fn notified(&self, method: &str) -> Vec<Value> {
self.notifications.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
@@ -115,17 +111,11 @@ impl Handler for MockHandler {
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params.clone()));
s.requests.lock().push((method.to_owned(), params));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"shutdown" => Ok(Value::Null),
_ => {
let responder = s.responder.lock().clone();
if let Some(v) = responder.and_then(|f| f(s, method, &params)) {
return Ok(v);
}
Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null))
}
_ => Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null)),
}
}
}
@@ -202,7 +192,6 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
root_markers: vec!["mock.toml".into()],
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
launch_error: None,
}
@@ -426,42 +415,6 @@ async fn completion_mapping_merge_and_resolve() {
assert!(b.requested("completionItem/resolve").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn inline_completion_only_from_servers_that_advertise_it() {
let h = harness(&[
("plain", incremental_caps()),
("ghost", json!({ "textDocumentSync": 2, "inlineCompletionProvider": {} })),
("late", json!({ "textDocumentSync": 2 })),
]);
let (doc, _) = h.open("a.mk", "let x = fo");
for name in ["plain", "ghost", "late"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (plain, ghost) = (h.launcher.state("plain"), h.launcher.state("ghost"));
let init = &plain.requested("initialize")[0];
assert_eq!(init["capabilities"]["textDocument"]["inlineCompletion"], json!({ "dynamicRegistration": true }));
ghost.respond(
"textDocument/inlineCompletion",
json!({ "items": [
{ "insertText": "foo(1)", "range": {"start":{"line":0,"character":8},"end":{"line":0,"character":10}},
"command": { "title": "accepted", "command": "ghost.accepted", "arguments": [7] } },
{ "insertText": { "kind": "snippet", "value": "foo(${1:a}, $2)$0" }, "filterText": "fo" },
{ "insertText": "" }
] }),
);
let items = h.mgr.inline_completion(doc, Pos::new(0, 10), true, Default::default()).await.unwrap();
assert_eq!(items.len(), 2);
assert_eq!(items[0].insert_text, "foo(1)");
assert_eq!(items[0].range, Some(rng(0, 8, 0, 10)));
assert_eq!(items[0].command.as_ref().unwrap().command, "ghost.accepted");
assert_eq!(items[1].insert_text, "foo(a, )");
assert_eq!(items[1].filter_text.as_deref(), Some("fo"));
let req = &ghost.requested("textDocument/inlineCompletion")[0];
assert_eq!(req["context"], json!({ "triggerKind": 2 }));
assert_eq!(req["position"], json!({ "line": 0, "character": 10 }));
assert!(plain.requested("textDocument/inlineCompletion").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_become_events_and_feed_code_actions() {
let h = harness(&[("mock", incremental_caps())]);
@@ -757,15 +710,13 @@ async fn launch_error_fails_without_starting_the_server() {
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.launch_error = Some("needs JDK 21".into())));
assert!(!h.mgr.serves_path(&h.root.join("a.mk")), "batch inspection skips it");
h.open("a.mk", "x");
// Not a crash: nothing ran, the configuration has to change.
h.wait_status("mock", ServerStatus::Misconfigured).await;
h.wait_status("mock", ServerStatus::Crashed).await;
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 0);
let reason = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Misconfigured, message, .. } => message.clone(),
let crashed = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Crashed, message, .. } => message.clone(),
_ => None,
});
assert_eq!(reason.as_deref(), Some("needs JDK 21"));
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
assert_eq!(crashed.as_deref(), Some("needs JDK 21"));
}
#[tokio::test(flavor = "multi_thread")]
@@ -811,7 +762,7 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
s.respond("textDocument/references", json!([{ "uri": uri, "range": r(0,3,0,6) }, { "uri": uri, "range": r(1,0,1,3) }, { "uri": uri, "range": r(1,0,1,3) }]));
let refs = h.mgr.references(doc, Pos::new(1, 1), true, true, Default::default()).await.unwrap().locations;
let refs = h.mgr.references(doc, Pos::new(1, 1), true).await.unwrap();
assert_eq!(refs.len(), 2);
assert_eq!(s.requested("textDocument/references")[0]["context"]["includeDeclaration"], true);
@@ -853,11 +804,6 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(hints[0].label, "x:");
assert_eq!(hints[0].kind, InlayKind::Parameter);
// Nothing to prepare at the position: NotFound, so the UI can retry at the enclosing declaration.
s.respond("textDocument/prepareCallHierarchy", json!(null));
let err = h.mgr.call_hierarchy(doc, Pos::new(0, 1), HierarchyDirection::Incoming).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
s.respond("textDocument/prepareCallHierarchy", json!([item]));
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
@@ -997,7 +943,7 @@ async fn virtual_locations_and_text_document_content() {
"textDocument/references",
json!([{ "uri": uri_of(&path), "range": r(0, 4, 0, 9) }, { "uri": lib, "range": r(2, 4, 2, 9) }]),
);
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap().locations;
let refs = h.mgr.references(doc, Pos::new(0, 5), true).await.unwrap();
assert_eq!(refs.iter().map(|l| l.uri.is_some()).collect::<Vec<_>>(), vec![false, true]);
s.respond(
"textDocument/prepareTypeHierarchy",
@@ -1277,372 +1223,3 @@ async fn inspect_reports_files_without_a_server() {
let results = inspect(&h, "plaintext", vec![txt]).await;
assert!(matches!(results[0].1, ide_lsp::FileInspection::NoServer));
}
#[tokio::test(flavor = "multi_thread")]
async fn css_family_configuration_returns_default_objects() {
for language in ["css", "scss", "less"] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
let registry = Arc::new(LanguageRegistry::load(None).unwrap());
let launcher = Arc::new(MockLauncher::default());
let state = launcher.state("vscode-css-language-server");
*state.caps.lock() = incremental_caps();
let mgr = LspManager::with_launcher(root.clone(), registry, Arc::new(|_| {}), launcher);
let path = root.join(format!("a.{language}"));
let text = ".qa { colr: red; }";
std::fs::write(&path, text).unwrap();
mgr.did_open(DocId::next(), &path, &LanguageId::new(language), 1, text);
eventually(|| !state.notified("textDocument/didOpen").is_empty()).await;
let reply: Value = state
.peer()
.request(
"workspace/configuration",
json!({ "items": [
{ "section": "css", "scopeUri": uri_of(&path) },
{ "section": "scss", "scopeUri": uri_of(&path) },
{ "section": "less", "scopeUri": uri_of(&path) },
{ "section": "unknown" }
] }),
None,
)
.await
.unwrap();
assert_eq!(reply, json!([{}, {}, {}, null]), "{language}");
assert_eq!(state.requested("initialize")[0]["initializationOptions"]["provideFormatter"], true);
}
}
// ------------------------------------------------------------------ references beyond the analysis scope
const WORD: &str = "target";
/// Locations of [`WORD`] in `text` (ASCII, so UTF-16 columns are byte offsets).
fn occurrences(uri: &str, text: &str) -> Vec<Value> {
let mut out = Vec::new();
for (line, l) in text.lines().enumerate() {
for (col, _) in l.match_indices(WORD) {
let end = col + WORD.len();
out.push(json!({ "uri": uri, "range": {
"start": { "line": line, "character": col }, "end": { "line": line, "character": end } } }));
}
}
out
}
/// A server that only analyses its open documents (minus `blind` URIs), like
/// Pyright for files outside its `include`.
fn open_files_only(blind: Vec<String>) -> Responder {
Arc::new(move |s, method, _| {
let docs: Vec<(String, String)> =
s.docs.lock().iter().filter(|(u, _)| !blind.contains(u)).map(|(u, t)| (u.clone(), t.clone())).collect();
let locs = || docs.iter().flat_map(|(u, t)| occurrences(u, t));
match method {
"textDocument/references" => Some(Value::Array(locs().collect())),
"textDocument/rename" => {
let mut changes = serde_json::Map::new();
for loc in locs() {
let edits = changes.entry(loc["uri"].as_str().unwrap()).or_insert_with(|| json!([]));
edits.as_array_mut().unwrap().push(json!({ "range": loc["range"], "newText": "renamed" }));
}
Some(json!({ "changes": changes }))
}
_ => None,
}
})
}
/// Candidate files: those directly under the root that contain the word; records the queries.
fn grep_candidates(h: &Harness) -> Arc<Mutex<Vec<ide_lsp::CandidateQuery>>> {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
h.mgr.set_candidates_hook(Box::new(move |q, _| {
log.lock().push(q.clone());
let mut files: Vec<PathBuf> = std::fs::read_dir(&q.root)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| std::fs::read_to_string(p).is_ok_and(|t| t.contains(&q.word)))
.collect();
files.sort();
ide_lsp::CandidateFiles { files, limit_hit: false }
}));
seen
}
fn uris(params: &[Value]) -> Vec<String> {
params.iter().map(|p| p["textDocument"]["uri"].as_str().unwrap().to_owned()).collect()
}
fn diagnostics_for(h: &Harness, path: &Path) -> usize {
h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Diagnostics { path: p, .. } if p == path)).count()
}
fn scope_harness() -> (Harness, Arc<MockState>) {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
*s.responder.lock() = Some(open_files_only(vec![]));
(h, s)
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
let seen = grep_candidates(&h);
let b = h.root.join("b.mk");
let c = h.root.join("c.mk");
std::fs::write(&b, "call target\n").unwrap();
std::fs::write(&c, "nothing here\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let (_, d) = h.open("d.mk", "use target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let mut paths: Vec<PathBuf> = refs.locations.iter().map(|l| l.path.to_path_buf()).collect();
paths.sort();
assert_eq!(paths, vec![a.clone(), b.clone(), d.clone()]);
assert_eq!(refs.incomplete, None);
let q = seen.lock()[0].clone();
assert_eq!((q.word.as_str(), q.root.as_path(), q.limit), (WORD, h.root.as_path(), ide_lsp::MAX_CANDIDATES));
assert_eq!(q.languages, vec![h.lang.clone()]);
// Only the unopened candidate was opened (from disk), then closed again.
let opens = s.notified("textDocument/didOpen");
let temp: Vec<&Value> = opens.iter().filter(|p| p["textDocument"]["uri"] == uri_of(&b)).collect();
assert_eq!(temp.len(), 1);
assert_eq!(temp[0]["textDocument"]["version"], 0);
assert_eq!(temp[0]["textDocument"]["text"], "call target\n");
assert!(!uris(&opens).contains(&uri_of(&c)));
assert_eq!(uris(&opens).iter().filter(|u| **u == uri_of(&d)).count(), 1);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
assert_eq!(s.requested("textDocument/references").len(), 2);
assert_eq!(s.docs.lock().len(), 2);
// When every candidate file is already in the answer, no second request is made.
std::fs::remove_file(&b).unwrap();
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(s.requested("textDocument/references").len(), 3);
// Without project_wide only the server's scope counts: no project search.
std::fs::write(&b, "call target\n").unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(seen.lock().len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn references_never_reopen_or_close_the_users_files() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
// Open, mentions the name, but the server does not report it.
let (_, d) = h.open("d.mk", "use target\n");
*s.responder.lock() = Some(open_files_only(vec![uri_of(&d)]));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(uris(&s.notified("textDocument/didOpen")).iter().filter(|u| **u == uri_of(&d)).count(), 1);
assert!(s.notified("textDocument/didClose").is_empty());
assert_eq!(s.requested("textDocument/references").len(), 1);
assert!(s.docs.lock().contains_key(&uri_of(&d)));
}
#[tokio::test(flavor = "multi_thread")]
async fn references_report_a_capped_candidate_search() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|q, _| ide_lsp::CandidateFiles {
files: vec![q.root.join("b.mk")],
limit_hit: true,
}));
std::fs::write(h.root.join("b.mk"), "target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_references_search_stops_the_candidate_search_and_closes_files() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|_, cancel| {
while !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(5));
}
ide_lsp::CandidateFiles::default()
}));
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
later.cancel();
});
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
// Cancelled while the server answers with a file opened for the search.
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
grep_candidates(&h);
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&slow) {
std::thread::sleep(Duration::from_millis(600));
}
inner(s, method, params)
}));
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
later.cancel();
});
let started = std::time::Instant::now();
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed() < Duration::from_millis(550));
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_of_files_opened_for_a_search_stay_out_of_problems() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let diag = json!([{ "range": {"start":{"line":0,"character":0},"end":{"line":0,"character":1}}, "message": "e" }]);
let inner = open_files_only(vec![]);
let (temp, user, d) = (uri_of(&b), uri_of(&a), diag.clone());
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&temp) {
for uri in [&temp, &user] {
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri, "diagnostics": d })).unwrap();
}
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
// Published right after the didClose (analysis still running): dropped too.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": diag })).unwrap();
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&a), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &a) == 2).await;
assert_eq!(diagnostics_for(&h, &b), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn opening_a_file_during_a_search_takes_it_over() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().get(&slow).is_some_and(|t| t.starts_with("call")) {
std::thread::sleep(Duration::from_millis(400));
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let mgr = h.mgr.clone();
let search = tokio::spawn(async move { mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await });
eventually(|| s.docs.lock().contains_key(&uri_of(&b))).await;
let user_doc = DocId::next();
h.mgr.did_open(user_doc, &b, &h.lang, 7, "edited target\n");
search.await.unwrap().unwrap();
// The temporary copy was closed before the user's didOpen, and the user's stays open.
let events: Vec<(String, Value)> = s
.notifications
.lock()
.iter()
.filter(|(m, p)| m.starts_with("textDocument/did") && p["textDocument"]["uri"] == uri_of(&b))
.map(|(m, p)| (m.clone(), p["textDocument"]["version"].clone()))
.collect();
assert_eq!(
events,
vec![
("textDocument/didOpen".to_owned(), json!(0)),
("textDocument/didClose".to_owned(), Value::Null),
("textDocument/didOpen".to_owned(), json!(7)),
]
);
assert_eq!(s.docs.lock().get(&uri_of(&b)).map(String::as_str), Some("edited target\n"));
// Its diagnostics are the user's again.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &b) == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_empty_answer_while_indexing_is_retried_when_indexing_ends() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
let (doc, path) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let peer = s.peer();
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let (state, uri) = (s.clone(), uri_of(&path));
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
state.respond("textDocument/references", Value::Array(occurrences(&uri, "def target\n")));
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "end" } })).unwrap();
});
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(refs.incomplete, None);
assert_eq!(s.requested("textDocument/references").len(), 2);
// While the server works, results are taken as they are; finding nothing is flagged.
s.peer()
.notify("$/progress", json!({ "token": "again", "value": { "kind": "begin", "title": "Indexing" } }))
.unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!((refs.locations.len(), refs.incomplete), (1, None));
s.respond("textDocument/references", json!([]));
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 0);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_edits_files_outside_the_analysis_scope() {
let (h, s) = scope_harness();
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into()).await.unwrap();
let mut paths: Vec<PathBuf> = edit
.files
.iter()
.map(|f| match f {
FileEdit::Edit { path, .. } => path.to_path_buf(),
_ => panic!("unexpected {f:?}"),
})
.collect();
paths.sort();
assert_eq!(paths, vec![a, b.clone()]);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
+1 -76
Переглянути файл
@@ -71,7 +71,6 @@ async fn missing_binary_is_reported_with_install_hint() {
root_markers: vec![],
initialization_options: None,
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
launch_error: None,
};
@@ -125,7 +124,7 @@ async fn rust_analyzer_end_to_end() {
mgr.did_open(doc, &main, &LanguageId::new("rust"), 1, MAIN_RS);
retry("rust-analyzer ready", Duration::from_secs(60), || {
let s = last_status(&events, "rust-analyzer");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &s {
if let Some((ServerStatus::Crashed | ServerStatus::Missing, msg)) = &s {
panic!("rust-analyzer failed: {msg:?}");
}
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
@@ -199,7 +198,6 @@ async fn typescript_language_server_end_to_end() {
root_markers: vec!["tsconfig.json".into()],
initialization_options: None,
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
};
@@ -229,76 +227,3 @@ async fn typescript_language_server_end_to_end() {
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
const APP_VUE: &str = "<script setup lang=\"ts\">\nconst count: number = 1\n</script>\n\n<template>\n <div>{{ count }}</div>\n</template>\n";
fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Value>) -> LanguageServerConfig {
LanguageServerConfig {
name: name.into(),
command: tools.join("node_modules/.bin").join(bin).to_string_lossy().into_owned(),
args: vec!["--stdio".into()],
env: Default::default(),
root_markers: vec!["package.json".into()],
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
}
}
/// Vue Language Server 3 in hybrid mode: its `tsserver/request`s go through the
/// client to vtsls with `@vue/typescript-plugin` (issue #25). Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@"<7" @vtsls/language-server`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vue/language-server and @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vue_hybrid_mode_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
std::fs::write(root.join("tsconfig.json"), "{\"compilerOptions\":{\"strict\":true},\"include\":[\"src/**/*\"]}")
.unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
let file = root.join("src/App.vue");
std::fs::write(&file, APP_VUE).unwrap();
let plugin = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
"name": "@vue/typescript-plugin",
"location": tools.join("node_modules/@vue/language-server").to_string_lossy(),
"languages": ["vue"],
"configNamespace": "typescript",
"enableForWorkspaceTypeScriptVersions": true,
}] } } });
for with_vtsls in [false, true] {
let mut vue = lang("vue", "vue", npm_server(&tools, "vue-language-server", "vue-language-server", None));
if with_vtsls {
vue.language_servers.push(npm_server(&tools, "vtsls", "vtsls", Some(plugin.clone())));
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![vue]));
let doc = DocId::next();
mgr.did_open(doc, &file, &LanguageId::new("vue"), 1, APP_VUE);
// `count` in `{{ count }}`.
let pos = Pos::new(5, 12);
if with_vtsls {
let hover = retry("hover", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.hover(doc, pos, Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.contains("count: number"), "{}", hover.contents.value);
}
retry("vue-language-server ready", Duration::from_secs(30), || {
let s = last_status(&events, "vue-language-server");
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
// Every request of vue-language-server waits for a tsserver answer (the
// project info); without vtsls it is `null` and the server falls back.
let symbols = tokio::time::timeout(Duration::from_secs(20), mgr.document_symbols(doc)).await;
assert!(matches!(symbols, Ok(Ok(_))), "vue-language-server did not answer: {symbols:?}");
let crashed = matches!(last_status(&events, "vue-language-server"), Some((ServerStatus::Crashed, _)));
assert!(!crashed, "{:?}", last_status(&events, "vue-language-server"));
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
-241
Переглянути файл
@@ -1,241 +0,0 @@
//! Language servers reached over TCP (`connect`, the Godot editor's GDScript
//! server) against a mock LSP server on a local socket.
use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId, Pos};
use ide_jsonrpc::{Handler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
use ide_lsp::{LaunchError, Launcher, LspManager, ProcessLauncher};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
struct ServerLog {
requests: Mutex<Vec<String>>,
notifications: Mutex<Vec<String>>,
/// Server ends of the accepted connections.
peers: Mutex<Vec<Peer>>,
}
struct MockHandler(Arc<ServerLog>);
impl Handler for MockHandler {
fn on_notification(&self, method: &str, _params: Value) {
self.0.notifications.lock().push(method.to_owned());
}
fn on_request(&self, method: &str, _params: Value) -> Result<Value, (i64, String)> {
self.0.requests.lock().push(method.to_owned());
match method {
"initialize" => Ok(json!({
"capabilities": { "textDocumentSync": 1, "hoverProvider": true },
"serverInfo": { "name": "mock-godot" }
})),
"textDocument/hover" => Ok(json!({ "contents": { "kind": "markdown", "value": "**Node2D**" } })),
_ => Ok(Value::Null),
}
}
}
/// Accepts LSP connections on a local port, like the Godot editor on 6005.
async fn mock_server() -> (u16, Arc<ServerLog>, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(ServerLog::default());
let accept = {
let log = log.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let (r, w) = stream.into_split();
let peer = Peer::connect(r, w, Arc::new(MockHandler(log.clone())));
log.peers.lock().push(peer);
}
})
};
(port, log, accept)
}
fn godot_cfg(port: u16, command: &str) -> LanguageServerConfig {
toml::from_str(&format!(
"name = \"godot\"\ncommand = \"{command}\"\nconnect = \"127.0.0.1:{port}\"\nroot-markers = [\"project.godot\"]\ninstall-hint = \"Open the project in the Godot editor\""
))
.unwrap()
}
struct Harness {
_dir: tempfile::TempDir,
root: PathBuf,
mgr: Arc<LspManager>,
events: Arc<Mutex<Vec<IdeEvent>>>,
}
fn harness(server: LanguageServerConfig) -> Harness {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
let lang: LanguageConfig = toml::from_str("id = \"gdscript\"\nname = \"GDScript\"\nextensions = [\"gd\"]").unwrap();
let lang = LanguageConfig { language_servers: vec![server], ..lang };
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let mgr = LspManager::with_launcher(root.clone(), registry, sink, Arc::new(ProcessLauncher));
Harness { _dir: dir, root, mgr, events }
}
impl Harness {
fn open(&self, name: &str, text: &str) -> DocId {
let path = self.root.join(name);
std::fs::write(&path, text).unwrap();
let doc = DocId::next();
self.mgr.did_open(doc, &path, &LanguageId::new("gdscript"), 1, text);
doc
}
fn statuses(&self) -> Vec<(ServerStatus, Option<String>)> {
self.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::LanguageServer { status, message, .. } => Some((*status, message.clone())),
_ => None,
})
.collect()
}
async fn wait_status(&self, status: ServerStatus, count: usize) {
eventually(|| self.statuses().iter().filter(|(s, _)| *s == status).count() >= count).await;
}
}
async fn eventually(mut f: impl FnMut() -> bool) {
for _ in 0..1000 {
if f() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("condition not reached in time");
}
#[tokio::test(flavor = "multi_thread")]
async fn connects_to_a_running_server_requests_and_reconnects() {
let (port, log, _accept) = mock_server().await;
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
let doc = h.open("player.gd", "extends Node2D\n");
h.wait_status(ServerStatus::Ready, 1).await;
assert_eq!(log.requests.lock().first().map(String::as_str), Some("initialize"));
eventually(|| log.notifications.lock().iter().any(|m| m == "textDocument/didOpen")).await;
let hover = h.mgr.hover(doc, Pos::new(0, 9), CancellationToken::new()).await.unwrap().unwrap();
assert!(format!("{hover:?}").contains("Node2D"), "{hover:?}");
// Attached to a server it didn't start: no process id.
assert_eq!(h.mgr.servers()[0].pid, None);
// The editor drops the connection (closed or restarted): the client reconnects and reopens.
log.peers.lock().remove(0).kill();
h.wait_status(ServerStatus::Crashed, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Crashed).unwrap();
assert!(message.unwrap().contains(&format!("127.0.0.1:{port}")));
h.wait_status(ServerStatus::Ready, 2).await;
eventually(|| log.notifications.lock().iter().filter(|m| *m == "textDocument/didOpen").count() == 2).await;
assert_eq!(log.requests.lock().iter().filter(|m| *m == "initialize").count(), 2);
// Shutting down leaves a server it didn't start running: no `shutdown` / `exit`.
h.mgr.shutdown_all().await;
eventually(|| log.peers.lock().iter().all(Peer::is_closed)).await;
assert!(!log.requests.lock().iter().any(|m| m == "shutdown"));
assert!(!log.notifications.lock().iter().any(|m| m == "exit"));
}
#[tokio::test(flavor = "multi_thread")]
async fn nothing_listening_and_no_executable_reports_how_to_fix_it() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
h.open("player.gd", "extends Node\n");
h.wait_status(ServerStatus::Missing, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Missing).unwrap();
assert_eq!(message.as_deref(), Some("Open the project in the Godot editor"));
}
/// The command is started when nothing listens yet, the client waits until the
/// port accepts, and the started process belongs to the connection.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn starts_the_command_and_waits_until_it_listens() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let root = tempfile::tempdir().unwrap();
// The "server" (`sleep`) never listens itself; a listener comes up a moment later.
let log = Arc::new(ServerLog::default());
let server = {
let log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(400)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
let (r, w) = stream.into_split();
log.peers.lock().push(Peer::connect(r, w, Arc::new(MockHandler(log.clone()))));
})
};
let path = root.path().to_path_buf();
let peer = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.unwrap_or_else(|e| panic!("{e:?}"));
server.await.unwrap();
let pid = peer.pid().expect("owns the started process");
let init: Value = peer.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["serverInfo"]["name"], "mock-godot");
peer.kill();
peer.closed().await;
eventually(|| !process_alive(pid)).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_command_that_exits_without_listening_fails_and_cancel_stops_waiting() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let root = tempfile::tempdir().unwrap();
let path = root.path().to_path_buf();
let cfg = godot_cfg(port, "false");
let err = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.err()
.expect("fails");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("exited before accepting connections")), "{err:?}");
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let path = root.path().to_path_buf();
let cancel = CancellationToken::new();
let token = cancel.clone();
let started = std::time::Instant::now();
let waiting = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch_cancellable(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}), &token)
});
tokio::time::sleep(Duration::from_millis(300)).await;
cancel.cancel();
let err = waiting.await.unwrap().err().expect("cancelled");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("cancelled")), "{err:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
+2 -7
Переглянути файл
@@ -20,9 +20,7 @@ mod sandbox;
mod theme;
mod types;
pub use manifest::{
API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest, ThemeDecl,
};
pub use manifest::{API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest};
pub use sandbox::resolve_in_root;
pub use theme::{ThemeDef, ThemeKind};
pub use types::*;
@@ -629,10 +627,7 @@ fn static_contributions(dir: &Path, m: &PluginManifest) -> Result<Registrations,
regs.add_language(cfg);
}
for f in &m.contributes.themes {
let mut theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?;
if let Some(scheme) = &f.editor_scheme {
theme.merge_editor_scheme(&read(scheme)?).map_err(|e| format!("{}: {e}", scheme.display()))?;
}
let theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?;
regs.add_theme(theme);
}
Ok(regs)
+5 -25
Переглянути файл
@@ -64,7 +64,7 @@ pub struct Contributions {
#[serde(default)]
pub languages: Vec<FileDecl>,
#[serde(default)]
pub themes: Vec<ThemeDecl>,
pub themes: Vec<FileDecl>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -83,16 +83,6 @@ pub struct FileDecl {
pub path: PathBuf,
}
/// A contributed theme: the UI theme file plus an optional editor colour scheme
/// whose tokens are merged over it (IntelliJ's `.theme.json` + `.icls`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ThemeDecl {
pub path: PathBuf,
#[serde(default)]
pub editor_scheme: Option<PathBuf>,
}
impl PluginManifest {
pub fn parse(src: &str) -> Result<Self, String> {
let manifest: Self = toml::from_str(src).map_err(|e| e.to_string())?;
@@ -133,9 +123,8 @@ impl PluginManifest {
return Err(format!("command {:?} has an empty title", c.id));
}
}
let theme_files = self.contributes.themes.iter().flat_map(|t| std::iter::once(&t.path).chain(&t.editor_scheme));
for path in self.contributes.languages.iter().map(|f| &f.path).chain(theme_files) {
check_relative(path, "contributes path")?;
for f in self.contributes.languages.iter().chain(&self.contributes.themes) {
check_relative(&f.path, "contributes path")?;
}
Ok(())
}
@@ -144,10 +133,7 @@ impl PluginManifest {
pub fn files(&self) -> Vec<&Path> {
let mut files: Vec<&Path> = self.wasm.iter().map(PathBuf::as_path).collect();
files.extend(self.contributes.languages.iter().map(|f| f.path.as_path()));
for t in &self.contributes.themes {
files.push(t.path.as_path());
files.extend(t.editor_scheme.as_deref());
}
files.extend(self.contributes.themes.iter().map(|f| f.path.as_path()));
files
}
@@ -216,7 +202,6 @@ mod tests {
[[contributes.themes]]
path = "themes/dark.json"
editor-scheme = "themes/dark.scheme.json"
"#;
#[test]
@@ -225,10 +210,7 @@ mod tests {
assert_eq!(m.id, "hello");
assert_eq!(m.permissions, vec![Permission::ProjectRead, Permission::EditorWrite]);
assert_eq!(m.contributes.commands[0].category.as_deref(), Some("Hello"));
assert_eq!(
m.files(),
vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json"), Path::new("themes/dark.scheme.json")]
);
assert_eq!(m.files(), vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json")]);
assert!(m.has(Permission::EditorWrite) && !m.has(Permission::EditorRead));
}
@@ -260,8 +242,6 @@ mod tests {
assert!(err(&base(dup, "ok", "0.1")).contains("duplicate command"));
let traversal = "[[contributes.languages]]\npath = \"a/../../x.toml\"";
assert!(err(&base(traversal, "ok", "0.1")).contains("relative path"));
let scheme_escape = "[[contributes.themes]]\npath = \"t.json\"\neditor-scheme = \"../s.json\"";
assert!(err(&base(scheme_escape, "ok", "0.1")).contains("relative path"));
assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nopenidea-api = \"0.1\"").contains("version"));
assert!(err("id = \"ok\"\nname = \" \"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"").contains("name"));
}
+1 -94
Переглянути файл
@@ -1,5 +1,4 @@
//! Theme contributions: design-token overrides applied as CSS variables on `:root`.
//! Theme and editor-scheme files are JSON that may contain `//` and `/* */` comments.
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -25,28 +24,13 @@ pub struct ThemeDef {
pub tokens: BTreeMap<String, String>,
}
/// `{"name"?, "tokens": {...}}`: an editor colour scheme merged over a theme.
#[derive(Deserialize)]
struct EditorScheme {
tokens: BTreeMap<String, String>,
}
impl ThemeDef {
pub fn parse(src: &str) -> Result<Self, String> {
let theme: Self =
serde_json::from_str(&strip_json_comments(src)).map_err(|e| format!("invalid theme JSON: {e}"))?;
let theme: Self = serde_json::from_str(src).map_err(|e| format!("invalid theme JSON: {e}"))?;
theme.validate()?;
Ok(theme)
}
/// Merges an editor colour scheme file over the theme's tokens (the scheme wins).
pub fn merge_editor_scheme(&mut self, src: &str) -> Result<(), String> {
let scheme: EditorScheme =
serde_json::from_str(&strip_json_comments(src)).map_err(|e| format!("invalid editor scheme JSON: {e}"))?;
self.tokens.extend(scheme.tokens);
self.validate()
}
pub fn validate(&self) -> Result<(), String> {
crate::manifest::validate_command_id(&self.id).map_err(|e| e.replace("command id", "theme id"))?;
if self.name.trim().is_empty() {
@@ -71,53 +55,6 @@ impl ThemeDef {
}
}
/// Blanks out `//` and `/* */` comments outside strings, keeping newlines so
/// parse errors still point at the right line.
fn strip_json_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let (mut in_str, mut escaped) = (false, false);
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == '"' {
in_str = false;
}
continue;
}
match (c, chars.peek()) {
('/', Some('/')) => {
if chars.by_ref().any(|c| c == '\n') {
out.push('\n');
}
}
('/', Some('*')) => {
chars.next();
let mut prev = ' ';
for c in chars.by_ref() {
if c == '\n' {
out.push('\n');
}
if prev == '*' && c == '/' {
break;
}
prev = c;
}
out.push(' ');
}
_ => {
in_str = c == '"';
out.push(c);
}
}
}
out
}
/// Values are plain CSS values (colours, lengths, font stacks). Anything that
/// could break out of the declaration or fetch resources is rejected.
fn is_safe_value(v: &str) -> bool {
@@ -158,34 +95,4 @@ mod tests {
assert!(mk("--bg", " ").is_err());
assert!(ThemeDef::parse("{\"id\":\"x\"}").is_err());
}
#[test]
fn allows_comments_outside_strings() {
let src = r##"{
// line comment
"id": "c", "name": "C // not a comment", "kind": "dark",
/* block
comment */
"tokens": { "--bg-app": "#000" /* inline */, "--font-ui": "\"a/*b\", sans-serif" }
}"##;
let t = ThemeDef::parse(src).unwrap();
assert_eq!(t.name, "C // not a comment");
assert_eq!(t.tokens["--font-ui"], "\"a/*b\", sans-serif");
assert!(ThemeDef::parse("{\n // x\n \"id\": 1\n}").unwrap_err().contains("line 3"));
}
#[test]
fn merges_editor_scheme_over_theme() {
let mut t = ThemeDef::parse(
r##"{"id":"m","name":"M","kind":"dark","tokens":{"--bg-app":"#111","--syn-keyword":"#222"}}"##,
)
.unwrap();
t.merge_editor_scheme(r##"{"name":"M", /* editor */ "tokens":{"--syn-keyword":"#333","--caret":"#fff"}}"##)
.unwrap();
assert_eq!(t.tokens["--bg-app"], "#111");
assert_eq!(t.tokens["--syn-keyword"], "#333");
assert_eq!(t.tokens["--caret"], "#fff");
assert!(t.clone().merge_editor_scheme(r#"{"tokens":{"--caret":"url(x)"}}"#).is_err());
assert!(t.merge_editor_scheme(r#"{"name":"no tokens"}"#).is_err());
}
}
-36
Переглянути файл
@@ -242,42 +242,6 @@ fn contribution_only_plugins() {
assert_eq!(f.status("language-toy"), PluginStatus::Disabled);
}
#[test]
fn theme_template_installs_with_its_editor_scheme() {
let f = fixture(Limits::default());
let info = f.host.install_from_dir(&repo().join("templates/theme-plugin")).unwrap();
assert_eq!(info.status, PluginStatus::Static);
assert!(!info.has_code);
assert_eq!(info.themes[0].id, "harbor-night");
assert_eq!(info.themes[0].kind, ThemeKind::Dark);
// The scheme file is copied with the package and merged over the UI tokens.
assert!(f.plugins_dir.join("theme-harbor-night/themes/harbor-night.scheme.json").is_file());
let active = f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap().unwrap();
let tokens = &active.theme.tokens;
assert!(
tokens.contains_key("--bg-app") && tokens.contains_key("--syn-keyword") && tokens.contains_key("--ansi-red")
);
assert!(tokens.len() > 150);
}
#[test]
fn theme_with_broken_editor_scheme_fails_to_load() {
let f = fixture(Limits::default());
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("t")).unwrap();
std::fs::write(
dir.path().join("plugin.toml"),
"id = \"bad-scheme\"\nname = \"B\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\n\
[[contributes.themes]]\npath = \"t/a.json\"\neditor-scheme = \"t/a.scheme.json\"\n",
)
.unwrap();
std::fs::write(dir.path().join("t/a.json"), r##"{"id":"a","name":"A","kind":"light","tokens":{}}"##).unwrap();
std::fs::write(dir.path().join("t/a.scheme.json"), "{\n \"tokens\": { \"--caret\": \"url(x)\" }\n}").unwrap();
let info = f.host.install_from_dir(dir.path()).unwrap();
assert_eq!(info.status, PluginStatus::Failed);
assert!(info.error.unwrap_or_default().contains("a.scheme.json"));
}
#[test]
fn state_persists_across_restarts() {
let f = fixture(Limits::default());
+1 -1
Переглянути файл
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
if !data.is_file() {
return Err(nothing_recorded("perf wrote no data"));
}
let out = ide_core::process::no_window(&mut Command::new(perf))
let out = Command::new(perf)
.args(["script", "-i"])
.arg(data.as_ref() as &Path)
.current_dir(cwd)
-2
Переглянути файл
@@ -232,8 +232,6 @@ mod tests {
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
-2
Переглянути файл
@@ -14,10 +14,8 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
tokio.workspace = true
portable-pty.workspace = true
parking_lot.workspace = true
tracing.workspace = true
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+22 -216
Переглянути файл
@@ -11,26 +11,9 @@
//! env = { RUST_LOG = "debug" }
//! is-test = false
//! debug-adapter = "codelldb"
//! allow-parallel = true
//! folder = "Servers"
//! params = { mode = "command" }
//! env-files = [".env"]
//! include-system-env = false
//! stdin-file = "input.txt"
//! output-file = "out/server.log"
//! before-launch = [{ kind = "build" }, { kind = "run", target = "user:migrate" }]
//! emulate-terminal = true
//! stop-command = "docker stop server"
//!
//! [[templates]] # per-type defaults for new configurations
//! kind = "npm"
//! env = { NODE_ENV = "development" }
//! ```
//!
//! Configurations not stored as project files live in the same format in the
//! workspace-local, git-ignored `run.local.toml`.
use crate::{BeforeLaunchTask, RunConfig, RunExtras};
use crate::RunConfig;
use ide_core::{IdeError, IdeResult, project_dir};
use serde::Deserialize;
use std::collections::BTreeMap;
@@ -39,30 +22,16 @@ use std::path::{Path, PathBuf};
use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, Table, value};
const FILE: &str = "run.toml";
const LOCAL_FILE: &str = "run.local.toml";
const CONFIGURATIONS: &str = "configurations";
const TEMPLATES: &str = "templates";
/// Where run configurations are written.
pub(crate) fn config_path(root: &Path) -> PathBuf {
project_dir::path(root, FILE)
}
/// Workspace-local configurations ("Store as project file" off).
pub(crate) fn local_path(root: &Path) -> PathBuf {
project_dir::path(root, LOCAL_FILE)
}
#[derive(Deserialize)]
struct FileDoc {
#[serde(default)]
configurations: Vec<FileConfig>,
#[serde(default)]
templates: Vec<FileConfig>,
}
fn yes() -> bool {
true
}
#[derive(Deserialize)]
@@ -82,35 +51,6 @@ struct FileConfig {
is_test: bool,
#[serde(alias = "debugAdapter", alias = "debug_adapter")]
debug_adapter: Option<String>,
#[serde(default, alias = "allowParallel", alias = "allow_parallel")]
allow_parallel: bool,
#[serde(default)]
params: BTreeMap<String, String>,
folder: Option<String>,
#[serde(default = "yes", alias = "includeSystemEnv")]
include_system_env: bool,
#[serde(default, alias = "envFiles")]
env_files: Vec<String>,
#[serde(alias = "stdinFile")]
stdin_file: Option<String>,
#[serde(alias = "outputFile")]
output_file: Option<String>,
#[serde(default, alias = "beforeLaunch")]
before_launch: Vec<BeforeLaunchTask>,
#[serde(default)]
compound: Vec<String>,
#[serde(default, alias = "showOnStdout")]
show_on_stdout: bool,
#[serde(default, alias = "showOnStderr")]
show_on_stderr: bool,
#[serde(alias = "openToolWindow")]
open_tool_window: Option<bool>,
#[serde(default, alias = "focusToolWindow")]
focus_tool_window: bool,
#[serde(default, alias = "emulateTerminal")]
emulate_terminal: bool,
#[serde(alias = "stopCommand")]
stop_command: Option<String>,
}
fn slug(s: &str) -> String {
@@ -125,22 +65,17 @@ fn slug(s: &str) -> String {
out.trim_matches('-').to_owned()
}
fn read_doc(path: &Path) -> IdeResult<Option<FileDoc>> {
let text = match fs::read_to_string(path) {
pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
let path = config_path(root);
let text = match fs::read_to_string(&path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
toml::from_str(&text).map(Some).map_err(|e| IdeError::invalid(format!("{}: {}", path.display(), e.message())))
}
fn non_empty(s: Option<String>) -> Option<String> {
s.filter(|s| !s.trim().is_empty())
}
fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
let mut out = Vec::with_capacity(configs.len());
for (i, c) in configs.into_iter().enumerate() {
let doc: FileDoc =
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {}", path.display(), e.message())))?;
let mut out = Vec::with_capacity(doc.configurations.len());
for (i, c) in doc.configurations.into_iter().enumerate() {
let name = c.name.filter(|n| !n.is_empty()).unwrap_or_else(|| {
if c.command.is_empty() { format!("Configuration {}", i + 1) } else { c.command.clone() }
});
@@ -156,43 +91,11 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
detected: false,
is_test: c.is_test,
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
allow_parallel: c.allow_parallel,
extras: RunExtras {
params: c.params,
folder: non_empty(c.folder),
local,
include_system_env: c.include_system_env,
env_files: c.env_files.into_iter().filter(|f| !f.trim().is_empty()).collect(),
stdin_file: non_empty(c.stdin_file),
output_file: non_empty(c.output_file),
before_launch: c.before_launch.into_iter().filter(|t| !t.kind.is_empty()).collect(),
compound: c.compound,
show_on_stdout: c.show_on_stdout,
show_on_stderr: c.show_on_stderr,
open_tool_window: c.open_tool_window,
focus_tool_window: c.focus_tool_window,
emulate_terminal: c.emulate_terminal,
stop_command: non_empty(c.stop_command),
},
});
}
out
}
/// Project configurations (`run.toml`) followed by workspace-local ones (`run.local.toml`).
pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
let mut out = read_doc(&config_path(root))?.map(|d| convert(d.configurations, false)).unwrap_or_default();
if let Some(local) = read_doc(&local_path(root))? {
let ids: Vec<String> = out.iter().map(|c| c.id.clone()).collect();
out.extend(convert(local.configurations, true).into_iter().filter(|c| !ids.contains(&c.id)));
}
Ok(out)
}
pub(crate) fn load_templates(root: &Path) -> IdeResult<Vec<RunConfig>> {
Ok(read_doc(&config_path(root))?.map(|d| convert(d.templates, false)).unwrap_or_default())
}
fn to_table(c: &RunConfig) -> Table {
let mut t = Table::new();
t.insert("id", value(&c.id));
@@ -218,69 +121,12 @@ fn to_table(c: &RunConfig) -> Table {
if let Some(adapter) = &c.debug_adapter {
t.insert("debug-adapter", value(adapter));
}
if c.allow_parallel {
t.insert("allow-parallel", value(true));
}
let x = &c.extras;
if let Some(folder) = &x.folder {
t.insert("folder", value(folder));
}
if !x.params.is_empty() {
let mut params = InlineTable::new();
for (k, v) in &x.params {
params.insert(k, v.into());
}
t.insert("params", value(params));
}
if !x.include_system_env {
t.insert("include-system-env", value(false));
}
if !x.env_files.is_empty() {
t.insert("env-files", value(x.env_files.iter().collect::<Array>()));
}
if let Some(f) = &x.stdin_file {
t.insert("stdin-file", value(f));
}
if let Some(f) = &x.output_file {
t.insert("output-file", value(f));
}
if !x.before_launch.is_empty() {
let mut tasks = Array::new();
for task in &x.before_launch {
let mut it = InlineTable::new();
it.insert("kind", task.kind.as_str().into());
if !task.target.is_empty() {
it.insert("target", task.target.as_str().into());
}
tasks.push(it);
}
t.insert("before-launch", value(tasks));
}
if !x.compound.is_empty() {
t.insert("compound", value(x.compound.iter().collect::<Array>()));
}
for (key, on) in [
("show-on-stdout", x.show_on_stdout),
("show-on-stderr", x.show_on_stderr),
("focus-tool-window", x.focus_tool_window),
("emulate-terminal", x.emulate_terminal),
] {
if on {
t.insert(key, value(true));
}
}
if let Some(open) = x.open_tool_window {
t.insert("open-tool-window", value(open));
}
if let Some(stop) = &x.stop_command {
t.insert("stop-command", value(stop));
}
t
}
/// Replaces the `key` array of tables in the file at `path`, keeping unrelated keys and comments.
fn write_array(path: &Path, key: &str, configs: &[&RunConfig]) -> IdeResult<()> {
let existing = match fs::read_to_string(path) {
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
let path = config_path(root);
let existing = match fs::read_to_string(&path) {
Ok(t) => Some(t),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(e.into()),
@@ -288,65 +134,25 @@ fn write_array(path: &Path, key: &str, configs: &[&RunConfig]) -> IdeResult<()>
if existing.is_none() && configs.is_empty() {
return Ok(());
}
// A file we cannot parse is replaced.
// Keep unrelated keys and comments; a file we cannot parse is replaced.
let mut doc = existing.as_deref().and_then(|t| t.parse::<DocumentMut>().ok()).unwrap_or_default();
if configs.is_empty() {
doc.remove(key);
} else {
let mut array = ArrayOfTables::new();
for c in configs {
array.push(to_table(c));
}
doc.insert(key, Item::ArrayOfTables(array));
let mut array = ArrayOfTables::new();
for c in configs {
array.push(to_table(c));
}
let text = doc.to_string();
if existing.as_deref() == Some(text.as_str()) {
return Ok(());
if configs.is_empty() {
doc.remove("configurations");
} else {
doc.insert("configurations", Item::ArrayOfTables(array));
}
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("toml.tmp");
fs::write(&tmp, text)?;
fs::rename(&tmp, path).inspect_err(|_| {
fs::write(&tmp, doc.to_string())?;
fs::rename(&tmp, &path).inspect_err(|_| {
let _ = fs::remove_file(&tmp);
})?;
Ok(())
}
/// Keeps the workspace-local file out of version control (`.openidea/.gitignore`).
fn ignore_local(root: &Path) -> IdeResult<()> {
let entry = format!("/{LOCAL_FILE}");
let file = project_dir::path(root, ".gitignore");
let current = fs::read_to_string(&file).unwrap_or_default();
if current.lines().any(|l| l.trim() == entry) {
return Ok(());
}
let mut text = current;
if text.is_empty() {
text.push_str("# Per-user IDE state\n");
} else if !text.ends_with('\n') {
text.push('\n');
}
text.push_str(&entry);
text.push('\n');
if let Some(dir) = file.parent() {
fs::create_dir_all(dir)?;
}
fs::write(file, text)?;
Ok(())
}
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
let (local, shared): (Vec<&RunConfig>, Vec<&RunConfig>) = configs.iter().partition(|c| c.extras.local);
write_array(&config_path(root), CONFIGURATIONS, &shared)?;
if !local.is_empty() {
ignore_local(root)?;
}
write_array(&local_path(root), CONFIGURATIONS, &local)
}
pub(crate) fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
write_array(&config_path(root), TEMPLATES, &templates.iter().collect::<Vec<_>>())
}
Loaded 100 of 1083 files, more files were not shown because too many files have changed in this diff. Show more