дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
Порівняти коміти
91
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
4548cf05ea | ||
|
|
c199a56c3f | ||
|
|
566b4fdeb1 | ||
|
|
12418e0184 | ||
|
|
7f0fd870e8 | ||
|
|
575749f2ac | ||
|
|
580f0efc28 | ||
|
|
dcdb0e48e4 | ||
|
|
17400ade3d | ||
|
|
b91402ef7d | ||
|
|
56fdc005a8 | ||
|
|
beab7992f9 | ||
|
|
2e0c74e31d | ||
|
|
e16253a890 | ||
|
|
7146779f6c | ||
|
|
cac95273d3 | ||
|
|
55f42d2771 | ||
|
|
30310810e6 | ||
|
|
b2fec4ae30 | ||
|
|
aa5821bb46 | ||
|
|
eda8cae0a1 | ||
|
|
e150101244 | ||
|
|
642b80cef0 | ||
|
|
b4a3e866c6 | ||
|
|
5670c2e8dd | ||
|
|
843127f4a3 | ||
|
|
1127263ea8 | ||
|
|
de84a643aa | ||
|
|
6dfd82de4c | ||
|
|
b79522fd03 | ||
|
|
d7c27c1184 | ||
|
|
6b9a2ec67e | ||
|
|
d3feb056aa | ||
|
|
1e00ea5ee2 | ||
|
|
294198a727 | ||
|
|
82b6980a59 | ||
|
|
81e0e8e2d0 | ||
|
|
87b463990c | ||
|
|
046fd37064 | ||
|
|
cacddee19d | ||
|
|
c8cea62eab | ||
|
|
4a2d5c9599 | ||
|
|
059f25f13e | ||
|
|
a765959d48 | ||
|
|
efbb48c3cb | ||
|
|
bb9486c758 | ||
|
|
5c0c3a009c | ||
|
|
ef667f6e21 | ||
|
|
81b43a52b4 | ||
|
|
0bb730039d | ||
|
|
709e1eb855 | ||
|
|
4473324822 | ||
|
|
5d5b3e4791 | ||
|
|
c5b4b71e30 | ||
|
|
0e299ad936 | ||
|
|
5b8e0b9659 | ||
|
|
3d8a6f07b4 | ||
|
|
99b4f8bdf6 | ||
|
|
86f1f666d7 | ||
|
|
be49490153 | ||
|
|
1f5fcb477d | ||
|
|
1bb454bd2f | ||
|
|
f38f63e397 | ||
|
|
08d87c3903 | ||
|
|
1652866769 | ||
|
|
be5a6f62ad | ||
|
|
f5e8d77dcf | ||
|
|
c3ea376899 | ||
|
|
fde075457b | ||
|
|
135723bca6 | ||
|
|
03a660354c | ||
|
|
1572fc36ea | ||
|
|
4f74f22624 | ||
|
|
1309ce10e4 | ||
|
|
49be259232 | ||
|
|
6a8016b888 | ||
|
|
b8f422d451 | ||
|
|
c868ec8b68 | ||
|
|
059a5193ff | ||
|
|
0f7008391c | ||
|
|
c59f93988b | ||
|
|
76d33f0306 | ||
|
|
cd55bc8f7f | ||
|
|
deec86fab9 | ||
|
|
29e89f2525 | ||
|
|
b1bb4a69cd | ||
|
|
ee99b3641f | ||
|
|
19aee5f262 | ||
|
|
acf6931017 | ||
|
|
555ea8901f | ||
|
|
769c1248d6 |
No files matched your search
Створено
+99
-26
@@ -3960,9 +3960,27 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.15"
|
||||
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.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -3976,7 +3994,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -3989,9 +4007,13 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.15"
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4003,7 +4025,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4017,7 +4039,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4034,7 +4056,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4054,20 +4076,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4081,7 +4104,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4099,7 +4122,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4121,7 +4144,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4136,7 +4159,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4188,7 +4211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4211,7 +4234,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4229,7 +4252,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4242,12 +4265,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4256,16 +4280,19 @@ 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.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"ide-run",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4277,7 +4304,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4285,6 +4312,7 @@ dependencies = [
|
||||
"grep-regex",
|
||||
"grep-searcher",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
"insta",
|
||||
"memchr",
|
||||
@@ -4294,9 +4322,22 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"spellbook",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4324,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4336,7 +4377,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4356,7 +4397,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4373,7 +4414,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4389,11 +4430,28 @@ dependencies = [
|
||||
"tempfile",
|
||||
"tracing",
|
||||
"trash",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4410,6 +4468,7 @@ dependencies = [
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5817,12 +5876,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-agent",
|
||||
"ide-analysis",
|
||||
"ide-build",
|
||||
"ide-clipboard",
|
||||
"ide-core",
|
||||
"ide-coverage",
|
||||
"ide-dap",
|
||||
@@ -5838,12 +5899,14 @@ 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",
|
||||
@@ -7702,6 +7765,16 @@ 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"
|
||||
|
||||
+5
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.3"
|
||||
version = "0.1.15"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -32,6 +32,10 @@ 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"] }
|
||||
|
||||
+9
-1
@@ -9,13 +9,21 @@
|
||||
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>
|
||||
·
|
||||
<a href="#benchmark">Benchmark</a>
|
||||
·
|
||||
<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.
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
## Benchmark
|
||||
|
||||
|
||||
@@ -79,6 +79,15 @@ 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`
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
[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
|
||||
@@ -0,0 +1,224 @@
|
||||
//! 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
@@ -0,0 +1,285 @@
|
||||
//! 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,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! 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", "@zed-industries/[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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
//! 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();
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
let model = ide_build::load(&root, &cache, None);
|
||||
println!("{}", serde_json::to_string_pretty(&model).unwrap());
|
||||
eprintln!("loaded in {:?}", started.elapsed());
|
||||
}
|
||||
@@ -225,6 +225,7 @@ 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();
|
||||
@@ -583,6 +584,7 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -671,7 +673,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"));
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(p.title, "demo");
|
||||
@@ -685,7 +687,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"));
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"), None);
|
||||
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"]);
|
||||
|
||||
@@ -285,6 +285,74 @@ 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);
|
||||
@@ -333,6 +401,38 @@ 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]
|
||||
|
||||
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -36,9 +36,10 @@ pub struct BuildModel {
|
||||
}
|
||||
|
||||
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
|
||||
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
|
||||
/// 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 {
|
||||
let maven = maven::is_maven_project(root).then(|| {
|
||||
let mut m = maven::load(root);
|
||||
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
m
|
||||
});
|
||||
@@ -49,6 +50,56 @@ pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
|
||||
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 };
|
||||
@@ -68,13 +119,52 @@ 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), BuildModel::default());
|
||||
assert_eq!(load(&root, &cache, None), 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);
|
||||
let m = load(&root, &cache, None);
|
||||
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"]);
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,8 @@ 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>,
|
||||
}
|
||||
@@ -410,7 +412,7 @@ struct Resolver {
|
||||
}
|
||||
|
||||
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
|
||||
fn default_local_repo() -> Option<PathBuf> {
|
||||
pub(crate) 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")
|
||||
@@ -924,6 +926,7 @@ 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() {
|
||||
|
||||
@@ -52,12 +52,7 @@ pub(crate) fn run(
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
ide_core::process::no_window(&mut command);
|
||||
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)>| {
|
||||
|
||||
@@ -29,6 +29,10 @@ 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)]
|
||||
@@ -184,6 +188,7 @@ 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());
|
||||
}
|
||||
@@ -194,7 +199,8 @@ 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 out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
let out = run(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) });
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
[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]
|
||||
@@ -0,0 +1,293 @@
|
||||
//! 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(¤t)));
|
||||
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"]));
|
||||
}
|
||||
}
|
||||
@@ -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: true,
|
||||
scroll_past_end: false,
|
||||
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: false, placement: "bottom".into(), disabled_languages: Vec::new() }
|
||||
Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,12 @@ 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,
|
||||
@@ -130,10 +136,13 @@ impl Default for CompletionSettings {
|
||||
case_sensitivity: "first".into(),
|
||||
auto_popup: true,
|
||||
insert_on_special_keys: false,
|
||||
show_documentation: true,
|
||||
auto_insert_single: true,
|
||||
sort_alphabetically: false,
|
||||
insert_parentheses: true,
|
||||
show_documentation: false,
|
||||
documentation_delay: 500,
|
||||
parameter_info: true,
|
||||
parameter_info_delay: 300,
|
||||
parameter_info_delay: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,13 +175,22 @@ impl Default for FoldingSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct EditorTabsSettings {
|
||||
/// `top` | `none`.
|
||||
/// `top` | `bottom` | `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,
|
||||
@@ -187,14 +205,21 @@ 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: 10,
|
||||
closing_policy: "unchanged".into(),
|
||||
activate_on_close: "mru".into(),
|
||||
tab_limit: 30,
|
||||
closing_policy: "lru".into(),
|
||||
activate_on_close: "left".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,7 +239,7 @@ pub struct SmartKeysSettings {
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
pub smart_indent: bool,
|
||||
/// Backspace › Unindent: `nearest` indent position | `none`.
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
}
|
||||
|
||||
@@ -226,10 +251,10 @@ impl Default for SmartKeysSettings {
|
||||
pair_brackets: true,
|
||||
pair_quotes: true,
|
||||
surround_selection: true,
|
||||
tab_out_of_pair: false,
|
||||
reformat_on_paste: "indentBlock".into(),
|
||||
tab_out_of_pair: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
smart_indent: true,
|
||||
backspace_unindent: "nearest".into(),
|
||||
backspace_unindent: "autoindent".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,11 +300,38 @@ 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 }
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,6 +366,12 @@ 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).
|
||||
@@ -329,6 +387,14 @@ 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 {
|
||||
@@ -340,6 +406,11 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ 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,
|
||||
@@ -106,6 +111,9 @@ 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)]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,9 @@ 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;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Child-process helpers shared by every crate that spawns tools.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// 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
|
||||
}
|
||||
@@ -6,6 +6,7 @@ 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)]
|
||||
@@ -37,6 +38,27 @@ 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 {
|
||||
@@ -59,6 +81,9 @@ 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +116,11 @@ 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 {
|
||||
@@ -103,6 +133,8 @@ impl Default for GeneralSettings {
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
date_format: DateFormatSettings::default(),
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,6 +224,20 @@ 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 {
|
||||
@@ -221,6 +267,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_names: true,
|
||||
widescreen_tool_windows: false,
|
||||
status_bar_widgets: BTreeMap::new(),
|
||||
main_toolbar: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,9 +289,18 @@ 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,
|
||||
@@ -255,6 +311,7 @@ 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,
|
||||
@@ -277,8 +334,12 @@ 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(),
|
||||
@@ -289,6 +350,7 @@ 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(),
|
||||
@@ -311,6 +373,22 @@ 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 {
|
||||
@@ -323,6 +401,8 @@ 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,6 +415,7 @@ pub struct LanguagesSettings {
|
||||
pub rust: RustSettings,
|
||||
pub go: GoSettings,
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub java: JavaSettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -397,6 +478,35 @@ 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 {
|
||||
@@ -423,6 +533,17 @@ 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 {
|
||||
@@ -438,10 +559,12 @@ impl Settings {
|
||||
out
|
||||
}
|
||||
|
||||
/// `files.exclude` plus `files.ignoredNames` (a bare name matches at any depth).
|
||||
/// `files.exclude`, `files.ignoredNames` and the Project Structure "Exclude files"
|
||||
/// patterns (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
|
||||
}
|
||||
|
||||
@@ -454,6 +577,16 @@ 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 =
|
||||
@@ -476,4 +609,15 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,11 @@ 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`.
|
||||
@@ -168,6 +173,17 @@ 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 {
|
||||
@@ -179,6 +195,10 @@ 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.
|
||||
|
||||
@@ -24,7 +24,8 @@ pub struct VcsSettings {
|
||||
impl Default for VcsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_dirty_directories: true,
|
||||
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
|
||||
show_dirty_directories: false,
|
||||
limit_history: true,
|
||||
history_limit: 1000,
|
||||
git: GitSettings::default(),
|
||||
@@ -211,6 +212,8 @@ 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,
|
||||
@@ -218,7 +221,7 @@ pub struct RunSettings {
|
||||
|
||||
impl Default for RunSettings {
|
||||
fn default() -> Self {
|
||||
Self { confirm_rerun: true, show_on_start: true, termination_timeout_ms: 3000 }
|
||||
Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +244,8 @@ 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,
|
||||
@@ -249,6 +254,10 @@ 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 {
|
||||
@@ -267,12 +276,15 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
//! "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);
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,12 @@
|
||||
//! 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};
|
||||
@@ -204,7 +206,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 = Command::new(program)
|
||||
let out = ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env)
|
||||
|
||||
@@ -287,6 +287,8 @@ mod tests {
|
||||
detected: true,
|
||||
is_test: true,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ 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>,
|
||||
}
|
||||
|
||||
/// Built-in adapters used when no language definition names `adapter`.
|
||||
@@ -116,6 +118,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
|
||||
install_hint: config.install_hint.clone(),
|
||||
cwd,
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +236,9 @@ 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 probe = Command::new(&python)
|
||||
let mut probe = Command::new(&python);
|
||||
ide_core::process::no_window(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.args(["-c", "import debugpy.adapter"])
|
||||
.current_dir(&spec.cwd)
|
||||
.stdin(Stdio::null())
|
||||
@@ -307,7 +312,12 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
Box::pin(async move {
|
||||
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
|
||||
if let Some(port) = reuse_port {
|
||||
let stream = connect_with_retries(port, None, Duration::from_secs(5)).await?;
|
||||
// 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 (r, w) = stream.into_split();
|
||||
return Ok(AdapterIo {
|
||||
reader: Box::new(r),
|
||||
@@ -335,6 +345,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
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)
|
||||
@@ -363,7 +374,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
if let Some(out) = child.stdout.take() {
|
||||
pump_lines(out, spec.adapter.clone(), stderr.clone());
|
||||
}
|
||||
let stream = match connect_with_retries(port, Some(&mut child), CONNECT_TIMEOUT).await {
|
||||
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), CONNECT_TIMEOUT).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
let _ = child.start_kill();
|
||||
@@ -407,14 +418,17 @@ 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(("127.0.0.1", port)).await {
|
||||
match tokio::net::TcpStream::connect((host, port)).await {
|
||||
Ok(s) => {
|
||||
let _ = s.set_nodelay(true);
|
||||
return Ok(s);
|
||||
@@ -429,7 +443,7 @@ async fn connect_with_retries(
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"could not connect to debug adapter on port {port}: {e}"
|
||||
"could not connect to debug adapter at {host}:{port}: {e}"
|
||||
)));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
|
||||
@@ -55,6 +55,7 @@ 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)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! "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);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
pub mod jdwp;
|
||||
mod session;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -45,7 +46,8 @@ 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.
|
||||
/// instead of starting one, `"debugServer": "host:port"` to one on another machine
|
||||
/// (`dlv --headless`, `debugpy --listen`).
|
||||
pub extra_json: Option<String>,
|
||||
}
|
||||
|
||||
@@ -357,15 +359,34 @@ 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 and returns its port.
|
||||
pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<u16>> {
|
||||
/// 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>> {
|
||||
let Some(v) = arguments.as_object_mut().and_then(|o| o.remove("debugServer")) else { return Ok(None) };
|
||||
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 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 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).
|
||||
@@ -522,6 +543,17 @@ 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
|
||||
@@ -531,6 +563,9 @@ 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") {
|
||||
@@ -544,6 +579,9 @@ 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")
|
||||
@@ -585,8 +623,8 @@ impl DebugManager {
|
||||
if config.adapter == "codelldb" && arguments.get("sourceLanguages").is_none() {
|
||||
arguments["sourceLanguages"] = json!(["rust"]);
|
||||
}
|
||||
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, debug_server)
|
||||
.await
|
||||
let port = debug_server.map(|s| s.port);
|
||||
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
|
||||
}
|
||||
|
||||
/// `startDebugging` reverse request: a child session on the same adapter.
|
||||
|
||||
@@ -390,6 +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).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);
|
||||
|
||||
@@ -597,14 +597,23 @@ 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(), Some(4711));
|
||||
assert_eq!(take_debug_server(&mut args).unwrap(), local(4711));
|
||||
assert!(args.get("debugServer").is_none());
|
||||
assert_eq!(args["mainClass"], "a.B");
|
||||
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), Some(5005));
|
||||
assert_eq!(take_debug_server(&mut json!({"debugServer": "5005"})).unwrap(), local(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]
|
||||
@@ -696,6 +705,41 @@ 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()
|
||||
|
||||
@@ -15,7 +15,8 @@ use sqlx::{
|
||||
postgres::{PgConnectOptions, PgPool, PgPoolOptions, PgSslMode},
|
||||
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions},
|
||||
};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -39,6 +40,8 @@ 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 {
|
||||
@@ -129,7 +132,9 @@ 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)) => {
|
||||
@@ -151,12 +156,13 @@ macro_rules! fetch {
|
||||
drop(stream);
|
||||
match failure {
|
||||
Some(e) => Err(e),
|
||||
None => Ok((columns, rows, affected, has_more)),
|
||||
None => Ok((columns, rows, affected, has_more, first)),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool);
|
||||
/// 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>);
|
||||
|
||||
/// The server-side id of a connection (to cancel its statement from another one).
|
||||
macro_rules! backend_id {
|
||||
@@ -184,6 +190,90 @@ 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 {
|
||||
@@ -196,7 +286,24 @@ 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 timeout = Duration::from_secs(30);
|
||||
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(())
|
||||
})
|
||||
}
|
||||
}};
|
||||
}
|
||||
match source.driver {
|
||||
DbDriver::Sqlite => {
|
||||
let file = source.file.as_deref().ok_or_else(|| IdeError::invalid("no database file"))?;
|
||||
@@ -204,11 +311,18 @@ impl Pool {
|
||||
Some(r) if file.is_relative() => r.join(file),
|
||||
_ => file.to_path_buf(),
|
||||
};
|
||||
let opts =
|
||||
let mut 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)?;
|
||||
@@ -219,24 +333,39 @@ impl Pool {
|
||||
.host(&source.host)
|
||||
.port(source.port.unwrap_or(5432))
|
||||
.username(&source.user)
|
||||
.application_name("OpenIDEA")
|
||||
.application_name(setup.application_name.as_deref().unwrap_or("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 source.read_only {
|
||||
opts = opts.options([("default_transaction_read_only", "on")]);
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
@@ -251,25 +380,41 @@ 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);
|
||||
}
|
||||
let read_only = source.read_only;
|
||||
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 pool = MySqlPoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(move |conn, _| {
|
||||
Box::pin(async move {
|
||||
if read_only {
|
||||
conn.execute("SET SESSION TRANSACTION READ ONLY").await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
@@ -282,6 +427,10 @@ 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));
|
||||
@@ -408,14 +557,16 @@ impl Held {
|
||||
}
|
||||
Held::Mysql(c) => run!(c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
};
|
||||
let (columns, rows, affected, has_more) = fetched;
|
||||
let (columns, rows, affected, has_more, first) = fetched;
|
||||
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
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: started.elapsed().as_secs_f64() * 1000.0,
|
||||
elapsed_ms,
|
||||
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -434,3 +585,68 @@ 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())]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
+256
-18
@@ -3,6 +3,8 @@
|
||||
//! 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;
|
||||
@@ -10,9 +12,14 @@ pub mod sql;
|
||||
pub mod tunnel;
|
||||
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn};
|
||||
pub use source::{DataSource, DbDriver, DbSsh, DbSshAuth, DbSslMode};
|
||||
pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
use history::HistoryStore;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
use secrets::SecretStore;
|
||||
@@ -21,6 +28,7 @@ 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)]
|
||||
@@ -28,6 +36,67 @@ 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)]
|
||||
@@ -65,6 +134,7 @@ 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)]
|
||||
@@ -145,6 +215,7 @@ 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
|
||||
@@ -219,6 +290,24 @@ 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();
|
||||
@@ -230,21 +319,24 @@ async fn end_session(session: &Session) {
|
||||
}
|
||||
|
||||
impl DbManager {
|
||||
/// `passwords` is the app-wide file of saved passwords ([`SecretStore`]).
|
||||
pub fn new(root: PathBuf, passwords: PathBuf) -> Self {
|
||||
/// `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 {
|
||||
let ssh_dir = dirs::home_dir().unwrap_or_default().join(".ssh");
|
||||
Self::with_ssh_files(root, passwords, ssh_dir.join("known_hosts"), Some(ssh_dir.join("config")))
|
||||
Self::with_ssh_files(root, passwords, history, 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(),
|
||||
@@ -261,14 +353,16 @@ impl DbManager {
|
||||
source::load(&self.root)
|
||||
}
|
||||
|
||||
/// The data source of connection target `target`, with its database for `<id>:<database>`.
|
||||
/// The connection settings of target `target` ([`DataSource::resolved`]), 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}")))?;
|
||||
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
|
||||
.resolved()?;
|
||||
if let Some(db) = database {
|
||||
source.database = db.to_owned();
|
||||
}
|
||||
@@ -341,7 +435,10 @@ impl DbManager {
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await
|
||||
match self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
|
||||
Some(p) => Some(p),
|
||||
None => source.url_password(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Trusts the host key that failed the last connection of `id` (adds it to `known_hosts`).
|
||||
@@ -411,6 +508,7 @@ 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,
|
||||
@@ -458,9 +556,14 @@ 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.
|
||||
Ok(pools.entry(id.to_owned()).or_insert(pool).clone())
|
||||
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)
|
||||
}
|
||||
|
||||
/// Closes the tunnel of `source_id` once none of its targets is connected.
|
||||
@@ -496,24 +599,30 @@ 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 pool = self.pool(split_target(id).0).await?;
|
||||
let id = split_target(id).0;
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let system = introspection.show_system;
|
||||
let pool = self.pool(id).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, MAX_META_ROWS).await?;
|
||||
let rows = pool.rows(sql::databases(introspection.show_templates), MAX_META_ROWS).await?;
|
||||
let mut names: Vec<String> =
|
||||
first(rows).filter(|n| *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
|
||||
first(rows).filter(|n| system || *n == current || !sql::INTERNAL_DATABASES.contains(&n.as_str())).collect();
|
||||
if !names.contains(¤t) {
|
||||
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()), MAX_META_ROWS).await?;
|
||||
let rows = pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?;
|
||||
Ok(rows.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect())
|
||||
}
|
||||
|
||||
@@ -525,9 +634,7 @@ impl DbManager {
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
let kind =
|
||||
if it.next().flatten().as_deref() == Some("view") { DbTableKind::View } else { DbTableKind::Table };
|
||||
Some(TableInfo { name, kind })
|
||||
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -575,7 +682,85 @@ impl DbManager {
|
||||
.collect();
|
||||
}
|
||||
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
|
||||
Ok(TableDetails { columns, indexes, foreign_keys })
|
||||
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"))
|
||||
}
|
||||
|
||||
/// The DDL of table or view `name`: SQLite's stored statements, MySQL's
|
||||
@@ -671,7 +856,7 @@ impl DbManager {
|
||||
_ => tables.push(CompletionTable {
|
||||
schema,
|
||||
name,
|
||||
kind: if kind == "view" { DbTableKind::View } else { DbTableKind::Table },
|
||||
kind: DbTableKind::from_catalog(Some(&kind)),
|
||||
columns: vec![column],
|
||||
}),
|
||||
}
|
||||
@@ -695,12 +880,65 @@ 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();
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! 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"));
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,91 @@ 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").
|
||||
@@ -84,6 +169,20 @@ 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 {
|
||||
@@ -101,10 +200,188 @@ 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")]
|
||||
@@ -164,4 +441,77 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,26 @@ pub fn qualified(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Databases one can connect to (PostgreSQL).
|
||||
pub const DATABASES: &str = "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname";
|
||||
/// 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 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) -> &'static str {
|
||||
pub fn schemas(driver: DbDriver, system: bool) -> &'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') \
|
||||
@@ -53,7 +64,7 @@ pub fn schemas(driver: DbDriver) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `name, kind` where kind is `table` or `view`.
|
||||
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
|
||||
pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -61,7 +72,13 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
|
||||
quote_ident(driver, schema)
|
||||
),
|
||||
_ => format!(
|
||||
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!(
|
||||
"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)
|
||||
@@ -134,7 +151,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 WHEN c.relkind IN ('v', 'm') THEN 'view' ELSE 'table' END, a.attname, \
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized 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, \
|
||||
@@ -363,6 +380,123 @@ 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,
|
||||
@@ -452,6 +586,31 @@ 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 = [
|
||||
|
||||
@@ -200,7 +200,7 @@ fn home() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// `~/x` → `$HOME/x`.
|
||||
fn expand(path: &str) -> PathBuf {
|
||||
pub(crate) fn expand(path: &str) -> PathBuf {
|
||||
match (path.strip_prefix("~/"), home()) {
|
||||
(Some(rest), Some(h)) => h.join(rest),
|
||||
_ => PathBuf::from(path),
|
||||
|
||||
@@ -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, DbRowEdit, DbTableKind, SortKey};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, 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"));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"));
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s1".into(),
|
||||
name: "app".into(),
|
||||
@@ -246,3 +246,74 @@ 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(())
|
||||
}
|
||||
@@ -15,3 +15,6 @@ which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,402 @@
|
||||
//! 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, ®istry.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());
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
//!
|
||||
//! 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};
|
||||
@@ -61,21 +63,38 @@ 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(¤t).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(args: &[&str]) -> IdeResult<Command> {
|
||||
fn command(ep: &DockerEndpoint, 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(args: &[&str], timeout: Duration) -> IdeResult<String> {
|
||||
let out = process::run(command(args)?, timeout, None)?;
|
||||
fn run(ep: &DockerEndpoint, args: &[&str], timeout: Duration) -> IdeResult<String> {
|
||||
let out = process::run(command(ep, args)?, timeout, None)?;
|
||||
if out.success { Ok(out.stdout) } else { Err(failure(args, &out.stderr, &out.stdout)) }
|
||||
}
|
||||
|
||||
@@ -94,8 +113,8 @@ fn failure(args: &[&str], stderr: &str, stdout: &str) -> IdeError {
|
||||
}
|
||||
|
||||
/// Whether docker can be used right now.
|
||||
pub fn availability() -> DockerAvailability {
|
||||
let Ok(cmd) = command(&["version", "--format", "{{json .}}"]) else {
|
||||
pub fn availability(ep: &DockerEndpoint) -> DockerAvailability {
|
||||
let Ok(cmd) = command(ep, &["version", "--format", "{{json .}}"]) else {
|
||||
return DockerAvailability::NotInstalled;
|
||||
};
|
||||
match process::run(cmd, Duration::from_secs(15), None) {
|
||||
@@ -105,8 +124,8 @@ pub fn availability() -> DockerAvailability {
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks (listed in parallel).
|
||||
pub fn snapshot() -> DockerSnapshot {
|
||||
let availability = availability();
|
||||
pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
let availability = availability(ep);
|
||||
let executable = docker_executable().map(|p| ide_core::ipc_path::to_ipc(&p));
|
||||
let mut snap = DockerSnapshot {
|
||||
availability,
|
||||
@@ -116,16 +135,17 @@ pub fn snapshot() -> 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(&["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 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 join = |h: std::thread::ScopedJoinHandle<'_, IdeResult<String>>| {
|
||||
h.join().unwrap_or_else(|_| Err(IdeError::internal("docker listing panicked")))
|
||||
};
|
||||
@@ -178,13 +198,13 @@ impl ContainerOp {
|
||||
}
|
||||
|
||||
/// Starts / stops / … the containers `ids`.
|
||||
pub fn container_op(ids: &[String], op: ContainerOp) -> IdeResult<()> {
|
||||
pub fn container_op(ep: &DockerEndpoint, 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(&args, LIFECYCLE).map(drop)
|
||||
run(ep, &args, LIFECYCLE).map(drop)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -208,7 +228,7 @@ impl DockerObject {
|
||||
}
|
||||
|
||||
/// `docker <object> rm` (`force`: stop running containers / untag used images first).
|
||||
pub fn remove(object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
|
||||
pub fn remove(ep: &DockerEndpoint, object: DockerObject, ids: &[String], force: bool) -> IdeResult<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -217,12 +237,12 @@ pub fn remove(object: DockerObject, ids: &[String], force: bool) -> IdeResult<()
|
||||
args.push("--force");
|
||||
}
|
||||
args.extend(ids.iter().map(String::as_str));
|
||||
run(&args, LIFECYCLE).map(drop)
|
||||
run(ep, &args, LIFECYCLE).map(drop)
|
||||
}
|
||||
|
||||
/// `docker inspect` of one object, pretty-printed.
|
||||
pub fn inspect(object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
let out = run(&["inspect", "--type", object.noun(), id], QUICK)?;
|
||||
pub fn inspect(ep: &DockerEndpoint, object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
let out = run(ep, &["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 => {
|
||||
@@ -236,6 +256,7 @@ pub fn inspect(object: DockerObject, id: &str) -> IdeResult<String> {
|
||||
/// 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,
|
||||
@@ -252,16 +273,16 @@ pub fn logs(
|
||||
args.push("--timestamps");
|
||||
}
|
||||
args.push(id);
|
||||
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, text| {
|
||||
let (ok, stderr) = process::stream(command(ep, &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(cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
|
||||
pub fn watch_events(ep: &DockerEndpoint, cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent)) -> IdeResult<()> {
|
||||
let args = ["events", "--format", "{{json .}}"];
|
||||
let (ok, stderr) = process::stream(command(&args)?, cancel, &mut |stream, line| {
|
||||
let (ok, stderr) = process::stream(command(ep, &args)?, cancel, &mut |stream, line| {
|
||||
if stream == Stream::Stdout
|
||||
&& let Some(e) = parse_event(&line)
|
||||
{
|
||||
@@ -272,9 +293,19 @@ pub fn watch_events(cancel: &CancellationToken, on_event: &dyn Fn(DockerEvent))
|
||||
}
|
||||
|
||||
/// Runs a long docker command (pull, prune, compose…), streaming its output lines.
|
||||
fn run_streaming(args: &[&str], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
fn run_streaming(
|
||||
ep: &DockerEndpoint,
|
||||
config: Option<&Path>,
|
||||
args: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
on_output(format!("docker {}", args.join(" ")));
|
||||
let (ok, stderr) = process::stream(command(args)?, cancel, &mut |_, line| {
|
||||
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| {
|
||||
if !line.trim().is_empty() {
|
||||
on_output(line);
|
||||
}
|
||||
@@ -282,13 +313,57 @@ fn run_streaming(args: &[&str], cancel: &CancellationToken, on_output: &dyn Fn(S
|
||||
if ok { Ok(()) } else { Err(failure(args, &stderr.join("\n"), "")) }
|
||||
}
|
||||
|
||||
/// `docker pull <reference>`.
|
||||
pub fn pull(reference: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
/// `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<()> {
|
||||
let reference = reference.trim();
|
||||
if reference.is_empty() || reference.starts_with('-') {
|
||||
return Err(IdeError::invalid("enter an image name, e.g. postgres:16"));
|
||||
}
|
||||
run_streaming(&["pull", reference], cancel, on_output)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -306,7 +381,12 @@ pub enum PruneTarget {
|
||||
}
|
||||
|
||||
/// `docker <object> prune --force`.
|
||||
pub fn prune(target: PruneTarget, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
pub fn prune(
|
||||
ep: &DockerEndpoint,
|
||||
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"],
|
||||
@@ -315,7 +395,7 @@ pub fn prune(target: PruneTarget, cancel: &CancellationToken, on_output: &dyn Fn
|
||||
PruneTarget::Networks => &["network", "prune", "--force"],
|
||||
PruneTarget::System => &["system", "prune", "--force"],
|
||||
};
|
||||
run_streaming(args, cancel, on_output)
|
||||
run_streaming(ep, None, args, cancel, on_output)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -332,6 +412,7 @@ 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>,
|
||||
@@ -357,5 +438,5 @@ pub fn compose_op(
|
||||
ComposeOp::Restart => "restart",
|
||||
ComposeOp::Down => "down",
|
||||
});
|
||||
run_streaming(&args, cancel, on_output)
|
||||
run_streaming(ep, None, &args, cancel, on_output)
|
||||
}
|
||||
@@ -105,6 +105,9 @@ 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.
|
||||
|
||||
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
@@ -64,9 +60,26 @@ 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(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
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> {
|
||||
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;
|
||||
|
||||
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
|
||||
@@ -181,10 +181,10 @@ impl IndexData {
|
||||
Some(old)
|
||||
}
|
||||
|
||||
/// Removes every file at or below `dir`; returns their relative paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<String> {
|
||||
/// Removes every file at or below `dir`; returns their paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
|
||||
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
|
||||
doomed.iter().filter_map(|p| self.remove(p)).map(|e| e.rel.into_string()).collect()
|
||||
doomed.into_iter().filter(|p| self.remove(p).is_some()).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!["a/b.rs".to_owned()]);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
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", ""));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Which paths belong in the index: `.gitignore`/`.ignore` rules (via the
|
||||
//! `ignore` crate) plus the user's `files.exclude` globs.
|
||||
//! `ignore` crate) plus the user's `files.exclude` globs, below the project root
|
||||
//! and the extra content roots (Project Structure).
|
||||
|
||||
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
|
||||
use ignore::gitignore::{Gitignore, GitignoreBuilder};
|
||||
@@ -14,10 +15,45 @@ 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)]
|
||||
@@ -32,9 +68,9 @@ pub(crate) fn mtime_of(meta: &std::fs::Metadata) -> u64 {
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
pub(crate) fn new(root: &Path, excludes: &[String]) -> Self {
|
||||
pub(crate) fn new(root: &Path, extra_roots: &[PathBuf], exclude_globs: &[String]) -> Self {
|
||||
let mut set = GlobSetBuilder::new();
|
||||
for raw in excludes {
|
||||
for raw in exclude_globs {
|
||||
let p = raw.trim().trim_end_matches('/');
|
||||
let anchored = p.starts_with('/');
|
||||
let p = p.trim_start_matches("./").trim_start_matches('/');
|
||||
@@ -55,34 +91,76 @@ impl PathFilter {
|
||||
}
|
||||
}
|
||||
let excludes = set.build().unwrap_or_else(|_| GlobSet::empty());
|
||||
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 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 name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
extra.push(ExtraRoot { gitignore: root_ignores(&path), name, path });
|
||||
}
|
||||
let gitignore = gi.build().unwrap_or_else(|_| Gitignore::empty());
|
||||
Self { root: root.to_owned(), excludes, gitignore }
|
||||
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
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// `/`-separated path relative to the root.
|
||||
pub(crate) fn rel(&self, path: &Path) -> Option<String> {
|
||||
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());
|
||||
/// 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));
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
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.
|
||||
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;
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
@@ -96,7 +174,11 @@ 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(rel) = self.rel(path) else { return true };
|
||||
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 mut prefix = String::new();
|
||||
for seg in rel.split('/') {
|
||||
if Self::skip_name(seg) {
|
||||
@@ -110,14 +192,15 @@ impl PathFilter {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.gitignore.matched_path_or_any_parents(path, is_dir).is_ignore()
|
||||
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 root = self.root.clone();
|
||||
let Some((root, _, _)) = self.base_of(dir) else { return Vec::new() };
|
||||
let root = root.to_path_buf();
|
||||
let excludes = self.excludes.clone();
|
||||
let walker = WalkBuilder::new(dir)
|
||||
.hidden(false)
|
||||
@@ -207,7 +290,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();
|
||||
@@ -220,4 +303,31 @@ 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()]));
|
||||
}
|
||||
}
|
||||
@@ -67,14 +67,17 @@ 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>,
|
||||
@@ -85,7 +88,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, &excludes);
|
||||
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
|
||||
let worker = {
|
||||
let shared = shared.clone();
|
||||
@@ -94,7 +97,25 @@ 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)) }))
|
||||
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));
|
||||
}
|
||||
|
||||
pub fn status(&self) -> IndexStatus {
|
||||
@@ -121,6 +142,11 @@ 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]) {
|
||||
@@ -154,6 +180,26 @@ 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()
|
||||
@@ -177,14 +223,15 @@ impl ProjectIndex {
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
self.shared.filter.root()
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Absolute path inside the root, or `None` for paths outside the project / excluded.
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let root = self.shared.filter.root();
|
||||
let filter = self.shared.filter();
|
||||
let root = &self.root;
|
||||
let path = if path.is_absolute() { path.to_owned() } else { root.join(path) };
|
||||
let path = if path.starts_with(root) {
|
||||
let path = if filter.contains(&path) {
|
||||
path
|
||||
} else {
|
||||
// Watchers / the UI may report non-canonical spellings (`/tmp` vs `/private/tmp`).
|
||||
@@ -196,7 +243,7 @@ impl ProjectIndex {
|
||||
}
|
||||
}
|
||||
};
|
||||
(path.starts_with(root) && path != root).then_some(path)
|
||||
(filter.contains(&path) && filter.rel(&path).is_some()).then_some(path)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
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;
|
||||
@@ -419,6 +420,33 @@ 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::*;
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Fixture {
|
||||
let idx = ProjectIndex::open(
|
||||
&self.root,
|
||||
&self.cache,
|
||||
Vec::new(),
|
||||
vec!["**/node_modules".into(), "**/target".into()],
|
||||
languages,
|
||||
syntax,
|
||||
@@ -192,7 +193,11 @@ 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();
|
||||
@@ -381,3 +386,90 @@ 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");
|
||||
}
|
||||
@@ -24,6 +24,11 @@ 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)]
|
||||
@@ -34,7 +39,7 @@ struct Queue {
|
||||
}
|
||||
|
||||
pub(crate) struct Shared {
|
||||
pub filter: PathFilter,
|
||||
filter: RwLock<std::sync::Arc<PathFilter>>,
|
||||
pub languages: std::sync::Arc<LanguageRegistry>,
|
||||
pub syntax: std::sync::Arc<Syntax>,
|
||||
pub sink: SharedSink,
|
||||
@@ -60,7 +65,7 @@ impl Shared {
|
||||
store: Option<Store>,
|
||||
) -> Self {
|
||||
Self {
|
||||
filter,
|
||||
filter: RwLock::new(std::sync::Arc::new(filter)),
|
||||
languages,
|
||||
syntax,
|
||||
sink,
|
||||
@@ -76,6 +81,14 @@ 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();
|
||||
@@ -150,7 +163,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> =
|
||||
@@ -198,26 +211,31 @@ impl Shared {
|
||||
done: false,
|
||||
});
|
||||
|
||||
let found = self.filter.walk(self.filter.root(), &self.cancelled);
|
||||
let filter = self.filter();
|
||||
let mut found = Vec::new();
|
||||
for root in filter.roots() {
|
||||
found.extend(filter.walk(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<String>) = {
|
||||
let (todo, stale): (Vec<&Found>, Vec<PathBuf>) = {
|
||||
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())).filter_map(|p| self.filter.rel(p)).collect();
|
||||
let stale = d.paths().filter(|p| !seen.contains(p.as_path())).cloned().collect();
|
||||
(todo, stale)
|
||||
};
|
||||
if !stale.is_empty() {
|
||||
let mut d = self.data.write();
|
||||
for rel in &stale {
|
||||
d.remove(&self.filter.root().join(rel));
|
||||
for path in &stale {
|
||||
d.remove(path);
|
||||
}
|
||||
}
|
||||
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
@@ -227,7 +245,7 @@ impl Shared {
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
}
|
||||
self.index_files(chunk.iter().copied());
|
||||
self.index_files(chunk.iter().copied(), false);
|
||||
done += chunk.len();
|
||||
if last_progress.elapsed() >= PROGRESS_EVERY {
|
||||
last_progress = Instant::now();
|
||||
@@ -261,16 +279,18 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// Extracts records in parallel, then publishes them to memory and disk.
|
||||
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>) {
|
||||
/// `force` re-parses files whose content is unchanged (their language changed).
|
||||
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>, force: bool) {
|
||||
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 = self.filter.rel(&f.path)?;
|
||||
let prev_hash = self.data.read().get(&f.path).map(|e| e.hash);
|
||||
let rel = filter.rel(&f.path)?;
|
||||
let prev_hash = if force { None } else { 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.
|
||||
@@ -288,7 +308,7 @@ impl Shared {
|
||||
return;
|
||||
}
|
||||
let puts: Vec<(String, FileRecord)> =
|
||||
extracted.iter().map(|(rel, rec, _)| (rel.clone(), rec.clone())).collect();
|
||||
extracted.iter().filter_map(|(_, rec, path)| Some((filter.store_key(path)?, rec.clone()))).collect();
|
||||
{
|
||||
let entries: Vec<FileEntry> =
|
||||
extracted.into_iter().map(|(rel, rec, path)| FileEntry::new(path, rel, rec)).collect();
|
||||
@@ -346,13 +366,24 @@ 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.
|
||||
@@ -363,11 +394,11 @@ impl Shared {
|
||||
continue;
|
||||
}
|
||||
let mut d = self.data.write();
|
||||
if let Some(e) = d.remove(&path) {
|
||||
deletes.push(e.rel.into_string());
|
||||
} else {
|
||||
deletes.extend(d.remove_tree(&path));
|
||||
}
|
||||
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 !deletes.is_empty() {
|
||||
touched = true;
|
||||
@@ -381,11 +412,11 @@ impl Shared {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
|
||||
if self.filter.is_excluded(&path, meta.is_dir()) {
|
||||
if filter.is_excluded(&path, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
files.extend(self.filter.walk(&path, &self.cancelled));
|
||||
files.extend(filter.walk(&path, &self.cancelled));
|
||||
} else if meta.is_file() {
|
||||
files.push(Found { mtime: mtime_of(&meta), size: meta.len(), path });
|
||||
}
|
||||
@@ -403,11 +434,32 @@ impl Shared {
|
||||
if self.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
self.index_files(chunk.iter());
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| self.filter.rel(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Transport shared by the LSP and DAP clients.
|
||||
//!
|
||||
//! * [`framing`]: `Content-Length` header framing over any async byte stream
|
||||
//! (used by both protocols).
|
||||
//! (used by both protocols), and newline-delimited JSON ([`Framing::Lines`],
|
||||
//! the Agent Client Protocol).
|
||||
//! * [`Peer`]: a JSON-RPC 2.0 endpoint with request/response correlation,
|
||||
//! cancellation (`$/cancelRequest`) and handlers for server→client traffic.
|
||||
|
||||
@@ -88,6 +89,34 @@ 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;
|
||||
@@ -210,6 +239,32 @@ 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 {
|
||||
@@ -238,9 +293,23 @@ 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(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
@@ -254,7 +323,7 @@ impl Peer {
|
||||
let stderr = child.stderr.take();
|
||||
let pid = child.id();
|
||||
|
||||
let peer = Self::start(stdout, stdin, handler, false, pid);
|
||||
let peer = Self::start(stdout, stdin, handler, false, pid, framing);
|
||||
|
||||
if let Some(stderr) = stderr {
|
||||
let name = command.to_owned();
|
||||
@@ -298,10 +367,26 @@ impl Peer {
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
Self::start(reader, writer, handler, true, None)
|
||||
Self::start(reader, writer, handler, true, None, Framing::ContentLength)
|
||||
}
|
||||
|
||||
fn start<R, W>(reader: R, mut writer: W, handler: Arc<dyn Handler>, close_on_eof: bool, pid: Option<u32>) -> Self
|
||||
/// [`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)
|
||||
}
|
||||
|
||||
fn start<R, W>(
|
||||
reader: R,
|
||||
mut writer: W,
|
||||
handler: Arc<dyn Handler>,
|
||||
close_on_eof: bool,
|
||||
pid: Option<u32>,
|
||||
framing: Framing,
|
||||
) -> Self
|
||||
where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
@@ -329,7 +414,7 @@ impl Peer {
|
||||
_ = kill.cancelled() => None,
|
||||
};
|
||||
let Some(body) = body else { break };
|
||||
if let Err(e) = framing::write_message(&mut writer, &body).await {
|
||||
if let Err(e) = framing.write(&mut writer, &body).await {
|
||||
tracing::debug!("jsonrpc write failed: {e}");
|
||||
if let Some(inner) = weak.upgrade() {
|
||||
inner.close_transport();
|
||||
@@ -368,7 +453,7 @@ impl Peer {
|
||||
let mut reader = BufReader::new(reader);
|
||||
loop {
|
||||
let msg = tokio::select! {
|
||||
msg = framing::read_message(&mut reader) => msg,
|
||||
msg = framing.read(&mut reader) => msg,
|
||||
_ = inner.kill.cancelled() => break,
|
||||
};
|
||||
match msg {
|
||||
|
||||
@@ -120,6 +120,28 @@ 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());
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
; 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
|
||||
@@ -0,0 +1,29 @@
|
||||
; 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
|
||||
@@ -11,8 +11,12 @@ use std::collections::BTreeMap;
|
||||
|
||||
mod registry;
|
||||
mod syntax;
|
||||
pub use registry::LanguageRegistry;
|
||||
pub use syntax::{MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, TreeError};
|
||||
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,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -115,6 +119,18 @@ 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 {
|
||||
@@ -128,6 +144,9 @@ 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::LanguageConfig;
|
||||
use ide_core::settings::{FileSettings, FileTypeAssociation};
|
||||
use ide_core::{IdeError, IdeResult, LanguageId};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use parking_lot::RwLock;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Built-in definitions, embedded at compile time. Add new languages here.
|
||||
const BUILTIN: &[(&str, &str)] = &[
|
||||
@@ -78,11 +81,130 @@ 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 containing `*`, e.g. `Dockerfile.*`, `tsconfig.*.json`.
|
||||
/// File-name patterns with wildcards, e.g. `Dockerfile.*`, `tsconfig.*.json`; the user's first.
|
||||
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 {
|
||||
@@ -116,31 +238,31 @@ impl LanguageRegistry {
|
||||
None => languages.push(cfg),
|
||||
}
|
||||
}
|
||||
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),
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
// 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 }
|
||||
*self.tables.write() = Arc::new(Tables::build(&self.languages, &file_types));
|
||||
*current = file_types;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn all(&self) -> Vec<LanguageConfig> {
|
||||
@@ -151,48 +273,67 @@ impl LanguageRegistry {
|
||||
self.languages.iter().find(|l| &l.id == id).cloned()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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'.
|
||||
pub fn detect(&self, path: &Path, first_line: Option<&str>) -> LanguageId {
|
||||
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
if let Some(&i) = self.by_name.get(file_name) {
|
||||
let t = self.tables.read().clone();
|
||||
if !t.overrides.is_empty()
|
||||
&& let Some(&i) = t.overrides.get(path)
|
||||
{
|
||||
return self.languages[i].id.clone();
|
||||
}
|
||||
if let Some((_, i)) = self.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
|
||||
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) {
|
||||
return self.languages[i].id.clone();
|
||||
}
|
||||
if let Some((_, i)) = t.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) = self.by_ext.get(rest) {
|
||||
if let Some(&i) = t.by_ext.get(rest) {
|
||||
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();
|
||||
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();
|
||||
}
|
||||
}
|
||||
LanguageId::plain_text()
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any (possibly empty) run of characters; everything else is literal.
|
||||
/// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal.
|
||||
fn wildcard_match(pattern: &str, name: &str) -> bool {
|
||||
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,
|
||||
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;
|
||||
}
|
||||
}
|
||||
rest.len() >= last.len() && rest.ends_with(last)
|
||||
p[pi..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
fn parse(src: &str) -> Result<LanguageConfig, String> {
|
||||
@@ -573,6 +714,60 @@ 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(®, "a/x.foo"), "python");
|
||||
assert_eq!(detect(®, "x.FOO"), "python");
|
||||
assert_eq!(detect(®, "Pipfile.lock"), "python");
|
||||
assert_eq!(detect(®, "build_dev.cfg"), "python");
|
||||
assert_eq!(detect(®, "setup.cfg"), "ini");
|
||||
assert_eq!(detect(®, "server.log"), "python", "a user extension overrides a built-in one");
|
||||
assert_eq!(detect(®, "Jenkinsfile"), "shellscript");
|
||||
assert_eq!(detect(®, "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(®, "main.rs"), "rust");
|
||||
assert_eq!(detect(®, "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(®, "/proj/notes.txt"), "markdown");
|
||||
assert_eq!(detect(®, "/other/notes.txt"), "plaintext");
|
||||
assert_eq!(detect(®, "/abs/run"), "python");
|
||||
assert_eq!(detect(®, "/proj/bad.txt"), "plaintext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
//! 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, TreeError, folding, outline, parse_cancellable, selection};
|
||||
use super::{
|
||||
Grammar, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxHighlights, TreeError, folding, highlight, outline,
|
||||
parse_cancellable, selection,
|
||||
};
|
||||
use crate::FoldRange;
|
||||
use ide_core::{DocId, LanguageId, OutlineItem, Range};
|
||||
use ide_text::ByteEdit;
|
||||
@@ -59,6 +62,7 @@ struct Memo {
|
||||
key: Option<(u32, LanguageId)>,
|
||||
outline: Option<Arc<Vec<OutlineItem>>>,
|
||||
folding: Option<Arc<Vec<FoldRange>>>,
|
||||
highlights: Option<Arc<Vec<u32>>>,
|
||||
}
|
||||
|
||||
impl Memo {
|
||||
@@ -211,6 +215,21 @@ 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,
|
||||
|
||||
@@ -9,6 +9,8 @@ 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],
|
||||
@@ -20,6 +22,21 @@ 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"))
|
||||
@@ -33,6 +50,7 @@ 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"],
|
||||
@@ -42,6 +60,7 @@ 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"],
|
||||
@@ -51,6 +70,7 @@ 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"],
|
||||
@@ -60,6 +80,7 @@ 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"],
|
||||
@@ -69,6 +90,7 @@ 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"],
|
||||
@@ -78,6 +100,7 @@ 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"],
|
||||
@@ -87,6 +110,7 @@ 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"],
|
||||
@@ -96,6 +120,7 @@ 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"],
|
||||
@@ -105,6 +130,7 @@ 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"],
|
||||
@@ -114,6 +140,7 @@ 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"],
|
||||
@@ -123,6 +150,7 @@ 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"],
|
||||
@@ -132,6 +160,7 @@ 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"],
|
||||
@@ -141,6 +170,7 @@ 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",
|
||||
@@ -160,6 +190,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ruby",
|
||||
language: tree_sitter_ruby::LANGUAGE,
|
||||
outline: outline!("ruby"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"method",
|
||||
"singleton_method",
|
||||
@@ -185,6 +216,7 @@ 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"],
|
||||
@@ -194,6 +226,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "lua",
|
||||
language: tree_sitter_lua::LANGUAGE,
|
||||
outline: outline!("lua"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"function_declaration",
|
||||
"function_definition",
|
||||
@@ -212,6 +245,7 @@ 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"],
|
||||
@@ -221,6 +255,7 @@ 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,
|
||||
@@ -230,6 +265,7 @@ 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,
|
||||
@@ -239,6 +275,7 @@ 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,
|
||||
@@ -249,6 +286,7 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
name: "ocaml",
|
||||
language: tree_sitter_ocaml::LANGUAGE_OCAML,
|
||||
outline: outline!("ocaml"),
|
||||
highlights: None,
|
||||
fold_nodes: &[
|
||||
"value_definition",
|
||||
"type_definition",
|
||||
@@ -266,6 +304,7 @@ 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"],
|
||||
@@ -275,6 +314,7 @@ 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,
|
||||
@@ -284,6 +324,7 @@ 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,
|
||||
@@ -293,6 +334,7 @@ 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,
|
||||
@@ -302,6 +344,7 @@ 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"],
|
||||
@@ -311,6 +354,7 @@ 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,
|
||||
@@ -320,6 +364,7 @@ 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,
|
||||
@@ -329,6 +374,7 @@ 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,
|
||||
@@ -338,6 +384,7 @@ 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,
|
||||
@@ -347,6 +394,7 @@ 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,
|
||||
@@ -356,6 +404,7 @@ 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,
|
||||
@@ -365,6 +414,7 @@ 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"],
|
||||
@@ -374,6 +424,7 @@ 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,
|
||||
@@ -383,6 +434,7 @@ 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"],
|
||||
@@ -392,6 +444,7 @@ 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,
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
//! 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(®ex_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)]),
|
||||
];
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ impl<'a> LineIndex<'a> {
|
||||
}
|
||||
|
||||
/// UTF-16 offset of a char-boundary byte offset.
|
||||
fn utf16_at(&self, byte: usize) -> usize {
|
||||
pub(crate) fn utf16_at(&self, byte: usize) -> usize {
|
||||
if self.checkpoints.is_empty() {
|
||||
return byte;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges.
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
|
||||
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};
|
||||
use ide_core::{LanguageId, OutlineItem, Range};
|
||||
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 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;
|
||||
@@ -31,6 +38,7 @@ 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>,
|
||||
}
|
||||
|
||||
@@ -50,6 +58,17 @@ 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! {
|
||||
@@ -72,6 +91,7 @@ impl Syntax {
|
||||
spec,
|
||||
language: Language::new(spec.language),
|
||||
outline: OnceLock::new(),
|
||||
highlights: OnceLock::new(),
|
||||
kinds: OnceLock::new(),
|
||||
})
|
||||
.collect();
|
||||
@@ -102,6 +122,8 @@ 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());
|
||||
@@ -126,7 +148,8 @@ 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.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
|
||||
self.web_grammar(lang).is_some()
|
||||
|| 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> {
|
||||
@@ -143,11 +166,80 @@ 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| {
|
||||
let query = g.outline_query()?;
|
||||
Some(outline::tags(g, query, tree, text))
|
||||
Some(SyntaxHighlights::new(highlight::highlights(g.highlight_query()?, tree, text)))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 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)))
|
||||
}
|
||||
|
||||
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
use super::Grammar;
|
||||
use super::lines::LineIndex;
|
||||
use crate::SymbolTag;
|
||||
use ide_core::{OutlineItem, SymbolKind};
|
||||
use ide_core::{OutlineItem, SymbolKind, Visibility};
|
||||
use std::collections::HashMap;
|
||||
use tree_sitter::{Node, Query, QueryCursor, StreamingIterator, Tree};
|
||||
|
||||
@@ -139,11 +139,16 @@ 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>,
|
||||
}
|
||||
|
||||
@@ -188,6 +193,7 @@ 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}"),
|
||||
@@ -213,6 +219,8 @@ 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 => {}
|
||||
@@ -239,6 +247,7 @@ 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;
|
||||
@@ -250,7 +259,10 @@ fn build_tree(g: &Grammar, raws: Vec<Raw>) -> Vec<Built> {
|
||||
kind = SymbolKind::Constructor;
|
||||
}
|
||||
}
|
||||
stack.push(Built { raw, kind, children: Vec::new() });
|
||||
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() });
|
||||
}
|
||||
while let Some(done) = stack.pop() {
|
||||
push_child(&mut stack, &mut roots, done);
|
||||
@@ -278,6 +290,7 @@ 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()
|
||||
@@ -308,6 +321,107 @@ 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,6 +1,6 @@
|
||||
use super::*;
|
||||
use crate::FoldKind;
|
||||
use ide_core::{OutlineItem, Pos, SymbolKind};
|
||||
use ide_core::{OutlineItem, Pos, SymbolKind, Visibility};
|
||||
|
||||
fn syntax() -> &'static Syntax {
|
||||
static S: OnceLock<Syntax> = OnceLock::new();
|
||||
@@ -1085,3 +1085,211 @@ 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"]);
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! 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()
|
||||
}
|
||||
@@ -121,6 +121,7 @@ pub fn client_capabilities() -> Value {
|
||||
"honorsChangeAnnotations": false
|
||||
},
|
||||
"codeLens": { "dynamicRegistration": false },
|
||||
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
|
||||
"formatting": { "dynamicRegistration": false },
|
||||
"rangeFormatting": { "dynamicRegistration": false },
|
||||
"rename": {
|
||||
@@ -156,6 +157,7 @@ pub fn client_capabilities() -> Value {
|
||||
"augmentsSyntaxTokens": true
|
||||
},
|
||||
"inlayHint": { "dynamicRegistration": false },
|
||||
"inlineCompletion": { "dynamicRegistration": true },
|
||||
"callHierarchy": { "dynamicRegistration": false },
|
||||
"typeHierarchy": { "dynamicRegistration": false }
|
||||
},
|
||||
@@ -203,8 +205,10 @@ 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,
|
||||
|
||||
@@ -434,6 +434,101 @@ 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 {
|
||||
@@ -614,6 +709,7 @@ pub fn document_symbols(conv: &Conv, path: &Path, r: lsp::DocumentSymbolResponse
|
||||
range,
|
||||
selection_range: range,
|
||||
children: Vec::new(),
|
||||
visibility: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -632,6 +728,7 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -733,19 +830,34 @@ 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 label = match h.label {
|
||||
lsp::InlayHintLabel::String(s) => s,
|
||||
lsp::InlayHintLabel::LabelParts(parts) => parts.into_iter().map(|p| p.value).collect(),
|
||||
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 kind = match h.kind {
|
||||
Some(lsp::InlayHintKind::TYPE) => InlayKind::Type,
|
||||
Some(lsp::InlayHintKind::PARAMETER) => InlayKind::Parameter,
|
||||
_ => InlayKind::Other,
|
||||
};
|
||||
let tooltip = h.tooltip.map(|t| match t {
|
||||
lsp::InlayHintTooltip::String(s) => s,
|
||||
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
|
||||
});
|
||||
let tooltip = h.tooltip.map(tooltip_text);
|
||||
InlayHint {
|
||||
position: conv.pos(path, h.position),
|
||||
label,
|
||||
@@ -753,6 +865,7 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -783,6 +896,27 @@ 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 {
|
||||
@@ -842,6 +976,7 @@ 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()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -855,6 +990,25 @@ 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)
|
||||
}
|
||||
@@ -1111,5 +1265,52 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,8 @@ impl ClientHandler {
|
||||
Value::Array(
|
||||
items
|
||||
.iter()
|
||||
.map(|item| match item.get("section").and_then(Value::as_str) {
|
||||
// vtsls asks for the whole configuration as section `""`.
|
||||
.map(|item| match item.get("section").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
Some(section) if section == self.server.name => options.clone(),
|
||||
// Servers that take settings under `initializationOptions.settings`
|
||||
// (jdtls) ask for the same sections later.
|
||||
@@ -193,6 +194,7 @@ 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),
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ 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)]
|
||||
@@ -70,6 +74,46 @@ 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.
|
||||
@@ -138,6 +182,9 @@ 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:?})"),
|
||||
}))
|
||||
}
|
||||
@@ -210,6 +257,10 @@ 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,
|
||||
@@ -225,9 +276,25 @@ 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| {
|
||||
@@ -256,6 +323,28 @@ 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!({
|
||||
|
||||
@@ -10,6 +10,8 @@ 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),
|
||||
}
|
||||
|
||||
@@ -72,7 +74,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
|
||||
if !is_proxy || command.contains('/') {
|
||||
return binary;
|
||||
}
|
||||
let works = std::process::Command::new(&binary)
|
||||
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod jdtls;
|
||||
mod launch;
|
||||
mod server;
|
||||
mod text;
|
||||
mod tsserver_bridge;
|
||||
pub mod types;
|
||||
mod uri;
|
||||
mod virtual_doc;
|
||||
@@ -339,7 +340,7 @@ 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::Failed(message.clone()) });
|
||||
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
|
||||
}
|
||||
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
|
||||
})
|
||||
@@ -358,6 +359,13 @@ 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) {
|
||||
@@ -797,6 +805,40 @@ 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) };
|
||||
@@ -1415,6 +1457,52 @@ 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,
|
||||
@@ -1425,8 +1513,9 @@ 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 mut out = Vec::new();
|
||||
for item in items.unwrap_or_default() {
|
||||
for item in items {
|
||||
let params = json!({ "item": item });
|
||||
match direction {
|
||||
HierarchyDirection::Incoming => {
|
||||
@@ -1467,12 +1556,13 @@ 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.unwrap_or_default() {
|
||||
for item in items {
|
||||
let related: Option<Vec<serde_json::Value>> =
|
||||
self.call(t, method, json!({ "item": item }), None, LONG_TIMEOUT).await?;
|
||||
let conv = self.conv(t.enc());
|
||||
@@ -1604,8 +1694,10 @@ impl LspManager {
|
||||
s.reset_for_restart();
|
||||
self.ensure_started(&s);
|
||||
}
|
||||
// Missing / crashed servers retry with the new configuration (e.g. a new PATH).
|
||||
ide_core::event::ServerStatus::Missing | ide_core::event::ServerStatus::Crashed => {
|
||||
// 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 => {
|
||||
s.reset_for_restart();
|
||||
self.ensure_started(&s);
|
||||
}
|
||||
@@ -1726,6 +1818,12 @@ 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::*;
|
||||
|
||||
@@ -13,7 +13,8 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::{Notify, watch};
|
||||
|
||||
const CRASH_WINDOW: Duration = Duration::from_secs(180);
|
||||
/// An instance that stayed up this long ran fine: earlier crashes no longer count.
|
||||
const STABLE_UPTIME: Duration = Duration::from_secs(180);
|
||||
const MAX_RESTARTS: usize = 3;
|
||||
const STDERR_LINES: usize = 50;
|
||||
|
||||
@@ -66,7 +67,10 @@ pub struct Server {
|
||||
state: Mutex<State>,
|
||||
phase: watch::Sender<Phase>,
|
||||
status: Mutex<(ServerStatus, Option<String>)>,
|
||||
crashes: Mutex<VecDeque<Instant>>,
|
||||
/// Consecutive crashes of short-lived instances.
|
||||
crashes: Mutex<usize>,
|
||||
/// When the current instance was launched.
|
||||
started: Mutex<Option<Instant>>,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
pub progress: Mutex<HashMap<String, Progress>>,
|
||||
diagnostics: Mutex<HashMap<PathBuf, Vec<lsp::Diagnostic>>>,
|
||||
@@ -88,7 +92,8 @@ impl Server {
|
||||
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
|
||||
phase: watch::channel(Phase::Down).0,
|
||||
status: Mutex::new((ServerStatus::Stopped, None)),
|
||||
crashes: Mutex::new(VecDeque::new()),
|
||||
crashes: Mutex::new(0),
|
||||
started: Mutex::new(None),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
progress: Mutex::new(HashMap::new()),
|
||||
diagnostics: Mutex::new(HashMap::new()),
|
||||
@@ -127,6 +132,7 @@ impl Server {
|
||||
}
|
||||
st.generation += 1;
|
||||
st.conn = Conn::Starting;
|
||||
*self.started.lock() = Some(Instant::now());
|
||||
self.phase.send_replace(Phase::Starting);
|
||||
Some(st.generation)
|
||||
}
|
||||
@@ -237,21 +243,22 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a crash; returns the backoff before restarting, or `None` when
|
||||
/// the restart budget for the window is exhausted.
|
||||
/// 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).
|
||||
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();
|
||||
let now = Instant::now();
|
||||
crashes.push_back(now);
|
||||
while crashes.front().is_some_and(|t| now.duration_since(*t) > CRASH_WINDOW) {
|
||||
crashes.pop_front();
|
||||
if uptime >= STABLE_UPTIME {
|
||||
*crashes = 0;
|
||||
}
|
||||
let n = crashes.len();
|
||||
*crashes += 1;
|
||||
let n = *crashes;
|
||||
(n <= MAX_RESTARTS).then(|| Duration::from_millis(500) * (1 << (n - 1)) as u32)
|
||||
}
|
||||
|
||||
pub fn reset_for_restart(&self) {
|
||||
self.crashes.lock().clear();
|
||||
*self.crashes.lock() = 0;
|
||||
let mut st = self.state.lock();
|
||||
if matches!(st.conn, Conn::Missing | Conn::Failed) {
|
||||
st.conn = Conn::Idle;
|
||||
@@ -300,8 +307,8 @@ impl Server {
|
||||
|
||||
pub fn stderr_tail(&self, n: usize) -> String {
|
||||
let buf = self.stderr.lock();
|
||||
let skip = buf.len().saturating_sub(n);
|
||||
buf.iter().skip(skip).cloned().collect::<Vec<_>>().join("\n")
|
||||
let lines: Vec<&str> = buf.iter().map(String::as_str).collect();
|
||||
crash_excerpt(&lines, n)
|
||||
}
|
||||
|
||||
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
|
||||
@@ -330,8 +337,108 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! 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(¶ms) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -145,6 +145,21 @@ 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 {
|
||||
@@ -195,6 +210,19 @@ 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.
|
||||
@@ -214,6 +242,21 @@ 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 {
|
||||
|
||||
@@ -415,6 +415,42 @@ 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())]);
|
||||
@@ -710,13 +746,15 @@ 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");
|
||||
h.wait_status("mock", ServerStatus::Crashed).await;
|
||||
// Not a crash: nothing ran, the configuration has to change.
|
||||
h.wait_status("mock", ServerStatus::Misconfigured).await;
|
||||
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 0);
|
||||
let crashed = h.events.lock().iter().find_map(|e| match e {
|
||||
IdeEvent::LanguageServer { status: ServerStatus::Crashed, message, .. } => message.clone(),
|
||||
let reason = h.events.lock().iter().find_map(|e| match e {
|
||||
IdeEvent::LanguageServer { status: ServerStatus::Misconfigured, message, .. } => message.clone(),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(crashed.as_deref(), Some("needs JDK 21"));
|
||||
assert_eq!(reason.as_deref(), Some("needs JDK 21"));
|
||||
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -804,6 +842,11 @@ 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)] }]));
|
||||
@@ -1223,3 +1266,37 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -124,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, msg)) = &s {
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &s {
|
||||
panic!("rust-analyzer failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
@@ -227,3 +227,75 @@ 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,
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,9 @@ mod sandbox;
|
||||
mod theme;
|
||||
mod types;
|
||||
|
||||
pub use manifest::{API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest};
|
||||
pub use manifest::{
|
||||
API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest, ThemeDecl,
|
||||
};
|
||||
pub use sandbox::resolve_in_root;
|
||||
pub use theme::{ThemeDef, ThemeKind};
|
||||
pub use types::*;
|
||||
@@ -627,7 +629,10 @@ fn static_contributions(dir: &Path, m: &PluginManifest) -> Result<Registrations,
|
||||
regs.add_language(cfg);
|
||||
}
|
||||
for f in &m.contributes.themes {
|
||||
let theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?;
|
||||
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()))?;
|
||||
}
|
||||
regs.add_theme(theme);
|
||||
}
|
||||
Ok(regs)
|
||||
|
||||
@@ -64,7 +64,7 @@ pub struct Contributions {
|
||||
#[serde(default)]
|
||||
pub languages: Vec<FileDecl>,
|
||||
#[serde(default)]
|
||||
pub themes: Vec<FileDecl>,
|
||||
pub themes: Vec<ThemeDecl>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -83,6 +83,16 @@ 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())?;
|
||||
@@ -123,8 +133,9 @@ impl PluginManifest {
|
||||
return Err(format!("command {:?} has an empty title", c.id));
|
||||
}
|
||||
}
|
||||
for f in self.contributes.languages.iter().chain(&self.contributes.themes) {
|
||||
check_relative(&f.path, "contributes path")?;
|
||||
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")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -133,7 +144,10 @@ 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()));
|
||||
files.extend(self.contributes.themes.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
|
||||
}
|
||||
|
||||
@@ -202,6 +216,7 @@ mod tests {
|
||||
|
||||
[[contributes.themes]]
|
||||
path = "themes/dark.json"
|
||||
editor-scheme = "themes/dark.scheme.json"
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
@@ -210,7 +225,10 @@ 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")]);
|
||||
assert_eq!(
|
||||
m.files(),
|
||||
vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json"), Path::new("themes/dark.scheme.json")]
|
||||
);
|
||||
assert!(m.has(Permission::EditorWrite) && !m.has(Permission::EditorRead));
|
||||
}
|
||||
|
||||
@@ -242,6 +260,8 @@ 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,4 +1,5 @@
|
||||
//! 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;
|
||||
@@ -24,13 +25,28 @@ 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(src).map_err(|e| format!("invalid theme JSON: {e}"))?;
|
||||
let theme: Self =
|
||||
serde_json::from_str(&strip_json_comments(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() {
|
||||
@@ -55,6 +71,53 @@ 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 {
|
||||
@@ -95,4 +158,34 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,42 @@ 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());
|
||||
|
||||
@@ -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 = Command::new(perf)
|
||||
let out = ide_core::process::no_window(&mut Command::new(perf))
|
||||
.args(["script", "-i"])
|
||||
.arg(data.as_ref() as &Path)
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -232,6 +232,8 @@ mod tests {
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ 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"
|
||||
|
||||
@@ -11,9 +11,26 @@
|
||||
//! 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::RunConfig;
|
||||
use crate::{BeforeLaunchTask, RunConfig, RunExtras};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -22,16 +39,30 @@ 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)]
|
||||
@@ -51,6 +82,35 @@ 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 {
|
||||
@@ -65,17 +125,22 @@ fn slug(s: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
let path = config_path(root);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
fn read_doc(path: &Path) -> IdeResult<Option<FileDoc>> {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
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() {
|
||||
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 name = c.name.filter(|n| !n.is_empty()).unwrap_or_else(|| {
|
||||
if c.command.is_empty() { format!("Configuration {}", i + 1) } else { c.command.clone() }
|
||||
});
|
||||
@@ -91,11 +156,43 @@ pub(crate) fn load(root: &Path) -> IdeResult<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));
|
||||
@@ -121,12 +218,69 @@ 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
|
||||
}
|
||||
|
||||
pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
let path = config_path(root);
|
||||
let existing = match fs::read_to_string(&path) {
|
||||
/// 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) {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
@@ -134,25 +288,65 @@ pub(crate) fn save(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
if existing.is_none() && configs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Keep unrelated keys and comments; a file we cannot parse is replaced.
|
||||
// A file we cannot parse is replaced.
|
||||
let mut doc = existing.as_deref().and_then(|t| t.parse::<DocumentMut>().ok()).unwrap_or_default();
|
||||
let mut array = ArrayOfTables::new();
|
||||
for c in configs {
|
||||
array.push(to_table(c));
|
||||
}
|
||||
if configs.is_empty() {
|
||||
doc.remove("configurations");
|
||||
doc.remove(key);
|
||||
} else {
|
||||
doc.insert("configurations", Item::ArrayOfTables(array));
|
||||
let mut array = ArrayOfTables::new();
|
||||
for c in configs {
|
||||
array.push(to_table(c));
|
||||
}
|
||||
doc.insert(key, Item::ArrayOfTables(array));
|
||||
}
|
||||
let text = doc.to_string();
|
||||
if existing.as_deref() == Some(text.as_str()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
fs::write(&tmp, doc.to_string())?;
|
||||
fs::rename(&tmp, &path).inspect_err(|_| {
|
||||
fs::write(&tmp, text)?;
|
||||
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<_>>())
|
||||
}
|
||||
@@ -37,6 +37,8 @@ fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! `.env` files ("Paths to .env files" / EnvFile): `KEY=value` lines, `export`
|
||||
//! prefixes, `#` comments, single- and double-quoted values (escapes in double
|
||||
//! quotes) and `${VAR}` references to earlier variables or the base environment.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Parses `text`; `lookup` resolves `${VAR}` / `$VAR` not defined earlier in the file.
|
||||
pub fn parse(text: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
let mut lines = text.lines();
|
||||
while let Some(raw) = lines.next() {
|
||||
let line = raw.trim_start_matches('\u{feff}').trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let line = line.strip_prefix("export ").map(str::trim_start).unwrap_or(line);
|
||||
let Some((key, rest)) = line.split_once('=') else { continue };
|
||||
let key = key.trim();
|
||||
if key.is_empty() || key.contains(char::is_whitespace) {
|
||||
continue;
|
||||
}
|
||||
let rest = rest.trim_start();
|
||||
let value = if let Some(body) = rest.strip_prefix('\'') {
|
||||
quoted(body, '\'', &mut lines).unwrap_or_else(|| rest.to_owned())
|
||||
} else if let Some(body) = rest.strip_prefix('"') {
|
||||
let v = quoted(body, '"', &mut lines).unwrap_or_else(|| rest.to_owned());
|
||||
expand(&unescape(&v), &out, lookup)
|
||||
} else {
|
||||
let v = match rest.find(" #") {
|
||||
Some(i) => &rest[..i],
|
||||
None => rest,
|
||||
};
|
||||
expand(v.trim_end(), &out, lookup)
|
||||
};
|
||||
out.retain(|(k, _)| k != key);
|
||||
out.push((key.to_owned(), value));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body of a quoted value up to the closing `quote`, which may be on a later line.
|
||||
fn quoted<'a>(first: &str, quote: char, lines: &mut impl Iterator<Item = &'a str>) -> Option<String> {
|
||||
let mut text = first.to_owned();
|
||||
loop {
|
||||
let mut escaped = false;
|
||||
for (i, c) in text.char_indices() {
|
||||
if quote == '"' && c == '\\' && !escaped {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if c == quote && !escaped {
|
||||
return Some(text[..i].to_owned());
|
||||
}
|
||||
escaped = false;
|
||||
}
|
||||
text.push('\n');
|
||||
text.push_str(lines.next()?);
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut chars = s.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match chars.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some(other) => out.push(other),
|
||||
None => out.push('\\'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn expand(value: &str, earlier: &[(String, String)], lookup: &dyn Fn(&str) -> Option<String>) -> String {
|
||||
let resolve = |name: &str| {
|
||||
earlier
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(k, _)| k == name)
|
||||
.map(|(_, v)| v.clone())
|
||||
.or_else(|| lookup(name))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let mut out = String::with_capacity(value.len());
|
||||
let bytes = value.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < value.len() {
|
||||
if bytes[i] == b'$' {
|
||||
if bytes.get(i + 1) == Some(&b'{')
|
||||
&& let Some(end) = value[i + 2..].find('}')
|
||||
{
|
||||
out.push_str(&resolve(&value[i + 2..i + 2 + end]));
|
||||
i += end + 3;
|
||||
continue;
|
||||
}
|
||||
let name_len = value[i + 1..].bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count();
|
||||
if name_len > 0 {
|
||||
out.push_str(&resolve(&value[i + 1..i + 1 + name_len]));
|
||||
i += name_len + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let c = value[i..].chars().next().unwrap_or_default();
|
||||
out.push(c);
|
||||
i += c.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables of every file in order (later files win); unreadable files are an error.
|
||||
pub fn load(
|
||||
paths: &[std::path::PathBuf],
|
||||
base: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<BTreeMap<String, String>> {
|
||||
let mut vars: BTreeMap<String, String> = BTreeMap::new();
|
||||
for path in paths {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: {e}", path.display())))?;
|
||||
let lookup = |name: &str| vars.get(name).or_else(|| base.get(name)).cloned();
|
||||
let parsed = parse(&text, &lookup);
|
||||
vars.extend(parsed);
|
||||
}
|
||||
Ok(vars)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn none(_: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_common_forms() {
|
||||
let text = "# comment\nA=1\nexport B = two words # trailing\nC='lit $A'\nD=\"x\\ny $A ${B}\"\nE=\"multi\nline\"\n\nbad line\nF=\n";
|
||||
let v = parse(text, &none);
|
||||
let get = |k: &str| v.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
|
||||
assert_eq!(get("A"), Some("1"));
|
||||
assert_eq!(get("B"), Some("two words"));
|
||||
assert_eq!(get("C"), Some("lit $A"));
|
||||
assert_eq!(get("D"), Some("x\ny 1 two words"));
|
||||
assert_eq!(get("E"), Some("multi\nline"));
|
||||
assert_eq!(get("F"), Some(""));
|
||||
assert_eq!(v.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_fall_back_to_base() {
|
||||
let v = parse("P=$HOME/bin:${MISSING}x", &|n| (n == "HOME").then(|| "/h".to_owned()));
|
||||
assert_eq!(v, [("P".to_owned(), "/h/bin:x".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
//! IDEA's "Shorten command line" for `java` launches: a classpath too long for
|
||||
//! the platform's command-line limit (Windows `CreateProcessW`: 32767 chars,
|
||||
//! `os error 206`) moves into an `@argfile` (JDK 9+) or a pathing jar whose
|
||||
//! manifest `Class-Path` lists the entries (any JDK, the only option on JDK 8).
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// `CreateProcessW` takes at most 32767 chars including the NUL; leave slack for quoting.
|
||||
pub const WINDOWS_LIMIT: usize = 32_000;
|
||||
/// Linux caps one argument at 128 KiB (`MAX_ARG_STRLEN`); macOS the whole `ARG_MAX` (1 MiB, env included).
|
||||
pub const UNIX_LIMIT: usize = 120_000;
|
||||
|
||||
/// How a long `java` command line is shortened (java-debug's `shortenCommandLine` values).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Shortening {
|
||||
None,
|
||||
/// A temporary jar whose manifest `Class-Path` lists the classpath.
|
||||
JarManifest,
|
||||
/// A temporary `@argfile` holding `-cp` (and `--module-path`), JDK 9+.
|
||||
ArgFile,
|
||||
}
|
||||
|
||||
impl Shortening {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::None => "none",
|
||||
Self::JarManifest => "jarmanifest",
|
||||
Self::ArgFile => "argfile",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command_line_limit(windows: bool) -> usize {
|
||||
if windows { WINDOWS_LIMIT } else { UNIX_LIMIT }
|
||||
}
|
||||
|
||||
/// Length of the command line as the OS receives it (quotes and separators included).
|
||||
pub fn command_line_length(program: &str, args: &[String]) -> usize {
|
||||
std::iter::once(program).chain(args.iter().map(String::as_str)).map(|a| a.len() + 3).sum()
|
||||
}
|
||||
|
||||
/// Whether the longest single argument or the whole line exceeds the platform limit.
|
||||
fn too_long(program: &str, args: &[String], windows: bool) -> bool {
|
||||
let limit = command_line_limit(windows);
|
||||
command_line_length(program, args) > limit || (!windows && args.iter().any(|a| a.len() > limit))
|
||||
}
|
||||
|
||||
/// IDEA's automatic choice: nothing when the line fits; else an `@argfile` on JDK 9+
|
||||
/// when every path is ASCII (the launcher reads argfiles in the platform charset),
|
||||
/// else a pathing jar (works on every JDK; manifest URLs are percent-encoded UTF-8).
|
||||
pub fn choose(too_long: bool, java_major: Option<u32>, classpath: &str) -> Shortening {
|
||||
if !too_long {
|
||||
Shortening::None
|
||||
} else if java_major.is_some_and(|v| v >= 9) && classpath.is_ascii() {
|
||||
Shortening::ArgFile
|
||||
} else {
|
||||
Shortening::JarManifest
|
||||
}
|
||||
}
|
||||
|
||||
/// Room left for VM options and program arguments when only the paths are known.
|
||||
const OTHER_ARGS_RESERVE: usize = 4_096;
|
||||
|
||||
/// The shortening a launcher that builds the command line itself (java-debug's
|
||||
/// `shortenCommandLine`) should use for `java -cp <class_paths> [--module-path …] …`.
|
||||
pub fn shortening_for(java: &Path, class_paths: &[String], module_paths: &[String], windows: bool) -> Shortening {
|
||||
let sep = if windows { ";" } else { ":" };
|
||||
let (cp, mp) = (class_paths.join(sep), module_paths.join(sep));
|
||||
let len = java.as_os_str().len() + cp.len() + mp.len() + 64 + OTHER_ARGS_RESERVE;
|
||||
let limit = command_line_limit(windows);
|
||||
choose(len > limit || cp.len() > limit || mp.len() > limit, java_feature_version(java), &format!("{cp}{mp}"))
|
||||
}
|
||||
|
||||
/// `JAVA_VERSION="21.0.3"` (or `"1.8.0_372"`) from a JDK's `release` file.
|
||||
pub fn parse_release(release: &str) -> Option<u32> {
|
||||
let line = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
|
||||
let mut parts = line.trim().trim_matches('"').split(['.', '_', '-', '+']);
|
||||
let first: u32 = parts.next()?.parse().ok()?;
|
||||
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
|
||||
}
|
||||
|
||||
/// Feature version of the JDK a `java` launcher belongs to (`<home>/bin/java`, or
|
||||
/// JDK 8's `<home>/jre/bin/java`), following symlinks; `None` when unknown.
|
||||
pub fn java_feature_version(java: &Path) -> Option<u32> {
|
||||
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
|
||||
java.ancestors()
|
||||
.skip(2)
|
||||
.take(2)
|
||||
.find_map(|home| std::fs::read_to_string(home.join("release")).ok())
|
||||
.and_then(|r| parse_release(&r))
|
||||
}
|
||||
|
||||
/// `java`, `java.exe`, `javaw.exe`.
|
||||
pub fn is_java_launcher(program: &Path) -> bool {
|
||||
let name = crate::wrap::program_name(&program.to_string_lossy()).to_ascii_lowercase();
|
||||
name == "java" || name == "javaw"
|
||||
}
|
||||
|
||||
/// `java` options whose value is the next argument.
|
||||
const WITH_VALUE: &[&str] = &[
|
||||
"-cp",
|
||||
"-classpath",
|
||||
"--class-path",
|
||||
"-p",
|
||||
"--module-path",
|
||||
"--upgrade-module-path",
|
||||
"--add-modules",
|
||||
"--add-opens",
|
||||
"--add-exports",
|
||||
"--add-reads",
|
||||
"--patch-module",
|
||||
"--limit-modules",
|
||||
"--enable-native-access",
|
||||
];
|
||||
|
||||
/// Indices of the `-cp` and `--module-path` values among the VM options (before the main class).
|
||||
fn path_options(args: &[String]) -> (Option<usize>, Option<usize>) {
|
||||
let (mut cp, mut mp) = (None, None);
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let a = args[i].as_str();
|
||||
if matches!(a, "-jar" | "-m" | "--module") || !a.starts_with('-') {
|
||||
break;
|
||||
}
|
||||
if WITH_VALUE.contains(&a) {
|
||||
if i + 1 < args.len() {
|
||||
match a {
|
||||
"-cp" | "-classpath" | "--class-path" => cp = Some(i + 1),
|
||||
"-p" | "--module-path" => mp = Some(i + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
(cp, mp)
|
||||
}
|
||||
|
||||
/// A shortened command line and the temporary file it refers to (delete it once the process exits).
|
||||
#[derive(Debug)]
|
||||
pub struct Shortened {
|
||||
pub args: Vec<String>,
|
||||
pub file: PathBuf,
|
||||
pub how: Shortening,
|
||||
}
|
||||
|
||||
/// Shortens `java [options] -cp <classpath> Main …` when it is too long for the platform:
|
||||
/// `None` for other programs, lines that fit, or no classpath option.
|
||||
pub fn shorten(
|
||||
program: &Path,
|
||||
args: &[String],
|
||||
cwd: &Path,
|
||||
windows: bool,
|
||||
temp_dir: &Path,
|
||||
) -> std::io::Result<Option<Shortened>> {
|
||||
if !is_java_launcher(program) || !too_long(&program.to_string_lossy(), args, windows) {
|
||||
return Ok(None);
|
||||
}
|
||||
let (cp, mp) = path_options(args);
|
||||
let Some(cp) = cp else { return Ok(None) };
|
||||
let how = choose(true, java_feature_version(program), &args[cp]);
|
||||
std::fs::create_dir_all(temp_dir)?;
|
||||
let mut out = args.to_vec();
|
||||
let file = match how {
|
||||
Shortening::ArgFile => {
|
||||
let file = temp_file(temp_dir, "argfile");
|
||||
let mut moved = vec![cp - 1, cp];
|
||||
if let Some(mp) = mp {
|
||||
moved.extend([mp - 1, mp]);
|
||||
}
|
||||
moved.sort_unstable();
|
||||
let text = argfile_text(&moved.iter().map(|&i| args[i].clone()).collect::<Vec<_>>());
|
||||
std::fs::write(&file, text)?;
|
||||
for &i in moved.iter().rev() {
|
||||
out.remove(i);
|
||||
}
|
||||
out.insert(moved[0], format!("@{}", file.display()));
|
||||
file
|
||||
}
|
||||
_ => {
|
||||
let file = temp_file(temp_dir, "jar");
|
||||
let entries = classpath_entries(&args[cp], cwd, windows);
|
||||
write_pathing_jar(&entries, &file)?;
|
||||
out[cp] = file.to_string_lossy().into_owned();
|
||||
file
|
||||
}
|
||||
};
|
||||
Ok(Some(Shortened { args: out, file, how }))
|
||||
}
|
||||
|
||||
/// Where launches put their pathing jars / argfiles.
|
||||
pub fn default_temp_dir() -> PathBuf {
|
||||
std::env::temp_dir().join("openidea-classpath")
|
||||
}
|
||||
|
||||
fn temp_file(dir: &Path, ext: &str) -> PathBuf {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
dir.join(format!("classpath-{}-{nanos}-{n}.{ext}", std::process::id()))
|
||||
}
|
||||
|
||||
/// Argument file lines: every argument quoted, `\` and `"` escaped (the launcher's argfile syntax).
|
||||
pub fn argfile_text(args: &[String]) -> String {
|
||||
let mut out = String::new();
|
||||
for a in args {
|
||||
out.push('"');
|
||||
for c in a.chars() {
|
||||
if c == '\\' || c == '"' {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push_str("\"\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Classpath entries as absolute paths: relative ones against `cwd`, `dir/*` expanded to its jars.
|
||||
pub fn classpath_entries(classpath: &str, cwd: &Path, windows: bool) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for e in classpath.split(if windows { ';' } else { ':' }).filter(|e| !e.is_empty()) {
|
||||
let wildcard = e.strip_suffix("/*").or_else(|| e.strip_suffix("\\*"));
|
||||
let path = cwd.join(wildcard.unwrap_or(e));
|
||||
if wildcard.is_some() {
|
||||
let mut jars: Vec<PathBuf> = std::fs::read_dir(&path)
|
||||
.map(|rd| {
|
||||
rd.flatten()
|
||||
.map(|d| d.path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
jars.sort();
|
||||
out.extend(jars);
|
||||
} else {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `file:` URL of a classpath entry: percent-encoded UTF-8, `/` separators, a trailing `/` on directories.
|
||||
pub fn file_url(path: &str, dir: bool) -> String {
|
||||
let mut p = path.replace('\\', "/");
|
||||
if !p.starts_with('/') {
|
||||
p.insert(0, '/'); // `C:/x` → `/C:/x`
|
||||
} else if p.starts_with("//") {
|
||||
p.insert_str(0, "//"); // UNC `//server/share` → `file:////server/share`, as `File.toURI` does
|
||||
}
|
||||
if dir && !p.ends_with('/') {
|
||||
p.push('/');
|
||||
}
|
||||
let mut url = String::from("file:");
|
||||
for b in p.bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"-._~/:".contains(&b) {
|
||||
url.push(b as char);
|
||||
} else {
|
||||
url.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
/// `META-INF/MANIFEST.MF` listing `entries`, lines wrapped at 72 bytes (continuations start with a space).
|
||||
pub fn manifest(entries: &[PathBuf]) -> String {
|
||||
let urls: Vec<String> = entries.iter().map(|e| file_url(&e.to_string_lossy(), e.is_dir())).collect();
|
||||
let mut out = String::from("Manifest-Version: 1.0\r\nCreated-By: OpenIDEA\r\n");
|
||||
out.push_str(&wrap_header(&format!("Class-Path: {}", urls.join(" "))));
|
||||
out.push_str("\r\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// One manifest header in lines of at most 72 bytes; `line` is ASCII (URLs are percent-encoded).
|
||||
fn wrap_header(line: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = line;
|
||||
let mut width = 72;
|
||||
while !rest.is_empty() {
|
||||
let (head, tail) = rest.split_at(width.min(rest.len()));
|
||||
if width == 71 {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(head);
|
||||
out.push_str("\r\n");
|
||||
rest = tail;
|
||||
width = 71;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A jar holding only a manifest whose `Class-Path` is `entries` (IDEA's "JAR manifest").
|
||||
pub fn write_pathing_jar(entries: &[PathBuf], out: &Path) -> std::io::Result<()> {
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(out)?);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
zip.start_file("META-INF/MANIFEST.MF", opts).map_err(std::io::Error::other)?;
|
||||
zip.write_all(manifest(entries).as_bytes())?;
|
||||
zip.finish().map_err(std::io::Error::other)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn strings(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chooses_like_idea() {
|
||||
assert_eq!(choose(false, Some(8), "a.jar"), Shortening::None);
|
||||
assert_eq!(choose(true, Some(8), "a.jar"), Shortening::JarManifest);
|
||||
assert_eq!(choose(true, None, "a.jar"), Shortening::JarManifest);
|
||||
assert_eq!(choose(true, Some(9), "a.jar"), Shortening::ArgFile);
|
||||
assert_eq!(choose(true, Some(21), "a.jar"), Shortening::ArgFile);
|
||||
assert_eq!(choose(true, Some(21), "C:\\用户\\a.jar"), Shortening::JarManifest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debugger_launches_get_the_same_choice() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jdk = dir.path().join("jdk11");
|
||||
std::fs::create_dir_all(jdk.join("bin")).unwrap();
|
||||
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"11.0.18\"").unwrap();
|
||||
let java = jdk.join("bin/java");
|
||||
let few = vec!["/r/a.jar".to_owned(); 10];
|
||||
let many = vec![r"C:\Users\dev\.m2\repository\org\x\lib\1.0\lib-1.0.jar".to_owned(); 600];
|
||||
assert_eq!(shortening_for(&java, &few, &[], true), Shortening::None);
|
||||
assert_eq!(shortening_for(&java, &many, &[], true), Shortening::ArgFile);
|
||||
assert_eq!(shortening_for(&java, &many, &[], false), Shortening::None);
|
||||
assert_eq!(shortening_for(Path::new("java"), &many, &[], true), Shortening::JarManifest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_versions() {
|
||||
assert_eq!(parse_release("JAVA_VERSION=\"1.8.0_372\"\n"), Some(8));
|
||||
assert_eq!(parse_release("IMPLEMENTOR=x\nJAVA_VERSION=\"21.0.3\""), Some(21));
|
||||
assert_eq!(parse_release("JAVA_VERSION=\"25\""), Some(25));
|
||||
assert_eq!(parse_release("nothing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_version_from_the_jdk_layout() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jdk8 = dir.path().join("jdk8");
|
||||
std::fs::create_dir_all(jdk8.join("jre/bin")).unwrap();
|
||||
std::fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"").unwrap();
|
||||
assert_eq!(java_feature_version(&jdk8.join("jre/bin/java")), Some(8));
|
||||
let jdk21 = dir.path().join("jdk21");
|
||||
std::fs::create_dir_all(jdk21.join("bin")).unwrap();
|
||||
std::fs::write(jdk21.join("release"), "JAVA_VERSION=\"21.0.3\"").unwrap();
|
||||
assert_eq!(java_feature_version(&jdk21.join("bin/java")), Some(21));
|
||||
assert_eq!(java_feature_version(Path::new("java")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launchers() {
|
||||
for p in ["java", "/usr/bin/java", r"C:\jdk\bin\java.exe", r"C:\jdk\bin\javaw.exe", "JAVA.EXE"] {
|
||||
assert!(is_java_launcher(Path::new(p)), "{p}");
|
||||
}
|
||||
for p in ["javac", "kotlin", "/usr/bin/mvn", "java-agent"] {
|
||||
assert!(!is_java_launcher(Path::new(p)), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_classpath_among_vm_options_only() {
|
||||
let a = strings(&["-Xmx1g", "--add-opens", "a/b=ALL", "-cp", "x.jar", "Main", "-cp", "y"]);
|
||||
assert_eq!(path_options(&a), (Some(4), None));
|
||||
let a = strings(&["-p", "mods", "-classpath", "x.jar", "Main"]);
|
||||
assert_eq!(path_options(&a), (Some(3), Some(1)));
|
||||
assert_eq!(path_options(&strings(&["-jar", "app.jar", "-cp", "x"])), (None, None));
|
||||
assert_eq!(path_options(&strings(&["Main", "-cp", "x"])), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_are_encoded_and_directories_end_with_a_slash() {
|
||||
assert_eq!(file_url("/p/a b/x.jar", false), "file:/p/a%20b/x.jar");
|
||||
assert_eq!(file_url("/p/classes", true), "file:/p/classes/");
|
||||
assert_eq!(file_url("/p/classes/", true), "file:/p/classes/");
|
||||
assert_eq!(file_url(r"C:\Users\me\.m2\a+b#c.jar", false), "file:/C:/Users/me/.m2/a%2Bb%23c.jar");
|
||||
assert_eq!(file_url(r"\\srv\share\x.jar", false), "file:////srv/share/x.jar");
|
||||
assert_eq!(file_url("/p/用户/x.jar", false), "file:/p/%E7%94%A8%E6%88%B7/x.jar");
|
||||
assert_eq!(file_url("/p/100%/x.jar", false), "file:/p/100%25/x.jar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_lines_are_at_most_72_bytes() {
|
||||
let entries: Vec<PathBuf> = (0..300)
|
||||
.map(|i| PathBuf::from(format!("/home/u/.m2/repository/org/x/lib-{i}/1.0/lib {i}-1.0.jar")))
|
||||
.collect();
|
||||
let m = manifest(&entries);
|
||||
assert!(m.starts_with("Manifest-Version: 1.0\r\n"));
|
||||
assert!(m.ends_with("\r\n\r\n"));
|
||||
for line in m.split("\r\n") {
|
||||
assert!(line.len() <= 72, "{line:?}");
|
||||
}
|
||||
// Unwrapping restores the header exactly.
|
||||
let joined = m.replace("\r\n ", "");
|
||||
let joined = joined.lines().find_map(|l| l.strip_prefix("Class-Path: ")).unwrap();
|
||||
let urls: Vec<&str> = joined.split(' ').collect();
|
||||
assert_eq!(urls.len(), 300);
|
||||
assert_eq!(urls[7], "file:/home/u/.m2/repository/org/x/lib-7/1.0/lib%207-1.0.jar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argfile_quotes_and_escapes() {
|
||||
assert_eq!(
|
||||
argfile_text(&strings(&["-cp", r#"C:\a b\x.jar;C:\q"y.jar"#])),
|
||||
"\"-cp\"\n\"C:\\\\a b\\\\x.jar;C:\\\\q\\\"y.jar\"\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_lines_and_other_programs_are_left_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let args = strings(&["-cp", "a.jar", "Main"]);
|
||||
assert!(shorten(Path::new("java"), &args, dir.path(), true, dir.path()).unwrap().is_none());
|
||||
let long = strings(&["-cp", &"x".repeat(40_000), "Main"]);
|
||||
assert!(shorten(Path::new("node"), &long, dir.path(), true, dir.path()).unwrap().is_none());
|
||||
// Fits the Unix limit; too long for Windows.
|
||||
assert!(shorten(Path::new("java"), &long, dir.path(), false, dir.path()).unwrap().is_none());
|
||||
}
|
||||
|
||||
/// The reporter's case: JDK 8, ~270 jars, past 32767 chars on Windows.
|
||||
#[test]
|
||||
fn jdk8_gets_a_pathing_jar() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jdk = dir.path().join("jdk8");
|
||||
std::fs::create_dir_all(jdk.join("bin")).unwrap();
|
||||
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"1.8.0_372\"").unwrap();
|
||||
let java = jdk.join("bin/java.exe");
|
||||
let cp: Vec<String> = (0..270)
|
||||
.map(|i| format!(r"C:\Users\developer01\.m2\repository\org\springframework\boot\spring-boot-starter-lib-{i}\2.7.18\spring-boot-starter-lib-{i}-2.7.18.jar"))
|
||||
.collect();
|
||||
let cp = format!(r"C:\work\demo\target\classes;{}", cp.join(";"));
|
||||
assert!(cp.len() > 32_767);
|
||||
let args =
|
||||
strings(&["-Dspring.profiles.active=dev", "-cp", &cp, "com.example.DemoApplication", "--port", "8080"]);
|
||||
let tmp = dir.path().join("tmp");
|
||||
let s = shorten(&java, &args, dir.path(), true, &tmp).unwrap().unwrap();
|
||||
assert_eq!(s.how, Shortening::JarManifest);
|
||||
assert_eq!(s.args[0], "-Dspring.profiles.active=dev");
|
||||
assert_eq!(s.args[1], "-cp");
|
||||
assert_eq!(s.args[2], s.file.to_string_lossy());
|
||||
assert_eq!(&s.args[3..], ["com.example.DemoApplication", "--port", "8080"]);
|
||||
assert!(command_line_length(&java.to_string_lossy(), &s.args) < 1_000);
|
||||
let mut jar = zip::ZipArchive::new(std::fs::File::open(&s.file).unwrap()).unwrap();
|
||||
let mut text = String::new();
|
||||
std::io::Read::read_to_string(&mut jar.by_name("META-INF/MANIFEST.MF").unwrap(), &mut text).unwrap();
|
||||
let text = text.replace("\r\n ", "");
|
||||
let urls: Vec<&str> = text.lines().find_map(|l| l.strip_prefix("Class-Path: ")).unwrap().split(' ').collect();
|
||||
assert_eq!(urls.len(), 271);
|
||||
assert!(urls.iter().all(|u| u.starts_with("file:/") && u.ends_with(".jar") || u.ends_with("classes")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdk9_plus_gets_an_argfile_with_the_module_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jdk = dir.path().join("jdk17");
|
||||
std::fs::create_dir_all(jdk.join("bin")).unwrap();
|
||||
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"17.0.6\"").unwrap();
|
||||
let cp = vec!["/r/lib.jar"; 3_000].join(":");
|
||||
let args = strings(&["-Xmx1g", "--module-path", "/r/mods", "-cp", &cp, "a.Main", "x"]);
|
||||
let s = shorten(&jdk.join("bin/java"), &args, dir.path(), true, dir.path()).unwrap().unwrap();
|
||||
assert_eq!(s.how, Shortening::ArgFile);
|
||||
assert_eq!(s.args, ["-Xmx1g".to_owned(), format!("@{}", s.file.display()), "a.Main".into(), "x".into()]);
|
||||
let text = std::fs::read_to_string(&s.file).unwrap();
|
||||
assert_eq!(text, format!("\"--module-path\"\n\"/r/mods\"\n\"-cp\"\n\"{cp}\"\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcards_and_relative_entries() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("lib")).unwrap();
|
||||
for f in ["b.jar", "a.JAR", "notes.txt"] {
|
||||
std::fs::write(dir.path().join("lib").join(f), "").unwrap();
|
||||
}
|
||||
// An absolute entry stays as is; built from the temp dir so it is absolute on every platform.
|
||||
let abs = dir.path().join("abs").join("x.jar");
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
let cp = ["classes", "lib/*", &abs.to_string_lossy()].join(sep);
|
||||
let e = classpath_entries(&cp, dir.path(), cfg!(windows));
|
||||
assert_eq!(e, [dir.path().join("classes"), dir.path().join("lib/a.JAR"), dir.path().join("lib/b.jar"), abs]);
|
||||
}
|
||||
|
||||
/// A pathing jar really loads classes (and resources from directories) with this machine's JDKs.
|
||||
#[test]
|
||||
fn pathing_jar_runs_with_a_local_jdk() {
|
||||
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from).or_else(|| {
|
||||
let java = crate::which::find_executable("java", &std::env::var_os("PATH").unwrap_or_default())?;
|
||||
std::fs::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let bin = |t: &str| home.join("bin").join(if cfg!(windows) { format!("{t}.exe") } else { t.to_owned() });
|
||||
if !bin("javac").is_file() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let src = dir.path().join("src dir");
|
||||
let classes = dir.path().join("out classes");
|
||||
std::fs::create_dir_all(src.join("p")).unwrap();
|
||||
std::fs::create_dir_all(&classes).unwrap();
|
||||
std::fs::write(
|
||||
src.join("p/Main.java"),
|
||||
"package p; public class Main { public static void main(String[] a) { System.out.println(\"hello \" + a[0]); } }",
|
||||
)
|
||||
.unwrap();
|
||||
let ok = std::process::Command::new(bin("javac"))
|
||||
.args(["--release", "8", "-d"])
|
||||
.arg(&classes)
|
||||
.arg(src.join("p/Main.java"))
|
||||
.status()
|
||||
.is_ok_and(|s| s.success())
|
||||
|| std::process::Command::new(bin("javac"))
|
||||
.arg("-d")
|
||||
.arg(&classes)
|
||||
.arg(src.join("p/Main.java"))
|
||||
.status()
|
||||
.is_ok_and(|s| s.success());
|
||||
assert!(ok, "javac failed");
|
||||
let mut entries: Vec<PathBuf> = (0..400).map(|i| dir.path().join(format!("missing {i}.jar"))).collect();
|
||||
entries.push(classes.clone());
|
||||
let jar = dir.path().join("cp.jar");
|
||||
write_pathing_jar(&entries, &jar).unwrap();
|
||||
let out =
|
||||
std::process::Command::new(bin("java")).arg("-cp").arg(&jar).args(["p.Main", "world"]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello world");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
mod config;
|
||||
mod detect;
|
||||
pub mod envfile;
|
||||
pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
mod utf8;
|
||||
@@ -34,6 +36,117 @@ pub struct RunConfig {
|
||||
pub is_test: bool,
|
||||
/// DAP adapter that can debug this config, if any.
|
||||
pub debug_adapter: Option<String>,
|
||||
/// "Allow multiple instances": Run on a running config starts another one instead of restarting it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub allow_parallel: bool,
|
||||
/// Options of user-defined configurations (all optional; old `run.toml` files load unchanged).
|
||||
#[serde(flatten)]
|
||||
pub extras: RunExtras,
|
||||
}
|
||||
|
||||
/// A step run before a configuration launches; a failing step aborts the launch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BeforeLaunchTask {
|
||||
/// `run` (another configuration, `target` = its id) | `build` | `tool` (external tool id) |
|
||||
/// `command` (a shell command line) | `toolWindow` (tool window id).
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_true(b: &bool) -> bool {
|
||||
*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RunExtras {
|
||||
/// Values of the configuration type's own form fields (the command line derives from them).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub params: BTreeMap<String, String>,
|
||||
/// Folder in the Run/Debug Configurations tree.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub folder: Option<String>,
|
||||
/// Stored in the workspace (`.openidea/run.local.toml`, not shared) instead of `run.toml`.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub local: bool,
|
||||
/// Off: the process gets only the configured variables.
|
||||
#[serde(default = "yes", skip_serializing_if = "is_true")]
|
||||
#[specta(optional)]
|
||||
pub include_system_env: bool,
|
||||
/// `.env` files (relative to the project root) loaded before `env`, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub env_files: Vec<String>,
|
||||
/// "Redirect input from": the process reads this file as stdin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub stdin_file: Option<String>,
|
||||
/// "Save console output to file" (overwritten on each run).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub output_file: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub before_launch: Vec<BeforeLaunchTask>,
|
||||
/// Compound configurations: ids of the configurations started together.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub compound: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub show_on_stdout: bool,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub show_on_stderr: bool,
|
||||
/// Overrides Settings › Run › "Show the Run tool window when a process starts".
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub open_tool_window: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub focus_tool_window: bool,
|
||||
/// "Emulate terminal in output console": the process runs on a pseudo-terminal
|
||||
/// (colours, line editing, full-screen programs); the console renders it as a terminal.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub emulate_terminal: bool,
|
||||
/// Shell command line run on Stop before the process is signalled (e.g. `docker stop <name>`),
|
||||
/// with the run's working directory and environment.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub stop_command: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RunExtras {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: BTreeMap::new(),
|
||||
folder: None,
|
||||
local: false,
|
||||
include_system_env: true,
|
||||
env_files: Vec::new(),
|
||||
stdin_file: None,
|
||||
output_file: None,
|
||||
before_launch: Vec::new(),
|
||||
compound: Vec::new(),
|
||||
show_on_stdout: false,
|
||||
show_on_stderr: false,
|
||||
open_tool_window: None,
|
||||
focus_tool_window: false,
|
||||
emulate_terminal: false,
|
||||
stop_command: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -59,6 +172,8 @@ pub struct RunInfo {
|
||||
pub name: String,
|
||||
pub pid: Option<u32>,
|
||||
pub running: bool,
|
||||
/// Runs on a pseudo-terminal: output is raw terminal data, input goes in keystroke by keystroke.
|
||||
pub pty: bool,
|
||||
}
|
||||
|
||||
/// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts),
|
||||
@@ -72,11 +187,26 @@ pub fn load_user_configs(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
config::load(root)
|
||||
}
|
||||
|
||||
/// Writes `<root>/.openidea/run.toml`, preserving unrelated content in the file.
|
||||
/// Writes `<root>/.openidea/run.toml` (and the workspace-local `run.local.toml` for
|
||||
/// configurations not stored as project files), preserving unrelated content.
|
||||
pub fn save_user_configs(root: &Path, configs: &[RunConfig]) -> IdeResult<()> {
|
||||
config::save(root, configs)
|
||||
}
|
||||
|
||||
/// Configuration templates (per-type defaults for new configurations) from `run.toml`.
|
||||
pub fn load_templates(root: &Path) -> IdeResult<Vec<RunConfig>> {
|
||||
config::load_templates(root)
|
||||
}
|
||||
|
||||
pub fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
|
||||
config::save_templates(root, templates)
|
||||
}
|
||||
|
||||
/// The environment runs inherit (unless "Include system environment variables" is off).
|
||||
pub fn system_env() -> BTreeMap<String, String> {
|
||||
std::env::vars().collect()
|
||||
}
|
||||
|
||||
/// Path of the user run configuration file for `root`.
|
||||
pub fn user_configs_path(root: &Path) -> PathBuf {
|
||||
config::config_path(root)
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
//! Process lifecycle for run configurations: spawn, stream output, stdin, stop.
|
||||
//! Process lifecycle for run configurations: spawn (on pipes, or on a pseudo-terminal
|
||||
//! for "Emulate terminal in output console"), stream output, stdin, stop.
|
||||
|
||||
use crate::utf8::OutputDecoder;
|
||||
use crate::{OutputChunk, RunConfig, RunInfo};
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{ChildStdin, Command, ExitStatus, Stdio};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
@@ -20,15 +22,39 @@ const BATCH_BYTES: usize = 64 * 1024;
|
||||
const EXIT_DRAIN: Duration = Duration::from_millis(500);
|
||||
/// Delay between SIGINT and SIGKILL on [`ProcessManager::stop`].
|
||||
const STOP_GRACE: Duration = Duration::from_secs(3);
|
||||
/// Longest a configuration's stop command (e.g. `docker stop`) may take before signals follow.
|
||||
const STOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// Finished runs kept for [`ProcessManager::list`].
|
||||
const MAX_FINISHED: usize = 20;
|
||||
/// PTY size until the console reports its own.
|
||||
const DEFAULT_PTY: (u16, u16) = (120, 30);
|
||||
|
||||
type OutputFn = Arc<dyn Fn(OutputChunk) + Send + Sync>;
|
||||
|
||||
/// Environment of a launched process: the inherited one (unless cleared) plus `vars`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct LaunchEnv {
|
||||
clear: bool,
|
||||
vars: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A configuration's stop command and where it runs.
|
||||
struct StopCommand {
|
||||
line: String,
|
||||
cwd: PathBuf,
|
||||
env: LaunchEnv,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
id: RunId,
|
||||
config_id: String,
|
||||
name: String,
|
||||
pid: Option<u32>,
|
||||
stdin: Mutex<Option<ChildStdin>>,
|
||||
stdin: Mutex<Option<Box<dyn Write + Send>>>,
|
||||
/// The PTY master of a terminal-emulated run (resize; dropped on exit).
|
||||
pty: Option<Mutex<Option<Box<dyn MasterPty + Send>>>>,
|
||||
stop: Option<StopCommand>,
|
||||
output: OutputFn,
|
||||
exited: AtomicBool,
|
||||
stopping: AtomicBool,
|
||||
}
|
||||
@@ -41,6 +67,7 @@ impl Entry {
|
||||
name: self.name.clone(),
|
||||
pid: self.pid,
|
||||
running: !self.exited.load(Ordering::Acquire),
|
||||
pty: self.pty.is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,9 +90,14 @@ enum Stream {
|
||||
Stderr,
|
||||
}
|
||||
|
||||
enum Exit {
|
||||
Pipes(std::io::Result<ExitStatus>),
|
||||
Pty(std::io::Result<portable_pty::ExitStatus>),
|
||||
}
|
||||
|
||||
enum Msg {
|
||||
Data(Stream, Vec<u8>),
|
||||
Exited(std::io::Result<ExitStatus>),
|
||||
Exited(Exit),
|
||||
}
|
||||
|
||||
/// The program and arguments actually executed, plus the echoed command line.
|
||||
@@ -112,6 +144,44 @@ pub(crate) fn invocation(config: &RunConfig, cwd: &Path) -> Invocation {
|
||||
Invocation { program, args: config.args.clone(), raw_args: false, display }
|
||||
}
|
||||
|
||||
/// "Shorten command line" for a `java` launch too long for the platform (see
|
||||
/// [`crate::java_cmdline`]): rewrites `inv` and returns the temporary file to delete on exit.
|
||||
fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResult<TempFile> {
|
||||
if inv.raw_args || !crate::java_cmdline::is_java_launcher(&inv.program) {
|
||||
return Ok(TempFile(None));
|
||||
}
|
||||
let java = if inv.program.components().count() == 1 {
|
||||
crate::which::find_executable(&inv.program.to_string_lossy(), &crate::wrap::search_path(config))
|
||||
.unwrap_or_else(|| inv.program.clone())
|
||||
} else {
|
||||
inv.program.clone()
|
||||
};
|
||||
let dir = crate::java_cmdline::default_temp_dir();
|
||||
let shortened = crate::java_cmdline::shorten(&java, &inv.args, cwd, cfg!(windows), &dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?;
|
||||
let Some(s) = shortened else { return Ok(TempFile(None)) };
|
||||
tracing::debug!(how = s.how.as_str(), file = %s.file.display(), "java command line shortened");
|
||||
let mut display = quote(config.command.trim());
|
||||
for a in &s.args {
|
||||
display.push(' ');
|
||||
display.push_str("e(a));
|
||||
}
|
||||
inv.args = s.args;
|
||||
inv.display = display;
|
||||
Ok(TempFile(Some(s.file)))
|
||||
}
|
||||
|
||||
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
|
||||
struct TempFile(Option<PathBuf>);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
if let Some(f) = self.0.take() {
|
||||
let _ = std::fs::remove_file(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `command` as one line for the platform shell: `/bin/sh -c`, or `cmd /D /S /C "…"`
|
||||
/// (`/S` strips exactly the outer quotes, so the line's own quoting survives).
|
||||
fn shell_invocation(command: &str, windows: bool, comspec: Option<String>) -> Invocation {
|
||||
@@ -154,6 +224,23 @@ fn resolve_program(command: &str, cwd: &Path, env: &BTreeMap<String, String>, wi
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// "Save console output to file": everything shown in the console is also written to `path`.
|
||||
fn tee_output(path: &Path, on_output: OutputFn) -> IdeResult<OutputFn> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = std::fs::File::create(path)
|
||||
.map_err(|e| IdeError::invalid(format!("cannot write console output to {}: {e}", path.display())))?;
|
||||
let file = Mutex::new(std::io::LineWriter::new(file));
|
||||
Ok(Arc::new(move |chunk: OutputChunk| {
|
||||
let text = match &chunk {
|
||||
OutputChunk::Stdout { text } | OutputChunk::Stderr { text } | OutputChunk::System { text } => text,
|
||||
};
|
||||
let _ = file.lock().write_all(text.as_bytes());
|
||||
on_output(chunk);
|
||||
}))
|
||||
}
|
||||
|
||||
fn resolve_cwd(root: &Path, cwd: Option<&Path>) -> PathBuf {
|
||||
match cwd {
|
||||
Some(c) if c.is_absolute() => c.to_path_buf(),
|
||||
@@ -183,7 +270,26 @@ impl ProcessManager {
|
||||
if !cwd.is_dir() {
|
||||
return Err(IdeError::not_found(format!("working directory does not exist: {}", cwd.display())));
|
||||
}
|
||||
let inv = invocation(config, &cwd);
|
||||
let mut inv = invocation(config, &cwd);
|
||||
let extras = &config.extras;
|
||||
if extras.emulate_terminal && extras.stdin_file.is_some() {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let env = launch_env(root, config)?;
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
let on_output = match extras.output_file.as_deref() {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
None => on_output,
|
||||
};
|
||||
let stop = extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand {
|
||||
line: line.to_owned(),
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
let temp = shorten_java(&mut inv, config, &cwd)?;
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
}
|
||||
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
if inv.raw_args {
|
||||
@@ -191,11 +297,21 @@ impl ProcessManager {
|
||||
} else {
|
||||
cmd.args(&inv.args);
|
||||
}
|
||||
cmd.current_dir(&cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
if matches!(config.kind.as_str(), "python" | "pytest") && !config.env.contains_key("PYTHONUNBUFFERED") {
|
||||
cmd.env("PYTHONUNBUFFERED", "1");
|
||||
}
|
||||
cmd.envs(&config.env);
|
||||
cmd.current_dir(&cwd).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let redirected = match extras.stdin_file.as_deref() {
|
||||
Some(file) => {
|
||||
let path = resolve_cwd(root, Some(Path::new(file)));
|
||||
let f = std::fs::File::open(&path)
|
||||
.map_err(|e| IdeError::not_found(format!("cannot redirect input from {}: {e}", path.display())))?;
|
||||
cmd.stdin(Stdio::from(f));
|
||||
true
|
||||
}
|
||||
None => {
|
||||
cmd.stdin(Stdio::piped());
|
||||
false
|
||||
}
|
||||
};
|
||||
apply_env(&mut cmd, &env);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
@@ -205,8 +321,7 @@ impl ProcessManager {
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
|
||||
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | ide_core::process::CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| match e.kind() {
|
||||
@@ -215,12 +330,19 @@ impl ProcessManager {
|
||||
})?;
|
||||
|
||||
let id = RunId::next();
|
||||
let stdin: Option<Box<dyn Write + Send>> = match child.stdin.take() {
|
||||
Some(pipe) if !redirected => Some(Box::new(pipe)),
|
||||
_ => None,
|
||||
};
|
||||
let entry = Arc::new(Entry {
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
pid: Some(child.id()),
|
||||
stdin: Mutex::new(child.stdin.take()),
|
||||
stdin: Mutex::new(stdin),
|
||||
pty: None,
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
exited: AtomicBool::new(false),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
@@ -253,7 +375,8 @@ impl ProcessManager {
|
||||
.name(format!("openidea-run-wait-{}", id.0))
|
||||
.spawn(move || {
|
||||
let status = child.wait();
|
||||
let _ = waiter_tx.send(Msg::Exited(status));
|
||||
drop(temp);
|
||||
let _ = waiter_tx.send(Msg::Exited(Exit::Pipes(status)));
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
|
||||
|
||||
@@ -261,6 +384,96 @@ impl ProcessManager {
|
||||
Ok(entry.info())
|
||||
}
|
||||
|
||||
/// [`Self::start`] on a pseudo-terminal: one merged output stream of raw terminal data.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_pty(
|
||||
&self,
|
||||
config: &RunConfig,
|
||||
inv: &Invocation,
|
||||
cwd: &Path,
|
||||
env: &LaunchEnv,
|
||||
stop: Option<StopCommand>,
|
||||
options: &StartOptions,
|
||||
sink: SharedSink,
|
||||
on_output: OutputFn,
|
||||
temp: TempFile,
|
||||
) -> IdeResult<RunInfo> {
|
||||
let pair = native_pty_system()
|
||||
.openpty(pty_size(DEFAULT_PTY.0, DEFAULT_PTY.1))
|
||||
.map_err(|e| IdeError::internal(format!("openpty failed: {e}")))?;
|
||||
let mut cmd = CommandBuilder::new(&inv.program);
|
||||
cmd.args(&inv.args);
|
||||
cmd.cwd(cwd);
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
for (k, v) in &env.vars {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
let mut child = pair.slave.spawn_command(cmd).map_err(|e| {
|
||||
let text = e.to_string();
|
||||
if text.contains("No such file") || text.contains("not found") {
|
||||
IdeError::unavailable(format!("command not found: {}", config.command))
|
||||
} else {
|
||||
IdeError::unavailable(format!("failed to start `{}`: {text}", config.command))
|
||||
}
|
||||
})?;
|
||||
// The child holds its own copy of the slave; dropping ours lets reads hit EOF on exit.
|
||||
drop(pair.slave);
|
||||
let reader = pair.master.try_clone_reader().map_err(|e| IdeError::internal(format!("pty reader: {e}")))?;
|
||||
let writer = pair.master.take_writer().map_err(|e| IdeError::internal(format!("pty writer: {e}")))?;
|
||||
|
||||
let id = RunId::next();
|
||||
let entry = Arc::new(Entry {
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
pid: child.process_id(),
|
||||
stdin: Mutex::new(Some(writer)),
|
||||
pty: Some(Mutex::new(Some(pair.master))),
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
exited: AtomicBool::new(false),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
self.register(entry.clone());
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let result = spawn_reader(id, Stream::Stdout, reader, tx.clone())
|
||||
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone()));
|
||||
if let Err(e) = result {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
return Err(IdeError::internal(format!("failed to start output threads: {e}")));
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name(format!("openidea-run-wait-{}", id.0))
|
||||
.spawn(move || {
|
||||
let status = child.wait();
|
||||
drop(temp);
|
||||
let _ = tx.send(Msg::Exited(Exit::Pty(status)));
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("failed to start waiter thread: {e}")))?;
|
||||
tracing::debug!(%id, config = %config.id, pid = ?entry.pid, "run started on a pty");
|
||||
Ok(entry.info())
|
||||
}
|
||||
|
||||
/// Resizes the pseudo-terminal of a terminal-emulated run.
|
||||
pub fn resize(&self, id: RunId, cols: u16, rows: u16) -> IdeResult<()> {
|
||||
let entry = self.entry(id)?;
|
||||
let Some(pty) = &entry.pty else { return Err(IdeError::invalid("the process does not run in a terminal")) };
|
||||
match pty.lock().as_ref() {
|
||||
Some(master) => {
|
||||
master.resize(pty_size(cols, rows)).map_err(|e| IdeError::internal(format!("resize failed: {e}")))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn register(&self, entry: Arc<Entry>) {
|
||||
let mut runs = self.runs.lock();
|
||||
runs.retain(|_, e| !(e.config_id == entry.config_id && e.exited.load(Ordering::Acquire)));
|
||||
@@ -294,9 +507,13 @@ impl ProcessManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Closes the process's stdin (sends EOF).
|
||||
/// Closes the process's stdin (sends EOF; on a terminal, types ^D).
|
||||
pub fn close_stdin(&self, id: RunId) -> IdeResult<()> {
|
||||
self.entry(id)?.stdin.lock().take();
|
||||
let entry = self.entry(id)?;
|
||||
if entry.pty.is_some() {
|
||||
return self.write_stdin(id, "\u{4}");
|
||||
}
|
||||
entry.stdin.lock().take();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -305,7 +522,8 @@ impl ProcessManager {
|
||||
self.stop_with_grace(id, STOP_GRACE)
|
||||
}
|
||||
|
||||
/// [`Self::stop`] with an explicit grace period before the kill.
|
||||
/// [`Self::stop`] with an explicit grace period before the kill. A configuration's
|
||||
/// stop command runs first; signals follow only if the process outlives it.
|
||||
pub fn stop_with_grace(&self, id: RunId, grace: Duration) -> IdeResult<()> {
|
||||
let entry = self.entry(id)?;
|
||||
if entry.exited.load(Ordering::Acquire) {
|
||||
@@ -317,19 +535,31 @@ impl ProcessManager {
|
||||
kill_tree(pid, true);
|
||||
return Ok(());
|
||||
}
|
||||
kill_tree(pid, false);
|
||||
if entry.stop.is_none() {
|
||||
kill_tree(pid, false);
|
||||
}
|
||||
let entry = entry.clone();
|
||||
std::thread::Builder::new()
|
||||
.name(format!("openidea-run-stop-{}", id.0))
|
||||
.spawn(move || {
|
||||
let deadline = Instant::now() + grace;
|
||||
while Instant::now() < deadline {
|
||||
if !group_alive(pid, &entry) {
|
||||
let exits_within = |limit: Duration| {
|
||||
let deadline = Instant::now() + limit;
|
||||
while Instant::now() < deadline {
|
||||
if !group_alive(pid, &entry) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
!group_alive(pid, &entry)
|
||||
};
|
||||
if let Some(stop) = &entry.stop {
|
||||
run_stop_command(stop, &entry.output);
|
||||
if exits_within(grace) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
kill_tree(pid, false);
|
||||
}
|
||||
if group_alive(pid, &entry) {
|
||||
if !exits_within(grace) {
|
||||
tracing::debug!(id = %entry.id, pid, "process ignored interrupt; killing");
|
||||
kill_tree(pid, true);
|
||||
}
|
||||
@@ -355,6 +585,90 @@ impl Drop for ProcessManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The environment a configuration's process gets on top of the inherited one: `.env`
|
||||
/// files, then the configured variables (later wins).
|
||||
fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let extras = &config.extras;
|
||||
let mut vars = if extras.env_files.is_empty() {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
let base: BTreeMap<String, String> =
|
||||
if extras.include_system_env { std::env::vars().collect() } else { BTreeMap::new() };
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
vars.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
}
|
||||
vars.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
Ok(LaunchEnv { clear: !extras.include_system_env, vars })
|
||||
}
|
||||
|
||||
fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
}
|
||||
cmd.envs(&env.vars);
|
||||
}
|
||||
|
||||
/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it
|
||||
/// and any error output to the console.
|
||||
fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
output(OutputChunk::System { text: format!("{}\n", stop.line) });
|
||||
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
if inv.raw_args {
|
||||
add_raw_args(&mut cmd, &inv.args);
|
||||
} else {
|
||||
cmd.args(&inv.args);
|
||||
}
|
||||
cmd.current_dir(&stop.cwd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
apply_env(&mut cmd, &stop.env);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
|
||||
return;
|
||||
}
|
||||
};
|
||||
let stderr = child.stderr.take().map(|mut pipe| {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
})
|
||||
});
|
||||
let deadline = Instant::now() + STOP_COMMAND_TIMEOUT;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status),
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
}
|
||||
};
|
||||
let err = stderr.and_then(|h| h.join().ok()).unwrap_or_default();
|
||||
if !status.is_some_and(|s| s.success()) && !err.trim().is_empty() {
|
||||
output(OutputChunk::Stderr { text: format!("{}\n", err.trim_end()) });
|
||||
}
|
||||
}
|
||||
|
||||
fn pty_size(cols: u16, rows: u16) -> PtySize {
|
||||
PtySize {
|
||||
cols: if cols == 0 { DEFAULT_PTY.0 } else { cols },
|
||||
rows: if rows == 0 { DEFAULT_PTY.1 } else { rows },
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn group_alive(pid: u32, _entry: &Entry) -> bool {
|
||||
// Signal 0 probes the group; it fails with ESRCH once every member is gone.
|
||||
@@ -400,7 +714,7 @@ fn kill_tree(pid: u32, _force: bool) {
|
||||
// Console children have no reliable graceful signal from outside their console.
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/T", "/F", "/PID", &pid.to_string()])
|
||||
.creation_flags(0x0800_0000)
|
||||
.creation_flags(ide_core::process::CREATE_NO_WINDOW)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
@@ -441,7 +755,7 @@ fn chunk(stream: Stream, text: String) -> OutputChunk {
|
||||
/// Merges both streams in arrival order, batching consecutive output of the same stream.
|
||||
fn spawn_pump(
|
||||
rx: mpsc::Receiver<Msg>,
|
||||
on_output: Box<dyn Fn(OutputChunk) + Send + Sync>,
|
||||
on_output: OutputFn,
|
||||
entry: Arc<Entry>,
|
||||
sink: SharedSink,
|
||||
encoding: Option<String>,
|
||||
@@ -452,7 +766,7 @@ fn spawn_pump(
|
||||
let mut pending = String::new();
|
||||
let mut pending_stream = Stream::Stdout;
|
||||
let mut batch_started: Option<Instant> = None;
|
||||
let mut status: Option<std::io::Result<ExitStatus>> = None;
|
||||
let mut status: Option<Exit> = None;
|
||||
let mut drain_deadline: Option<Instant> = None;
|
||||
|
||||
let flush = |pending: &mut String, stream: Stream, started: &mut Option<Instant>| {
|
||||
@@ -513,6 +827,9 @@ fn spawn_pump(
|
||||
let (code, message) = describe_exit(status);
|
||||
on_output(OutputChunk::System { text: format!("\n{message}\n") });
|
||||
entry.stdin.lock().take();
|
||||
if let Some(pty) = &entry.pty {
|
||||
pty.lock().take();
|
||||
}
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
tracing::debug!(id = %entry.id, ?code, "run exited");
|
||||
sink.emit(IdeEvent::RunExited { run: entry.id, code });
|
||||
@@ -543,9 +860,9 @@ fn signal_name(sig: i32) -> &'static str {
|
||||
}
|
||||
|
||||
/// IDEA wording: `Process finished with exit code 130 (interrupted by signal 2:SIGINT)`.
|
||||
fn describe_exit(status: Option<std::io::Result<ExitStatus>>) -> (Option<i32>, String) {
|
||||
fn describe_exit(status: Option<Exit>) -> (Option<i32>, String) {
|
||||
match status {
|
||||
Some(Ok(s)) => {
|
||||
Some(Exit::Pipes(Ok(s))) => {
|
||||
if let Some(code) = s.code() {
|
||||
return (Some(code), format!("Process finished with exit code {code}"));
|
||||
}
|
||||
@@ -553,23 +870,55 @@ fn describe_exit(status: Option<std::io::Result<ExitStatus>>) -> (Option<i32>, S
|
||||
{
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
if let Some(sig) = s.signal() {
|
||||
let code = 128 + sig;
|
||||
return (
|
||||
Some(code),
|
||||
format!(
|
||||
"Process finished with exit code {code} (interrupted by signal {sig}:{})",
|
||||
signal_name(sig)
|
||||
),
|
||||
);
|
||||
return signalled(sig);
|
||||
}
|
||||
}
|
||||
(None, "Process finished".to_owned())
|
||||
}
|
||||
Some(Err(e)) => (None, format!("Process finished with unknown exit status: {e}")),
|
||||
Some(Exit::Pty(Ok(s))) => match s.signal() {
|
||||
None => {
|
||||
let code = s.exit_code() as i32;
|
||||
(Some(code), format!("Process finished with exit code {code}"))
|
||||
}
|
||||
Some(name) => match signal_number(name) {
|
||||
Some(sig) => signalled(sig),
|
||||
None => (None, format!("Process finished ({name})")),
|
||||
},
|
||||
},
|
||||
Some(Exit::Pipes(Err(e)) | Exit::Pty(Err(e))) => {
|
||||
(None, format!("Process finished with unknown exit status: {e}"))
|
||||
}
|
||||
None => (None, "Process finished".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signalled(sig: i32) -> (Option<i32>, String) {
|
||||
let code = 128 + sig;
|
||||
(Some(code), format!("Process finished with exit code {code} (interrupted by signal {sig}:{})", signal_name(sig)))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn signalled(sig: i32) -> (Option<i32>, String) {
|
||||
(Some(128 + sig), format!("Process finished with exit code {}", 128 + sig))
|
||||
}
|
||||
|
||||
/// The number of a signal from the `strsignal` description portable-pty reports.
|
||||
#[cfg(unix)]
|
||||
fn signal_number(description: &str) -> Option<i32> {
|
||||
(1..32).find(|&sig| {
|
||||
// SAFETY: `strsignal` returns a pointer to a NUL-terminated C string that stays
|
||||
// valid until the next call on this thread; it is copied before that.
|
||||
let name = unsafe { libc::strsignal(sig) };
|
||||
!name.is_null() && unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy() == description
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn signal_number(_description: &str) -> Option<i32> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
|
||||
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
|
||||
let Some((program, args)) = argv.split_first() else { return false };
|
||||
let program = resolve(program, config);
|
||||
Command::new(program)
|
||||
ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
@@ -260,6 +260,8 @@ mod tests {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ fn sample() -> Vec<RunConfig> {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: Some("codelldb".into()),
|
||||
allow_parallel: true,
|
||||
extras: Default::default(),
|
||||
},
|
||||
RunConfig {
|
||||
id: "user:tests".into(),
|
||||
@@ -28,6 +30,8 @@ fn sample() -> Vec<RunConfig> {
|
||||
detected: false,
|
||||
is_test: true,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -110,3 +114,58 @@ fn invalid_file_is_reported() {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert!(err.message.contains("run.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extras_round_trip_and_local_file() {
|
||||
use ide_run::{BeforeLaunchTask, load_templates, save_templates};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut shared = sample().remove(0);
|
||||
shared.extras.folder = Some("Servers".into());
|
||||
shared.extras.params = BTreeMap::from([("mode".into(), "command".into())]);
|
||||
shared.extras.include_system_env = false;
|
||||
shared.extras.env_files = vec![".env".into(), "local.env".into()];
|
||||
shared.extras.stdin_file = Some("in.txt".into());
|
||||
shared.extras.output_file = Some("out.log".into());
|
||||
shared.extras.before_launch = vec![
|
||||
BeforeLaunchTask { kind: "build".into(), target: String::new() },
|
||||
BeforeLaunchTask { kind: "run".into(), target: "user:migrate".into() },
|
||||
];
|
||||
shared.extras.show_on_stderr = true;
|
||||
shared.extras.open_tool_window = Some(false);
|
||||
shared.extras.focus_tool_window = true;
|
||||
shared.extras.emulate_terminal = true;
|
||||
shared.extras.stop_command = Some("docker stop server".into());
|
||||
let mut local = sample().remove(1);
|
||||
local.extras.local = true;
|
||||
let mut compound = sample().remove(1);
|
||||
compound.id = "user:all".into();
|
||||
compound.name = "All".into();
|
||||
compound.kind = "compound".into();
|
||||
compound.command = String::new();
|
||||
compound.extras.compound = vec!["user:server".into(), "user:tests".into()];
|
||||
let configs = vec![shared, compound, local];
|
||||
save_user_configs(dir.path(), &configs).unwrap();
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
|
||||
|
||||
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
|
||||
assert!(!project.contains("\"user:tests\"\n"), "{project}");
|
||||
let private = fs::read_to_string(dir.path().join(".openidea/run.local.toml")).unwrap();
|
||||
assert!(private.contains("id = \"user:tests\""), "{private}");
|
||||
let ignore = fs::read_to_string(dir.path().join(".openidea/.gitignore")).unwrap();
|
||||
assert!(ignore.lines().any(|l| l == "/run.local.toml"), "{ignore}");
|
||||
|
||||
// Making it a project file moves it back.
|
||||
let mut moved = configs.clone();
|
||||
moved[2].extras.local = false;
|
||||
save_user_configs(dir.path(), &moved).unwrap();
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), moved);
|
||||
assert!(!fs::read_to_string(dir.path().join(".openidea/run.local.toml")).unwrap().contains("user:tests"));
|
||||
|
||||
// Templates share run.toml without disturbing configurations.
|
||||
let mut template = sample().remove(1);
|
||||
template.id = "template:npm".into();
|
||||
template.kind = "npm".into();
|
||||
save_templates(dir.path(), std::slice::from_ref(&template)).unwrap();
|
||||
assert_eq!(load_templates(dir.path()).unwrap(), vec![template]);
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), moved);
|
||||
}
|
||||
@@ -42,6 +42,8 @@ fn cfg(id: &str, command: &str, args: &[&str]) -> RunConfig {
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,3 +274,143 @@ fn exit_event_goes_to_the_starters_sink_only() {
|
||||
assert!(other_events.try_recv().is_err());
|
||||
assert!(h.events.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_files_system_env_and_redirects() {
|
||||
let h = harness();
|
||||
let root = h.root.path();
|
||||
std::fs::write(root.join(".env"), "FROM_FILE=file\nOVERRIDDEN=file\n").unwrap();
|
||||
std::fs::write(root.join("input.txt"), "from file\n").unwrap();
|
||||
let mut config = cfg(
|
||||
"t:extras",
|
||||
"/bin/sh",
|
||||
&["-c", "printf '%s|%s|%s|' \"$FROM_FILE\" \"$OVERRIDDEN\" \"${HOME:-unset}\"; cat"],
|
||||
);
|
||||
config.env.insert("OVERRIDDEN".into(), "config".into());
|
||||
config.extras.env_files = vec![".env".into()];
|
||||
config.extras.include_system_env = false;
|
||||
config.extras.stdin_file = Some("input.txt".into());
|
||||
config.extras.output_file = Some("logs/out.log".into());
|
||||
let (id, chunks) = start(&h, &config);
|
||||
// stdin comes from the file: writing to it is refused.
|
||||
assert!(h.pm.write_stdin(id, "x").is_err());
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0));
|
||||
assert_eq!(text(&chunks, stdout), "file|config|unset|from file\n");
|
||||
let saved = std::fs::read_to_string(root.join("logs/out.log")).unwrap();
|
||||
assert!(saved.contains("file|config|unset|from file\n"), "{saved}");
|
||||
assert!(saved.contains("Process finished with exit code 0"), "{saved}");
|
||||
|
||||
// With the system environment, HOME is inherited.
|
||||
config.extras.include_system_env = true;
|
||||
config.extras.stdin_file = None;
|
||||
config.extras.output_file = None;
|
||||
config.args = vec!["-c".into(), "printf '%s' \"${HOME:+set}\"".into()];
|
||||
let (id, chunks) = start(&h, &config);
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0));
|
||||
assert_eq!(text(&chunks, stdout), "set");
|
||||
|
||||
config.extras.env_files = vec!["missing.env".into()];
|
||||
assert!(h.pm.start(root, &config, &StartOptions::default(), h.sink.clone(), Box::new(|_| {})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_is_a_tty_with_input_resize_and_exit_code() {
|
||||
let h = harness();
|
||||
let script = "[ -t 1 ] && echo tty-yes; echo \"term=$TERM\"; read line; echo \"got:$line\"; stty size; exit 3";
|
||||
let mut config = cfg("t:pty", "/bin/sh", &["-c", script]);
|
||||
config.extras.emulate_terminal = true;
|
||||
let (id, chunks) = start(&h, &config);
|
||||
assert!(h.pm.list().iter().any(|r| r.id == id && r.pty));
|
||||
wait_for(&chunks, "term=xterm-256color");
|
||||
h.pm.resize(id, 100, 40).unwrap();
|
||||
h.pm.write_stdin(id, "hello\r").unwrap();
|
||||
let out = wait_for(&chunks, "40 100");
|
||||
assert!(out.contains("tty-yes"), "{out:?}");
|
||||
assert!(out.contains("got:hello"), "{out:?}");
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(3));
|
||||
assert!(text(&chunks, system).contains("Process finished with exit code 3"));
|
||||
// Stdout and stderr share the terminal.
|
||||
assert_eq!(text(&chunks, stderr), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_stop_reports_the_signal() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:pty-stop", "/bin/sh", &["-c", "echo ready; sleep 30"]);
|
||||
config.extras.emulate_terminal = true;
|
||||
let (id, chunks) = start(&h, &config);
|
||||
wait_for(&chunks, "ready");
|
||||
h.pm.stop(id).unwrap();
|
||||
let code = wait_exit(&h, id, Duration::from_secs(10));
|
||||
assert_eq!(code, Some(130), "{:?}", text(&chunks, system));
|
||||
assert!(text(&chunks, system).contains("SIGINT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_terminal_refuses_input_redirection() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:pty-stdin", "/bin/cat", &[]);
|
||||
config.extras.emulate_terminal = true;
|
||||
config.extras.stdin_file = Some("input.txt".into());
|
||||
assert!(h.pm.start(h.root.path(), &config, &StartOptions::default(), h.sink.clone(), Box::new(|_| {})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipe_runs_cannot_be_resized() {
|
||||
let h = harness();
|
||||
let (id, _chunks) = start(&h, &cfg("t:pipes", "/bin/sh", &["-c", "sleep 5"]));
|
||||
assert!(!h.pm.list().iter().find(|r| r.id == id).unwrap().pty);
|
||||
assert!(h.pm.resize(id, 80, 24).is_err());
|
||||
h.pm.stop(id).unwrap();
|
||||
wait_exit(&h, id, Duration::from_secs(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_command_runs_first_with_the_run_environment() {
|
||||
let h = harness();
|
||||
let mut config = cfg("t:stop-cmd", "/bin/sh", &["-c", "echo ready; sleep 30"]);
|
||||
config.env.insert("OPENIDEA_MARKER".into(), "stopped".into());
|
||||
config.extras.stop_command = Some("touch \"$OPENIDEA_MARKER\"".into());
|
||||
let (id, chunks) = start(&h, &config);
|
||||
wait_for(&chunks, "ready");
|
||||
h.pm.stop_with_grace(id, Duration::from_millis(200)).unwrap();
|
||||
// `sleep` ignores nothing: the signals that follow the stop command end it.
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(130));
|
||||
assert!(h.root.path().join("stopped").exists(), "stop command did not run");
|
||||
assert!(text(&chunks, system).contains("touch \"$OPENIDEA_MARKER\""));
|
||||
}
|
||||
|
||||
/// A `java` command line past the platform limit starts through a pathing jar
|
||||
/// (JDK 8) or an `@argfile` (JDK 9+), which is deleted once the JVM exits.
|
||||
#[test]
|
||||
fn long_java_classpath_is_shortened() {
|
||||
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return };
|
||||
let (java, javac) = (home.join("bin/java"), home.join("bin/javac"));
|
||||
if !javac.is_file() {
|
||||
return;
|
||||
}
|
||||
let h = harness();
|
||||
let classes = h.root.path().join("out classes");
|
||||
std::fs::create_dir_all(classes.join("p")).unwrap();
|
||||
let src = h.root.path().join("Main.java");
|
||||
std::fs::write(&src, "package p; public class Main { public static void main(String[] a) { System.out.println(\"hello \" + a[0]); } }").unwrap();
|
||||
let ok = std::process::Command::new(&javac).arg("-d").arg(&classes).arg(&src).status().unwrap().success();
|
||||
assert!(ok, "javac failed");
|
||||
let mut cp: Vec<String> = (0..3_000).map(|i| format!("/no/such/repository/lib-{i}/1.0/lib-{i}-1.0.jar")).collect();
|
||||
cp.push(classes.to_string_lossy().into_owned());
|
||||
let cp = cp.join(":");
|
||||
assert!(cp.len() > ide_run::java_cmdline::UNIX_LIMIT);
|
||||
let config = cfg("t:java", &java.to_string_lossy(), &["-cp", &cp, "p.Main", "world"]);
|
||||
let (id, chunks) = start(&h, &config);
|
||||
assert_eq!(wait_exit(&h, id, Duration::from_secs(30)), Some(0), "{}", text(&chunks, stderr));
|
||||
assert_eq!(text(&chunks, stdout).trim(), "hello world");
|
||||
let echo = text(&chunks, system);
|
||||
let first = echo.lines().next().unwrap();
|
||||
assert!(first.len() < 1_000, "{first}");
|
||||
let file = first
|
||||
.split(' ')
|
||||
.map(|a| a.trim_matches('\'').trim_start_matches('@'))
|
||||
.find(|a| a.contains("openidea-classpath"))
|
||||
.unwrap_or_else(|| panic!("no pathing jar / argfile in {first}"));
|
||||
assert!(!Path::new(file).exists(), "{file} not deleted");
|
||||
}
|
||||
Loaded 100 of 1047 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача