дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
94
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cc83c09e54 | ||
|
|
ef1b159544 | ||
|
|
7bfba926c2 | ||
|
|
1042f5fa56 | ||
|
|
fdad01034c | ||
|
|
6dddfde3bc | ||
|
|
0324bc368d | ||
|
|
96c6e65aad | ||
|
|
6eebd895ea | ||
|
|
cfad729dbd | ||
|
|
bd905c6689 | ||
|
|
7138becb3a | ||
|
|
6f7d2ce34d | ||
|
|
719961e34e | ||
|
|
11c432fc23 | ||
|
|
0b8698e47c | ||
|
|
f595a7abf0 | ||
|
|
fe7fa7d505 | ||
|
|
e998e2ca8e | ||
|
|
18424b322f | ||
|
|
daee26e680 | ||
|
|
5886e055b4 | ||
|
|
8d4b360933 | ||
|
|
f6704b53f6 | ||
|
|
91da88d09d | ||
|
|
5ab91245dd | ||
|
|
fb063c1f84 | ||
|
|
f926390d2e | ||
|
|
9b66744e72 | ||
|
|
071f768635 | ||
|
|
bbe9cf7a86 | ||
|
|
c10d2f0732 | ||
|
|
ec02a121e9 | ||
|
|
12eb2db641 | ||
|
|
2735d45d7e | ||
|
|
60262c92ba | ||
|
|
ca472742bf | ||
|
|
023408eb26 | ||
|
|
92c0e304cd | ||
|
|
3d534b447d | ||
|
|
89a3359aaf | ||
|
|
d88c4c87b6 | ||
|
|
197c7d6141 | ||
|
|
c61bb2b56d | ||
|
|
b9429858a6 | ||
|
|
c1e9707c7e | ||
|
|
a483ea77f4 | ||
|
|
de36b46660 | ||
|
|
5918605b2b | ||
|
|
f69d394480 | ||
|
|
eb078a0a19 | ||
|
|
5a884d7cba | ||
|
|
2ba2f33232 | ||
|
|
c9bb5a3169 | ||
|
|
bfbc70a438 | ||
|
|
e74edbcedc | ||
|
|
ebeb6476eb | ||
|
|
b8b245da5f | ||
|
|
5aeadcc888 | ||
|
|
edc750174b | ||
|
|
cdff357fdd | ||
|
|
de971848ab | ||
|
|
90cb56e9f8 | ||
|
|
baa0171d8a | ||
|
|
0d493fb515 | ||
|
|
a56add66ea | ||
|
|
2d568980c5 | ||
|
|
7920a4985e | ||
|
|
d6c7e7edc4 | ||
|
|
b1c69d1991 | ||
|
|
a869acdca2 | ||
|
|
fb3a037b7e | ||
|
|
dfaa784513 | ||
|
|
67e58f61b6 | ||
|
|
e75deb11c0 | ||
|
|
94b67515a5 | ||
|
|
a0b2678466 | ||
|
|
e3dc7e950b | ||
|
|
0a53c7b864 | ||
|
|
d4447c7aba | ||
|
|
9740edbfd4 | ||
|
|
b49b0e5c98 | ||
|
|
c88e379c8b | ||
|
|
db63c6c93b | ||
|
|
54a7962043 | ||
|
|
7c3b9824e6 | ||
|
|
0450de5321 | ||
|
|
fadd2a78aa | ||
|
|
53f5ecb233 | ||
|
|
0b079af75d | ||
|
|
6dab294dbf | ||
|
|
fc0ca1e029 | ||
|
|
fe024713da | ||
|
|
42c7834023 |
No files matched your search
+2
-21
@@ -149,27 +149,8 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
|
||||
Створено
+50
-48
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4172,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4184,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4195,7 +4195,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4213,7 +4213,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4227,7 +4227,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4238,7 +4238,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4249,7 +4249,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4271,7 +4271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4284,7 +4284,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4313,7 +4313,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4352,7 +4352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4365,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4379,7 +4379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4399,7 +4399,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4410,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4422,7 +4422,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4435,7 +4435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4454,7 +4454,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4530,7 +4530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4549,7 +4549,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4572,7 +4572,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4584,7 +4584,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4600,7 +4600,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4609,7 +4609,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4620,7 +4620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4679,7 +4679,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4708,7 +4708,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4727,7 +4727,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4748,7 +4748,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4770,7 +4770,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4784,7 +4784,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4804,7 +4804,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4828,7 +4828,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4844,7 +4844,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4870,7 +4870,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4891,7 +4891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4904,7 +4904,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4929,7 +4929,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4942,7 +4942,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4957,7 +4957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4971,7 +4971,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4984,10 +4984,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
"libc",
|
||||
@@ -5005,7 +5007,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5027,7 +5029,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5054,7 +5056,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5070,7 +5072,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6699,7 +6701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -751,3 +751,47 @@ async fn stop_ends_a_turn_left_running_only_by_background_shells() {
|
||||
assert_eq!(res["stopReason"], "cancelled");
|
||||
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skills() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"skills": {
|
||||
"copilotSkillDirectories": ["/farm/task-1/copilot"],
|
||||
"copilotDisabledSkills": ["muted", "off"],
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["skillDirectories"], json!(["/farm/task-1/copilot"]), "{method}: {params}");
|
||||
assert_eq!(params["disabledSkills"], json!(["muted", "off"]), "{method}: {params}");
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
@@ -649,11 +649,14 @@ pub struct Delivery {
|
||||
|
||||
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
|
||||
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
|
||||
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
|
||||
/// (its own folders of the working directory and the home) are not staged again: it already
|
||||
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
|
||||
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
|
||||
/// agent gets nothing here: its `/` menu is filtered instead.
|
||||
/// the CLI's tree — and reports what to hand the CLI. For Claude Code and Codex, skills
|
||||
/// the CLI discovers natively (its own folders of the working directory and the home) are
|
||||
/// not staged again so the CLI does not see duplicates. For Copilot (`copilot --headless`),
|
||||
/// config discovery is off by default (enabling it would also auto-load workspace `.mcp.json`
|
||||
/// outside OpenIDEA's MCP approvals), so every active `Auto` skill is staged into
|
||||
/// `skillDirectories`. Skills `off` are never staged; the CLI's native disable (where it has
|
||||
/// one) receives their names or paths. An ACP agent gets nothing here: its `/` menu is
|
||||
/// filtered instead.
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
@@ -705,7 +708,7 @@ pub fn stage(
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
|
||||
if let Some(tree) = copilot_tree.as_ref() {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
|
||||
@@ -794,29 +797,6 @@ fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
|
||||
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".copilot"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
@@ -1232,8 +1212,9 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
// Copilot headless does not run disk config discovery unless explicitly opted in, so
|
||||
// every active `Auto` skill — including `.github/skills`, `.agents/skills`, `~/.agents/skills`,
|
||||
// `~/.copilot/installed-plugins`, `.openidea/skills`, and `~/.codex/skills` — must be staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
@@ -1241,6 +1222,13 @@ mod tests {
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
let copilot_plugin_skills = home.join(".copilot/installed-plugins/_direct/azure/skills");
|
||||
std::fs::create_dir_all(copilot_plugin_skills.join("azure-ai")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("azure-ai", AgentSkillSource::CopilotUser, &copilot_plugin_skills),
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1249,7 +1237,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -1259,8 +1247,8 @@ mod tests {
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"],
|
||||
"all active Auto skills (including .github, .agents, ~/.agents, and ~/.copilot/installed-plugins) are staged for Copilot headless"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
@@ -1276,12 +1264,12 @@ mod tests {
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
// A worktree task also stages all active workspace, user, and plugin skills.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
assert_eq!(copilot_staged, ["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"]);
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1289,7 +1277,7 @@ mod tests {
|
||||
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
|
||||
assert_eq!(settings["skillOverrides"]["off"], "off");
|
||||
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill.
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill on disk.
|
||||
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
|
||||
let restated = resolve(
|
||||
states.iter().map(|s| s.skill.clone()).collect(),
|
||||
@@ -1299,10 +1287,14 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["azure-ai", "codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
let delivery = stage(&farm, "copilot", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&farm.join("copilot")), ["azure-ai", "codexy", "gh", "ideonly", "tdd"]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["lint", "muted", "off"]);
|
||||
|
||||
// An ACP agent gets no farm.
|
||||
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery, Delivery::default());
|
||||
|
||||
@@ -236,10 +236,13 @@ pub fn plan(
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
Some(f) => {
|
||||
let scope = model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir))))
|
||||
let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir))));
|
||||
let gradle_dirs = model.gradle.iter().flat_map(|g| {
|
||||
std::iter::once(normalize(&root.join(&g.dir)))
|
||||
.chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir))))
|
||||
});
|
||||
let scope = maven_dirs
|
||||
.chain(gradle_dirs)
|
||||
.filter(|dir| f.starts_with(dir))
|
||||
.max_by_key(|dir| dir.components().count())
|
||||
.unwrap_or_else(|| root.to_path_buf());
|
||||
@@ -251,10 +254,13 @@ pub fn plan(
|
||||
None => None,
|
||||
};
|
||||
let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf());
|
||||
// A folder of sibling projects has no build file itself; its Maven projects are built one by one.
|
||||
let system = detect_dir(&dir, model, root)
|
||||
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
|
||||
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
|
||||
let direct_system = detect_dir(&dir, model, root);
|
||||
let has_gradle = !model.gradle.is_empty();
|
||||
let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty());
|
||||
// A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it.
|
||||
let system = direct_system
|
||||
.or(has_gradle.then_some(BuildSystem::Gradle))
|
||||
.or(has_maven.then_some(BuildSystem::Maven))
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
|
||||
})?;
|
||||
@@ -267,17 +273,26 @@ pub fn plan(
|
||||
),
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven {
|
||||
let mut combined = gradle_steps(root, model, kind, None)?;
|
||||
combined.extend(maven_steps(root, model, kind, None, cache, cancel)?);
|
||||
combined
|
||||
} else {
|
||||
match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many); a directory target builds itself.
|
||||
BuildSystem::Go => {
|
||||
let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir);
|
||||
go_steps(pkg, kind)?
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
};
|
||||
Ok(BuildPlan { system, title, steps })
|
||||
}
|
||||
@@ -1912,4 +1927,92 @@ mod tests {
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test"));
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("polyglot");
|
||||
write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n");
|
||||
write(
|
||||
&root,
|
||||
"fixtures/java-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>app</artifactId><version>1</version></project>",
|
||||
);
|
||||
write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
|
||||
let maven = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/java-app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven.system, BuildSystem::Maven);
|
||||
assert_eq!(maven.steps.len(), 1);
|
||||
assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app"));
|
||||
|
||||
let gradle = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/kotlin-gradle")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gradle.system, BuildSystem::Gradle);
|
||||
assert_eq!(gradle.steps.len(), 1);
|
||||
assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle"));
|
||||
|
||||
let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(cargo.system, BuildSystem::Cargo);
|
||||
assert_eq!(cargo.steps[0].cwd, root);
|
||||
|
||||
// Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project.
|
||||
let mixed = tmp.path().join("mixed");
|
||||
write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n");
|
||||
write(
|
||||
&mixed,
|
||||
"maven-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>m</artifactId><version>1</version></project>",
|
||||
);
|
||||
let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None);
|
||||
let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, mixed.join("gradle-app"));
|
||||
assert_eq!(all.steps[1].cwd, mixed.join("maven-app"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_directory_target_builds_that_package_without_stepping_to_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("go-app");
|
||||
write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n");
|
||||
write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n");
|
||||
|
||||
let pkg = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("cmd/server")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(pkg.system, BuildSystem::Go);
|
||||
assert_eq!(pkg.steps[0].cwd, root);
|
||||
assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]);
|
||||
|
||||
let whole =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
}
|
||||
@@ -364,9 +364,9 @@ pub fn parse_reported_projects(output: &str) -> Vec<ReportedProject> {
|
||||
output.lines().filter_map(|l| serde_json::from_str(l.trim_end().strip_prefix(MODEL_LINE)?).ok()).collect()
|
||||
}
|
||||
|
||||
/// Source roots of the reported source sets: `(absolute folder, is test, is resources)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot)> = Vec::new();
|
||||
/// Source roots of the reported source sets: `(absolute folder, role, absolute folder of its project)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot, PathBuf)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot, PathBuf)> = Vec::new();
|
||||
for p in reported {
|
||||
for set in &p.source_sets {
|
||||
let (src, res) = if set.test {
|
||||
@@ -377,14 +377,14 @@ pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, Repo
|
||||
for (dir, kind) in set.src.iter().map(|d| (d, src)).chain(set.res.iter().map(|d| (d, res))) {
|
||||
let dir = PathBuf::from(dir);
|
||||
// A folder shared by `main` and another set is `main`'s, as in IDEA.
|
||||
if !out.iter().any(|(d, _)| *d == dir) {
|
||||
out.push((dir, kind));
|
||||
if !out.iter().any(|(d, _, _)| *d == dir) {
|
||||
out.push((dir, kind, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// IDEA excludes the build folder of every module.
|
||||
if let Some(b) = &p.build_dir {
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded));
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -517,7 +517,15 @@ impl JavaBuild<'_> {
|
||||
let Some(project) = project_at(path) else {
|
||||
return Ok(Built::Unsupported(format!("no Java project holds {}", path.display())));
|
||||
};
|
||||
launch_projects(&reactor_model, project, true)
|
||||
let mut all: Vec<(&ProjectModel, bool)> = Vec::new();
|
||||
for member in reactor_model.projects.iter().filter(|p| p.dir.starts_with(&project.dir)) {
|
||||
for set in launch_projects(&reactor_model, member, true) {
|
||||
if !all.iter().any(|(p, t)| p.dir == set.0.dir && *t == set.1) {
|
||||
all.push(set);
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
Target::File(file) => {
|
||||
let Some(project) = project_at(file) else {
|
||||
|
||||
@@ -84,6 +84,8 @@ impl Fixture {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let build = [
|
||||
// A persistent Gradle daemon can keep the fixture's output pipes open on Windows.
|
||||
("gradle.properties", "org.gradle.daemon=false\n"),
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
@@ -258,6 +260,12 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert_eq!(f.build(Target::Project).failure, None);
|
||||
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
|
||||
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
|
||||
|
||||
// Build Module on the root aggregator compiles every submodule under it.
|
||||
f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Module(&f.root)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -164,12 +164,13 @@ pub fn maven_external_roots(
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// Source, resource and build folders of the last Gradle sync, absolute.
|
||||
/// Source, resource and build folders of the last Gradle sync, with the folder of the
|
||||
/// project reporting each; all absolute.
|
||||
pub fn gradle_source_roots(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot)> {
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
@@ -28,6 +28,8 @@ pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// How long output may keep arriving after the child exits before the run stops reading it.
|
||||
const OUTPUT_AFTER_EXIT: Duration = Duration::from_secs(1);
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
@@ -236,6 +238,10 @@ fn run_with_env_capture(
|
||||
let mut tail_bytes = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut truncated = false;
|
||||
// When the child exited. A process it left running (a Gradle daemon on Windows) can inherit
|
||||
// the pipes and keep them open long after; the run ends once they have been quiet this long.
|
||||
let mut exited: Option<Instant> = None;
|
||||
let mut pipes_held = false;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
@@ -244,6 +250,9 @@ fn run_with_env_capture(
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
if exited.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
on_line(stream, &line);
|
||||
if !bounded {
|
||||
// The caller parses a complete model from `text`, so keep every line.
|
||||
@@ -274,12 +283,26 @@ fn run_with_env_capture(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => match exited {
|
||||
Some(at) if at.elapsed() >= OUTPUT_AFTER_EXIT => {
|
||||
pipes_held = true;
|
||||
break;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if child.try_wait()?.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
// Readers still blocked on a pipe that a leftover process holds end with it, on their own.
|
||||
if !pipes_held {
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let mut text = head;
|
||||
@@ -392,6 +415,31 @@ mod tests {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_left_holding_the_pipes_does_not_hold_the_run() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// The background child inherits stdout and stderr, as a Gradle daemon can on Windows.
|
||||
let script = "echo built; (sleep 30) & echo done >&2";
|
||||
let started = Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let out = run(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, l| lines.push(l.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
assert!(out.success);
|
||||
lines.sort();
|
||||
assert_eq!(lines, ["built", "done"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_kills_grandchildren() {
|
||||
if cfg!(windows) {
|
||||
|
||||
@@ -807,12 +807,13 @@ mod tests {
|
||||
Some(gradle::ProcessedResources { task: "processResources".into(), dir: "/p/build/resources/main".into() })
|
||||
);
|
||||
let src = |p: &str| PathBuf::from(core_src(p));
|
||||
let core = PathBuf::from(format!("{b}/modules/core"));
|
||||
assert_eq!(
|
||||
gradle::reported_source_roots(&projects),
|
||||
[
|
||||
(src("main/java"), gradle::ReportedRoot::Source),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources),
|
||||
(src("test/java"), gradle::ReportedRoot::Test),
|
||||
(src("main/java"), gradle::ReportedRoot::Source, core.clone()),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources, core.clone()),
|
||||
(src("test/java"), gradle::ReportedRoot::Test, core),
|
||||
]
|
||||
);
|
||||
let mut model = gradle::load(&root).unwrap();
|
||||
|
||||
@@ -58,9 +58,10 @@ pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
imp::set_text(text, owner)
|
||||
}
|
||||
|
||||
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
|
||||
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
|
||||
/// open the clipboard; empty when Windows holds none. Call on the main thread on
|
||||
/// macOS; Linux reads it asynchronously through GTK in the app.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
@@ -255,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let units: Vec<u16> =
|
||||
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
@@ -310,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -394,6 +404,19 @@ mod imp {
|
||||
image
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
|
||||
unsafe { CloseClipboard() };
|
||||
text
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
|
||||
@@ -890,6 +913,16 @@ mod tests {
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_stops_at_the_nul() {
|
||||
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
// No terminator, and a stray odd byte, still read the whole text.
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
bytes.push(7);
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! How often the terminal and Run console pumps hand output to the UI, from
|
||||
//! Settings › Tools › Terminal › Max FPS (#5897). The frontend paints at most that
|
||||
//! often anyway; batching at half its frame interval keeps a fresh batch ready for
|
||||
//! every frame while cutting the IPC events (and their handling on the UI thread)
|
||||
//! that would only be buffered there.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Frames per second; 0 is Unlimited.
|
||||
static MAX_FPS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Applies the `terminal.maxFps` setting: `"unlimited"` or a number of frames per second.
|
||||
/// Running sessions pick it up at their next batch.
|
||||
pub fn set_max_fps(setting: &str) {
|
||||
MAX_FPS.store(setting.trim().parse::<u32>().unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The batch interval for a pump whose Unlimited interval is `unlimited`.
|
||||
pub fn batch_interval(unlimited: Duration) -> Duration {
|
||||
interval_for(MAX_FPS.load(Ordering::Relaxed), unlimited)
|
||||
}
|
||||
|
||||
/// Half the paint interval, within 4–200 ms, and never faster than the Unlimited rate.
|
||||
fn interval_for(fps: u32, unlimited: Duration) -> Duration {
|
||||
if fps == 0 {
|
||||
return unlimited;
|
||||
}
|
||||
Duration::from_millis((500 / u64::from(fps)).clamp(4, 200)).max(unlimited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interval_is_half_the_frame_and_clamped() {
|
||||
let terminal = Duration::from_millis(4);
|
||||
let run = Duration::from_millis(8);
|
||||
let ms = |fps, unlimited| interval_for(fps, unlimited).as_millis();
|
||||
assert_eq!(ms(0, terminal), 4, "Unlimited keeps the pump's own rate");
|
||||
assert_eq!(ms(0, run), 8);
|
||||
assert_eq!([60, 30, 15, 10, 5].map(|fps| ms(fps, terminal)), [8, 16, 33, 50, 100]);
|
||||
assert_eq!(ms(1, terminal), 200, "upper bound");
|
||||
assert_eq!(ms(1000, terminal), 4, "lower bound");
|
||||
assert_eq!(ms(1000, run), 8, "never faster than Unlimited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_values_parse_and_unknown_means_unlimited() {
|
||||
set_max_fps("30");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 16);
|
||||
set_max_fps("unlimited");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 4);
|
||||
set_max_fps("fast");
|
||||
assert_eq!(batch_interval(Duration::from_millis(8)).as_millis(), 8);
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,6 @@ pub struct AgentSettings {
|
||||
pub show_usage_limits: bool,
|
||||
/// What the session has cost so far, as the agent reports it.
|
||||
pub show_cost: bool,
|
||||
/// A finished turn's work folds into one line under its message, leaving the reply.
|
||||
pub fold_turns: bool,
|
||||
/// Streaming text is revealed at a steady pace rather than chunk by chunk.
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
@@ -145,7 +143,6 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
@@ -420,10 +417,10 @@ impl Default for McpServerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
|
||||
/// unreachable.
|
||||
/// Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow
|
||||
/// or unreachable.
|
||||
///
|
||||
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// A mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
|
||||
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
|
||||
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
|
||||
@@ -431,8 +428,9 @@ impl Default for McpServerSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolDownloadSettings {
|
||||
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
|
||||
/// every download on its official host.
|
||||
/// Proxy prefixes prepended to `https://github.com/…` archive addresses only, separated by
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
}
|
||||
|
||||
@@ -826,6 +824,8 @@ pub struct AppearanceSettings {
|
||||
pub contrast_scrollbars: bool,
|
||||
/// Adjust colours for red-green vision deficiency.
|
||||
pub red_green_vision: bool,
|
||||
/// Turn off animations and transitions (also on when the OS asks for reduced motion).
|
||||
pub reduce_motion: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
@@ -966,6 +966,7 @@ impl Default for AppearanceSettings {
|
||||
ui_font_fallback: String::new(),
|
||||
contrast_scrollbars: false,
|
||||
red_green_vision: false,
|
||||
reduce_motion: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
@@ -2120,14 +2121,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn agent_meters_default_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true}}"#).unwrap();
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true,"foldTurns":true}}"#).unwrap();
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
assert!(!old.agents.fold_turns);
|
||||
assert!(!Settings::default().agents.show_cost);
|
||||
assert!(!Settings::default().agents.fit_window_width);
|
||||
assert!(!Settings::default().agents.fold_turns);
|
||||
let mut settings = Settings::default();
|
||||
settings.agents.show_usage_limits = false;
|
||||
settings.agents.fit_window_width = true;
|
||||
|
||||
@@ -450,6 +450,21 @@ fn no_session(s: DebugSessionId) -> IdeError {
|
||||
IdeError::not_found(format!("no debug session {}", s.0))
|
||||
}
|
||||
|
||||
/// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose
|
||||
/// `connect` is its own client listener: the child session is another connection to the running
|
||||
/// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server.
|
||||
fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> {
|
||||
configuration.get("subProcessId")?;
|
||||
let connect = configuration.get("connect")?;
|
||||
let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?;
|
||||
let mut spec = spec.clone();
|
||||
if let Some(host) = connect.get("host").and_then(Value::as_str) {
|
||||
let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
spec.server_host = (!loopback).then(|| host.to_owned());
|
||||
}
|
||||
Some((spec, port))
|
||||
}
|
||||
|
||||
/// The name of a child session: the adapter's, or the parent's when it gives none. js-debug
|
||||
/// names a browser page's session after the page the browser starts on, before the URL
|
||||
/// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged.
|
||||
@@ -1032,6 +1047,13 @@ impl DebugManager {
|
||||
if let Some(obj) = configuration.as_object_mut() {
|
||||
obj.entry("request").or_insert_with(|| request.clone().into());
|
||||
}
|
||||
let (spec, port) = match parent.port {
|
||||
Some(port) => (parent.spec.clone(), Some(port)),
|
||||
None => match subprocess_connection(&configuration, &parent.spec) {
|
||||
Some((spec, port)) => (spec, Some(port)),
|
||||
None => (parent.spec.clone(), None),
|
||||
},
|
||||
};
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
parent.owner.clone(),
|
||||
@@ -1040,8 +1062,8 @@ impl DebugManager {
|
||||
Some(parent.id),
|
||||
request,
|
||||
configuration,
|
||||
parent.spec.clone(),
|
||||
parent.port,
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -1017,6 +1017,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
|
||||
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
|
||||
/// in `input()` never sees its line end (#6041).
|
||||
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
@@ -1030,7 +1037,7 @@ pub(crate) struct ProgramTerminal {
|
||||
|
||||
impl ProgramTerminal {
|
||||
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
|
||||
self.writer.write(text.as_bytes())
|
||||
self.writer.write(as_typed(text).as_bytes())
|
||||
}
|
||||
|
||||
/// The program's process id while it runs.
|
||||
@@ -1386,6 +1393,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn typed_input_ends_lines_with_enter() {
|
||||
assert_eq!(super::as_typed("42\n"), "42\r");
|
||||
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
|
||||
assert_eq!(super::as_typed("no newline"), "no newline");
|
||||
}
|
||||
|
||||
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -122,6 +122,8 @@ struct Script {
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
/// Send a `startDebugging` reverse request (child session) when a non-child `launch` arrives.
|
||||
start_debugging: bool,
|
||||
/// The child's `startDebugging` arguments instead of a js-debug style `launch`.
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
@@ -201,6 +203,7 @@ impl Default for Script {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
debuggee_pid: None,
|
||||
@@ -365,10 +368,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
);
|
||||
}
|
||||
if script.start_debugging && msg["arguments"]["isChild"] != true {
|
||||
send!(
|
||||
let arguments = script.child_request.clone().unwrap_or_else(
|
||||
// Like js-debug, the child's configuration repeats the launch's `type`.
|
||||
json!({"type": "request", "command": "startDebugging", "arguments": {"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}})
|
||||
|| json!({"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}),
|
||||
);
|
||||
send!(json!({"type": "request", "command": "startDebugging", "arguments": arguments}));
|
||||
}
|
||||
if script.pending_startup != Some(false) {
|
||||
tokio::time::sleep(script.initialized_delay).await;
|
||||
@@ -1193,6 +1197,46 @@ async fn child_of(h: &Harness, parent: DebugSessionId) -> DebugSessionId {
|
||||
panic!("no child session of {parent:?}");
|
||||
}
|
||||
|
||||
/// debugpy's subprocess (`subProcess: true`): an `attach` whose `connect` is the running adapter's
|
||||
/// client listener, so the child session connects there instead of starting another adapter.
|
||||
#[tokio::test]
|
||||
async fn a_debugpy_subprocess_connects_to_the_running_adapter() {
|
||||
/// Each launch's reused port and remote host.
|
||||
type Launches = Arc<Mutex<Vec<(Option<u16>, Option<String>)>>>;
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
launches: Launches,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.launches.lock().push((reuse, spec.server_host.clone()));
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let child = |host: &str| {
|
||||
json!({"request": "attach", "configuration": {"name": "Subprocess 42", "isChild": true, "subProcessId": 42,
|
||||
"connect": {"host": host, "port": 51234}}})
|
||||
};
|
||||
for (host, server_host) in [("127.0.0.1", None), ("10.0.0.5", Some("10.0.0.5".to_owned()))] {
|
||||
let launches: Launches = Arc::default();
|
||||
let script = Script { start_debugging: true, child_request: Some(child(host)), ..Script::default() };
|
||||
let launcher =
|
||||
CaptureLauncher { inner: FakeLauncher { log: Arc::default(), script }, launches: launches.clone() };
|
||||
let manager =
|
||||
DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let (owner, _) = recording_owner("main");
|
||||
let parent = manager.start(config(), owner).await.unwrap();
|
||||
for _ in 0..200 {
|
||||
if launches.lock().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(*launches.lock(), [(None, None), (Some(51234), server_host)], "{host}");
|
||||
manager.stop(parent).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_browser_page_session_has_the_page_capability() {
|
||||
let h = harness(Script { start_debugging: true, ..Script::default() });
|
||||
|
||||
@@ -135,7 +135,7 @@ impl Context {
|
||||
}
|
||||
|
||||
macro_rules! sqlx_pool {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $initialize:ident, $unfinished:expr) => {
|
||||
pub struct $manager {
|
||||
options: $options,
|
||||
init: Arc<Vec<String>>,
|
||||
@@ -164,41 +164,28 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
}
|
||||
|
||||
impl $manager {
|
||||
async fn initialize(&self, mut conn: $connection) -> Result<$handle, sqlx::Error> {
|
||||
let context = Context::new($initialize(&self.options, &mut conn, &self.init).await?);
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ManageConnection for $manager {
|
||||
type Connection = $handle;
|
||||
type Error = sqlx::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
tokio::time::timeout(self.timeout, async {
|
||||
let mut conn = self.options.connect().await?;
|
||||
let context_sql = |value: Option<String>| {
|
||||
value.map(|v| {
|
||||
if $driver == DbDriver::Postgres {
|
||||
format!("SET search_path TO {v}")
|
||||
} else {
|
||||
crate::sql::use_schema($driver, &v).expect("switchable driver")
|
||||
}
|
||||
})
|
||||
};
|
||||
for sql in self.init.iter() {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
|
||||
}
|
||||
$(if !self.init.is_empty() {
|
||||
self.options.$after_init(&mut conn).await?;
|
||||
})?
|
||||
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
|
||||
let context = Context::new(context_sql(row.try_get(0)?));
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
tokio::time::timeout(self.timeout, async { self.initialize(self.options.connect().await?).await })
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -206,16 +193,24 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
|
||||
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
|
||||
conn.conn.is_none()
|
||||
conn.conn.is_none() || ($unfinished)(conn)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PgReadOnly {
|
||||
Off,
|
||||
Session,
|
||||
Transaction,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PostgresOptions {
|
||||
connection: PgConnectOptions,
|
||||
read_only: bool,
|
||||
read_only: PgReadOnly,
|
||||
local_settings: Arc<[String]>,
|
||||
}
|
||||
|
||||
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
|
||||
@@ -230,7 +225,7 @@ impl PostgresOptions {
|
||||
}
|
||||
|
||||
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
format!(
|
||||
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
|
||||
@@ -244,7 +239,7 @@ impl PostgresOptions {
|
||||
|
||||
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
self.verify_read_only(conn).await?;
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
|
||||
));
|
||||
@@ -285,19 +280,53 @@ fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
|
||||
error
|
||||
}
|
||||
|
||||
sqlx_pool!(
|
||||
PgManager,
|
||||
PgHandle,
|
||||
PostgresOptions,
|
||||
PgConnection,
|
||||
DbDriver::Postgres,
|
||||
"SHOW search_path",
|
||||
verify_startup_script
|
||||
);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
|
||||
async fn initialize_postgres(
|
||||
options: &PostgresOptions,
|
||||
conn: &mut PgConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
let guarded = options.read_only == PgReadOnly::Transaction;
|
||||
if guarded {
|
||||
sqlx::raw_sql(pg_read_only::BEGIN).execute(&mut *conn).await?;
|
||||
}
|
||||
for sql in init {
|
||||
if guarded {
|
||||
pg_read_only::check_single(conn, sql).await?;
|
||||
}
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
if !guarded && !init.is_empty() {
|
||||
options.verify_startup_script(conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SHOW search_path").fetch_one(&mut *conn).await?;
|
||||
let path: Option<String> = row.try_get(0)?;
|
||||
if guarded {
|
||||
sqlx::raw_sql("COMMIT").execute(conn).await?;
|
||||
return Ok(path);
|
||||
}
|
||||
Ok(path.map(|v| format!("SET search_path TO {v}")))
|
||||
}
|
||||
|
||||
async fn initialize_mysql(
|
||||
_: &MySqlConnectOptions,
|
||||
conn: &mut MySqlConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
for sql in init {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SELECT DATABASE()").fetch_one(conn).await?;
|
||||
Ok(row.try_get::<Option<String>, _>(0)?.and_then(|v| crate::sql::use_schema(DbDriver::Mysql, &v)))
|
||||
}
|
||||
|
||||
sqlx_pool!(PgManager, PgHandle, PostgresOptions, PgConnection, initialize_postgres, |c: &PgHandle| c.options.read_only
|
||||
== PgReadOnly::Transaction
|
||||
&& c.in_transaction);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, initialize_mysql, |_: &MysqlHandle| false);
|
||||
|
||||
pub struct ServerPool<M: ManageConnection> {
|
||||
inner: Bb8Pool<M>,
|
||||
transaction_read_only: bool,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -774,7 +803,9 @@ macro_rules! backend_id {
|
||||
}
|
||||
|
||||
mod cursor;
|
||||
mod pg_read_only;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
pub(crate) use pg_read_only::validate as validate_pg_read_only;
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
@@ -947,6 +978,10 @@ impl Setup {
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub(crate) fn transaction_read_only(&self) -> bool {
|
||||
matches!(self, Pool::Postgres(p) if p.transaction_read_only)
|
||||
}
|
||||
|
||||
pub fn driver(&self) -> DbDriver {
|
||||
match self {
|
||||
Pool::Sqlite(_) => DbDriver::Sqlite,
|
||||
@@ -1058,27 +1093,68 @@ impl Pool {
|
||||
if let Some(p) = password {
|
||||
opts = opts.password(p);
|
||||
}
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let options = PostgresOptions { connection: opts, read_only: source.read_only };
|
||||
let mut manager = PgManager { options, init: init.clone(), timeout };
|
||||
// Open once directly so authentication failures retain their database error.
|
||||
let first = match manager.connect().await {
|
||||
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
manager.connect().await
|
||||
}
|
||||
first => first,
|
||||
// Remove only the option supplied by the Read-only checkbox on a retry.
|
||||
let fallback = source.read_only.then(|| {
|
||||
let opts = opts.clone().statement_cache_capacity(0);
|
||||
if setup.params.len() == 1 { opts } else { opts.options(setup.params.iter().skip(1).cloned()) }
|
||||
});
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
.map_err(|e| postgres_connect_error(e, source.read_only))?;
|
||||
let mode = if source.read_only { PgReadOnly::Session } else { PgReadOnly::Off };
|
||||
let mut manager = PgManager {
|
||||
options: PostgresOptions { connection: opts, read_only: mode, local_settings: Arc::default() },
|
||||
init: init.clone(),
|
||||
timeout,
|
||||
};
|
||||
let mut fallback = fallback;
|
||||
let mut try_plain = source.ssl == DbSslMode::Prefer;
|
||||
let first = loop {
|
||||
let mut login_failed = false;
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
let mut conn =
|
||||
manager.options.connection.connect().await.inspect_err(|_| login_failed = true)?;
|
||||
manager.options.verify_read_only(&mut conn).await?;
|
||||
manager.initialize(conn).await
|
||||
})
|
||||
.await
|
||||
.unwrap_or(Err(sqlx::Error::PoolTimedOut));
|
||||
match result {
|
||||
Err(e) if login_failed && try_plain && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
try_plain = false;
|
||||
manager.options.connection =
|
||||
manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
fallback = fallback.map(|opts| opts.ssl_mode(PgSslMode::Disable));
|
||||
}
|
||||
Err(e)
|
||||
if login_failed
|
||||
&& fallback.is_some()
|
||||
&& e.as_database_error().is_some_and(|db| {
|
||||
postgres_read_only_hint(true, db.code().as_deref(), db.message()).is_some()
|
||||
}) =>
|
||||
{
|
||||
manager.options.connection =
|
||||
fallback.take().expect("read-only startup option was supplied");
|
||||
manager.options.read_only = PgReadOnly::Transaction;
|
||||
try_plain = false;
|
||||
let (startup, settings) = pg_read_only::startup(&init).map_err(IdeError::invalid)?;
|
||||
manager.init = Arc::new(startup);
|
||||
manager.options.local_settings = settings.into();
|
||||
tracing::info!(
|
||||
"PostgreSQL endpoint rejected read-only startup; using read-only transactions"
|
||||
);
|
||||
}
|
||||
result => break result.map_err(|e| postgres_connect_error(e, source.read_only))?,
|
||||
}
|
||||
};
|
||||
let transaction_read_only = manager.options.read_only == PgReadOnly::Transaction;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, transaction_read_only, closed: AtomicBool::new(false) }))
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
let mut opts = MySqlConnectOptions::new()
|
||||
@@ -1139,7 +1215,11 @@ impl Pool {
|
||||
let first = first.map_err(db_err)?;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Mysql(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Mysql(ServerPool {
|
||||
inner: pool,
|
||||
transaction_read_only: false,
|
||||
closed: AtomicBool::new(false),
|
||||
}))
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
use tiberius::Config;
|
||||
@@ -1204,6 +1284,29 @@ impl Pool {
|
||||
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
|
||||
}
|
||||
|
||||
async fn cancel_query(&self, sql: String) {
|
||||
if let Pool::Postgres(p) = self
|
||||
&& p.transaction_read_only
|
||||
{
|
||||
// The target owns its backend until cancellation finishes; all regular pool slots may be busy.
|
||||
let control = async {
|
||||
let mut c = p.inner.dedicated_connection().await.map_err(db_err)?;
|
||||
c.start_read_only().await?;
|
||||
Ok::<_, IdeError>(c)
|
||||
};
|
||||
// Never queue a late cancel after giving up the backend whose PID it names.
|
||||
if let Ok(Ok(mut conn)) = tokio::time::timeout(Duration::from_secs(2), control).await {
|
||||
let _ = sqlx::raw_sql(sqlx::AssertSqlSafe(format!("{sql}; ROLLBACK"))).execute(&mut *conn).await;
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"No PostgreSQL backend available to signal cancellation; discarding the client connection"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let _ = self.rows(&sql, 1).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
if let Pool::Jdbc(p) = self {
|
||||
@@ -1217,8 +1320,13 @@ impl Pool {
|
||||
}
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
conn.apply_context(None).await?;
|
||||
let fetched = conn.fetch_rows(sql, max).await;
|
||||
Ok(fetched?.1)
|
||||
let owned = conn.begin_read_only().await?;
|
||||
let result = async {
|
||||
conn.check_protected_statement(sql).await?;
|
||||
conn.fetch_rows(sql, max).await
|
||||
}
|
||||
.await;
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
@@ -1260,6 +1368,9 @@ impl Pool {
|
||||
/// Runs `statements` in one transaction; each must change `expect_one`
|
||||
/// row when flagged (table editor submits).
|
||||
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
if self.transaction_read_only() {
|
||||
return Err(IdeError::invalid("Cannot submit table changes on a read-only PostgreSQL source"));
|
||||
}
|
||||
match self {
|
||||
Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")),
|
||||
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1426,6 +1537,15 @@ impl Held {
|
||||
Held::Oracle(_) => DbDriver::Oracle,
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
let wanted = schema
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| crate::sql::quote_ident(driver, s))
|
||||
.or_else(|| c.context.default.clone());
|
||||
return c.select_path(wanted).await;
|
||||
}
|
||||
let context = self.context().expect("switchable connection");
|
||||
let wanted = context.wanted(driver, schema);
|
||||
if context.known && context.current == wanted {
|
||||
@@ -1467,6 +1587,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn fetch_rows(&mut self, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let result = match self {
|
||||
Held::Sqlite(c) => fetch!(&mut **c, sql, max, Cells::Text),
|
||||
@@ -1484,6 +1605,31 @@ impl Held {
|
||||
|
||||
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
|
||||
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_command(sql).await
|
||||
}
|
||||
.await;
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
pub(crate) async fn begin_manual(&mut self, driver: DbDriver) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
self.begin_read_only().await?;
|
||||
return Ok(());
|
||||
}
|
||||
self.run_command(begin_statement(driver)).await
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_manual(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
return self.end_read_only(commit).await;
|
||||
}
|
||||
self.run_command(if commit { "COMMIT" } else { "ROLLBACK" }).await
|
||||
}
|
||||
|
||||
async fn run_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.before_statement(sql);
|
||||
let result = self.raw_command(sql).await;
|
||||
if result.is_ok() {
|
||||
@@ -1493,6 +1639,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn raw_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
match self {
|
||||
Held::SqlServer(c) => mssql_command(c, sql).await,
|
||||
Held::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1575,6 +1722,31 @@ impl Held {
|
||||
if let Held::Snowflake(c, schema) = self {
|
||||
return c.execute_in(schema.as_deref(), sql, skip, max_rows, cancel).await;
|
||||
}
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_statement(pool, sql, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if cancel.is_cancelled()
|
||||
&& let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
c.conn.take();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
async fn run_statement(
|
||||
&mut self,
|
||||
pool: &Pool,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let started = Instant::now();
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
@@ -1590,7 +1762,7 @@ impl Held {
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -95,6 +95,7 @@ impl Cursors {
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
protected: bool,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
let (id, reads) = {
|
||||
let mut registry = self.registry.lock();
|
||||
@@ -110,7 +111,7 @@ impl Cursors {
|
||||
self.finish(id, &fetched);
|
||||
Some(Ok(fetched))
|
||||
}
|
||||
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
|
||||
Some(Err(e)) if protected || e.kind == ErrorKind::Cancelled => {
|
||||
self.close(id);
|
||||
Some(Err(e))
|
||||
}
|
||||
@@ -196,6 +197,19 @@ impl Cursors {
|
||||
/// nobody asks for [`IDLE`], or it is released (its channel closes).
|
||||
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
|
||||
let Some(first) = reads.recv().await else { return held.discard().await };
|
||||
let prepare = async {
|
||||
let owned = held.begin_read_only().await?;
|
||||
held.check_protected_statement(&sql).await?;
|
||||
Ok(owned)
|
||||
}
|
||||
.await;
|
||||
let owned = match prepare {
|
||||
Ok(owned) => owned,
|
||||
Err(error) => {
|
||||
let _ = first.reply.send(Err(error));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
// Evaluates to whether the connection can go back to its pool (the stream was read to
|
||||
// its end); otherwise it is closed rather than left to be drained.
|
||||
@@ -217,7 +231,7 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
let _ = reply.send(Err(IdeError::cancelled()));
|
||||
break;
|
||||
@@ -236,13 +250,13 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e));
|
||||
reusable = true;
|
||||
reusable = !owned;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(stream);
|
||||
if let Some((reply, mut fetched)) = last {
|
||||
if let Some((_, fetched)) = &mut last {
|
||||
if fetched.0.is_empty() && looks_like_query(&sql) {
|
||||
fetched.0 = (&mut **$conn)
|
||||
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
|
||||
@@ -250,12 +264,11 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
.map(|s| statement_columns(&s))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let _ = reply.send(Ok(fetched));
|
||||
}
|
||||
reusable
|
||||
(reusable, last)
|
||||
}};
|
||||
}
|
||||
let reusable = match &mut held {
|
||||
let (reusable, last) = match &mut held {
|
||||
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
|
||||
Held::Postgres(c) => {
|
||||
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
@@ -263,7 +276,9 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
_ => unreachable!("only the sqlx drivers keep cursors"),
|
||||
};
|
||||
if !reusable {
|
||||
if let Some((reply, fetched)) = last {
|
||||
let _ = reply.send(held.finish_read_only(owned, Ok(fetched)).await);
|
||||
} else if !reusable {
|
||||
held.discard().await;
|
||||
}
|
||||
}
|
||||
@@ -452,7 +467,7 @@ mod tests {
|
||||
});
|
||||
let resumed = tokio::spawn({
|
||||
let (cursors, key) = (cursors.clone(), key.clone());
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new(), false).await.is_some() }
|
||||
});
|
||||
in_read.notified().await;
|
||||
cursors.release(&key);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
//! PostgreSQL transaction-pool connections whose endpoint rejects the read-only startup option.
|
||||
|
||||
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use sqlx::{Executor, SqlSafeStr};
|
||||
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
|
||||
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
loop {
|
||||
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
|
||||
if let Some(comment) = input.strip_prefix("--") {
|
||||
*input = &comment[comment.find(['\r', '\n']).unwrap_or(comment.len())..];
|
||||
} else if let Some(mut comment) = input.strip_prefix("/*") {
|
||||
let mut depth = 1usize;
|
||||
while depth > 0 {
|
||||
let Some(at) = comment.find(['/', '*']) else { return "" };
|
||||
comment = &comment[at..];
|
||||
if let Some(rest) = comment.strip_prefix("/*") {
|
||||
depth += 1;
|
||||
comment = rest;
|
||||
} else if let Some(rest) = comment.strip_prefix("*/") {
|
||||
depth -= 1;
|
||||
comment = rest;
|
||||
} else {
|
||||
comment = &comment[1..];
|
||||
}
|
||||
}
|
||||
*input = comment;
|
||||
} else {
|
||||
let end = input.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(input.len());
|
||||
let (word, rest) = input.split_at(end);
|
||||
*input = rest;
|
||||
return word;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn control(mut sql: &str) -> Option<&'static str> {
|
||||
let first = leading_word(&mut sql);
|
||||
for name in ["BEGIN", "COMMIT", "END", "ROLLBACK", "ABORT"] {
|
||||
if first.eq_ignore_ascii_case(name) {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
let second = leading_word(&mut sql);
|
||||
if second.eq_ignore_ascii_case("TRANSACTION") {
|
||||
return [("START", "START TRANSACTION"), ("PREPARE", "PREPARE TRANSACTION"), ("SET", "SET TRANSACTION")]
|
||||
.into_iter()
|
||||
.find_map(|(verb, name)| first.eq_ignore_ascii_case(verb).then_some(name));
|
||||
}
|
||||
(first.eq_ignore_ascii_case("SET")
|
||||
&& second.eq_ignore_ascii_case("SESSION")
|
||||
&& leading_word(&mut sql).eq_ignore_ascii_case("CHARACTERISTICS"))
|
||||
.then_some("SET SESSION CHARACTERISTICS")
|
||||
}
|
||||
|
||||
pub(crate) fn validate(sql: &str) -> Result<(), String> {
|
||||
if sql.contains('\0') {
|
||||
return Err("PostgreSQL statements cannot contain a null byte".into());
|
||||
}
|
||||
let blocked = control(sql).or_else(|| {
|
||||
sql.contains(';')
|
||||
.then(|| crate::split::split(sql, crate::DbDriver::Postgres))
|
||||
.and_then(|statements| statements.iter().find_map(|s| control(&s.text)))
|
||||
});
|
||||
if let Some(name) = blocked {
|
||||
return Err(format!("{name} is unavailable while OpenIDEA manages the read-only transaction"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A startup SET must follow the client to its next backend without changing the next client's session.
|
||||
pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
let mut init = Vec::with_capacity(statements.len());
|
||||
let mut settings = Vec::new();
|
||||
for sql in statements {
|
||||
validate(sql)?;
|
||||
let mut rest = sql.as_str();
|
||||
let verb = leading_word(&mut rest);
|
||||
if verb.eq_ignore_ascii_case("RESET") || verb.eq_ignore_ascii_case("DISCARD") {
|
||||
return Err(format!("{verb} in a startup script cannot be preserved across pooled read-only transactions"));
|
||||
}
|
||||
if verb.eq_ignore_ascii_case("SET") {
|
||||
let after_set = rest;
|
||||
let kind = leading_word(&mut rest);
|
||||
if !kind.eq_ignore_ascii_case("LOCAL") && !kind.eq_ignore_ascii_case("CONSTRAINTS") {
|
||||
let mut after_session = rest;
|
||||
let local = if kind.eq_ignore_ascii_case("SESSION")
|
||||
&& !leading_word(&mut after_session).eq_ignore_ascii_case("AUTHORIZATION")
|
||||
{
|
||||
rest
|
||||
} else {
|
||||
after_set
|
||||
};
|
||||
let sql = format!("SET LOCAL {local}");
|
||||
settings.push(sql.clone());
|
||||
init.push(sql);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
init.push(sql.clone());
|
||||
}
|
||||
Ok((init, settings))
|
||||
}
|
||||
|
||||
// Keep the text result format of raw_sql. For SQL containing a delimiter, PostgreSQL's Parse
|
||||
// validates that the text denotes a single command, including under the server's quoting rules.
|
||||
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
|
||||
if sql.contains(';') {
|
||||
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl PgHandle {
|
||||
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
|
||||
self.in_transaction = true;
|
||||
let result = async {
|
||||
sqlx::raw_sql(BEGIN).execute(&mut **self).await.map_err(db_err)?;
|
||||
let settings = self.options.local_settings.clone();
|
||||
for sql in settings.iter() {
|
||||
check_single(self, sql).await.map_err(db_err)?;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
|
||||
}
|
||||
self.apply_local_path().await
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn apply_local_path(&mut self) -> IdeResult<()> {
|
||||
if let Some(path) = &self.context.current {
|
||||
let path = path.clone();
|
||||
sqlx::query("SELECT pg_catalog.set_config('search_path', $1, true)")
|
||||
.bind(path)
|
||||
.execute(&mut **self)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn select_path(&mut self, wanted: Option<String>) -> IdeResult<()> {
|
||||
if !self.context.known || self.context.current != wanted {
|
||||
self.context.current = wanted;
|
||||
if self.in_transaction {
|
||||
self.apply_local_path().await?;
|
||||
}
|
||||
self.context.known = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Held {
|
||||
pub(super) fn require_read_only_transaction(&self) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction && (!c.in_transaction || c.conn.is_none()))
|
||||
{
|
||||
return Err(IdeError::internal("PostgreSQL read-only transaction has not started"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn guarded_postgres(&mut self) -> Option<&mut PgHandle> {
|
||||
match self {
|
||||
Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when this operation owns the transaction and must finish it.
|
||||
pub(super) async fn begin_read_only(&mut self) -> IdeResult<bool> {
|
||||
if let Some(c) = self.guarded_postgres()
|
||||
&& !c.in_transaction
|
||||
{
|
||||
c.start_read_only().await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) async fn check_protected_statement(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
validate(sql).map_err(IdeError::invalid)?;
|
||||
check_single(c, sql).await.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn end_read_only(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
if c.conn.is_none() {
|
||||
return Err(IdeError::invalid("The read-only PostgreSQL transaction lost its connection"));
|
||||
}
|
||||
let end = if commit { "COMMIT" } else { "ROLLBACK" };
|
||||
if let Err(error) = sqlx::raw_sql(end).execute(&mut **c).await {
|
||||
c.conn.take();
|
||||
return Err(db_err(error));
|
||||
}
|
||||
c.in_transaction = false;
|
||||
c.context = Context::new(c.context.default.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn finish_read_only<T>(&mut self, owned: bool, result: IdeResult<T>) -> IdeResult<T> {
|
||||
if owned && let Err(error) = self.end_read_only(result.is_ok()).await {
|
||||
return Err(result.err().unwrap_or(error));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::validate;
|
||||
|
||||
#[test]
|
||||
fn names_transaction_control_and_accepts_quoted_text() {
|
||||
for name in [
|
||||
"BEGIN",
|
||||
"COMMIT",
|
||||
"END",
|
||||
"ROLLBACK",
|
||||
"ABORT",
|
||||
"START TRANSACTION",
|
||||
"PREPARE TRANSACTION",
|
||||
"SET TRANSACTION",
|
||||
"SET SESSION CHARACTERISTICS",
|
||||
] {
|
||||
let statement = name.to_lowercase().replace(' ', " /* note */ ");
|
||||
let sql = format!(" -- preceding comment\n /* outer /* nested */ block */ {statement}");
|
||||
assert!(validate(&sql).unwrap_err().contains(name), "{sql}");
|
||||
}
|
||||
assert!(validate("SELECT 1; COMMIT").unwrap_err().contains("COMMIT"));
|
||||
for sql in
|
||||
["SELECT 'a; COMMIT'", "SELECT $$;ROLLBACK$$", "SELECT 1 /* END */", "SET LOCAL search_path TO public"]
|
||||
{
|
||||
assert!(validate(sql).is_ok(), "{sql}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,6 +178,18 @@ pub struct TableDetails {
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
}
|
||||
|
||||
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
|
||||
/// by `grantor` (unknown on MySQL), and may grant it on when `grantable`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableGrant")]
|
||||
pub struct TableGrant {
|
||||
pub grantee: String,
|
||||
pub grantor: Option<String>,
|
||||
pub privilege: String,
|
||||
pub grantable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbCompletionColumn")]
|
||||
@@ -394,7 +406,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
|
||||
async fn end_session(session: &Session) {
|
||||
let held = session.lock().await.take();
|
||||
if let Some(mut conn) = held
|
||||
&& (conn.command("ROLLBACK").await.is_err() || conn.restore_default().await.is_err())
|
||||
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
|
||||
{
|
||||
conn.discard().await;
|
||||
}
|
||||
@@ -837,11 +849,18 @@ impl DbManager {
|
||||
_ => pool.rows(version, 1).await,
|
||||
};
|
||||
pool.close().await;
|
||||
let strict =
|
||||
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let strict = pool.transaction_read_only()
|
||||
|| source.external_tunnel.is_some()
|
||||
|| matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let rows = if strict { result? } else { result.unwrap_or_default() };
|
||||
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
|
||||
Ok(v.unwrap_or_else(|| "Connected".into()))
|
||||
let mut message = v.unwrap_or_else(|| "Connected".into());
|
||||
if pool.transaction_read_only() {
|
||||
message.push_str(
|
||||
"\nRead-only queries use BEGIN READ ONLY because this endpoint rejected the startup setting.",
|
||||
);
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Runs `job` with the client tool at `executable` against target `id`, connected like the
|
||||
@@ -1157,6 +1176,28 @@ impl DbManager {
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
/// [`sql::table_grants`] doesn't cover.
|
||||
pub async fn table_grants(&self, id: &str, schema: &str, table: &str) -> IdeResult<Vec<TableGrant>> {
|
||||
let pool = self.pool(id).await?;
|
||||
let Some(q) = sql::table_grants(pool.driver(), schema, table) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(pool
|
||||
.rows(&q, MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let grantee = it.next().flatten()?;
|
||||
let grantor = it.next().flatten().filter(|g| !g.is_empty());
|
||||
let privilege = it.next().flatten()?.to_ascii_uppercase();
|
||||
let grantable = flag(&it.next().flatten());
|
||||
Some(TableGrant { grantee, grantor, privilege, grantable })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The routines and sequences of `schema`.
|
||||
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
|
||||
let pool = self.pool(id).await?;
|
||||
@@ -1455,6 +1496,22 @@ impl DbManager {
|
||||
self.execute_from(id, statement, 0, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
|
||||
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
|
||||
if statements.len() > 1
|
||||
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
|
||||
&& self.pool(id).await?.transaction_read_only()
|
||||
{
|
||||
for statement in statements {
|
||||
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
|
||||
self.finish_transaction(id, false).await?;
|
||||
return Err(IdeError::invalid(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`execute`](Self::execute), reading past the first `skip` rows without keeping
|
||||
/// them: a later page of a result, where only that page is decoded and returned.
|
||||
/// `schema` is a query console's active context: the connection that runs the
|
||||
@@ -1590,16 +1647,23 @@ impl DbManager {
|
||||
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
|
||||
}
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
if !conn::cursor_statement(statement) {
|
||||
let protected = pool.transaction_read_only();
|
||||
let cursor = protected || conn::cursor_statement(statement);
|
||||
if !cursor || (protected && skip == 0 && paging) {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
|
||||
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
|
||||
let key = conn::CursorKey::new(id, statement, schema);
|
||||
let started = std::time::Instant::now();
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
|
||||
Some(page) => page,
|
||||
None => {
|
||||
if protected && skip > 0 {
|
||||
return Err(IdeError::invalid(
|
||||
"This read-only result is no longer open at this page. Run the query again.",
|
||||
));
|
||||
}
|
||||
let mut held = Held::acquire(&pool).await?;
|
||||
held.apply_context(schema).await?;
|
||||
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
|
||||
@@ -1627,10 +1691,32 @@ impl DbManager {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
let mut held = session.lock().await;
|
||||
if pool.transaction_read_only() {
|
||||
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
|
||||
let mut conn = match held.take() {
|
||||
Some(conn) => conn,
|
||||
None => {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
conn
|
||||
}
|
||||
};
|
||||
let result = async {
|
||||
conn.apply_context(schema).await?;
|
||||
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
*held = Some(conn);
|
||||
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
|
||||
conn.discard().await;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if held.is_none() {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.apply_context(schema).await?;
|
||||
conn.command(conn::begin_statement(pool.driver())).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
*held = Some(conn);
|
||||
}
|
||||
let conn = held.as_mut().expect("opened above");
|
||||
@@ -1676,7 +1762,7 @@ impl DbManager {
|
||||
let Some(session) = session else { return Ok(()) };
|
||||
let mut held = session.lock().await;
|
||||
let Some(mut conn) = held.take() else { return Ok(()) };
|
||||
if let Err(e) = conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await {
|
||||
if let Err(e) = conn.finish_manual(commit).await {
|
||||
// Discarding a Snowflake connection doesn't end its session, which the data source's
|
||||
// other targets share: the transaction stays open, so it stays held to be ended again.
|
||||
if matches!(conn, conn::Held::Snowflake(..)) {
|
||||
|
||||
@@ -673,6 +673,28 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `grantee, grantor, privilege, grantable` rows of `table`'s object privileges, for the
|
||||
/// engines whose catalog keeps them per table: PostgreSQL's ACL (its implicit owner
|
||||
/// privileges when `relacl` is null) and MySQL's `TABLE_PRIVILEGES` (no grantor). `None`
|
||||
/// for the other engines, which then run no query.
|
||||
pub fn table_grants(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
pg_get_userbyid(a.grantor), a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a \
|
||||
WHERE n.nspname = {s} AND c.relname = {t} ORDER BY 1, 2"
|
||||
)),
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT grantee, NULL, privilege_type, is_grantable FROM information_schema.table_privileges \
|
||||
WHERE table_schema = {s} AND table_name = {t} ORDER BY 1"
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `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();
|
||||
|
||||
@@ -322,3 +322,39 @@ async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> Id
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_list_table_privileges() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP DATABASE IF EXISTS oi_grants",
|
||||
"DROP USER IF EXISTS 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE DATABASE oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO 'oi_grant_reader'@'%'",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO 'oi_grant_writer'@'%' WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
let grants = db.table_grants("m", "oi_grants", "shared").await?;
|
||||
let mut rows: Vec<_> =
|
||||
grants.iter().map(|g| (g.grantee.as_str(), g.privilege.as_str(), g.grantable, g.grantor.clone())).collect();
|
||||
rows.sort();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("'oi_grant_reader'@'%'", "SELECT", false, None),
|
||||
("'oi_grant_writer'@'%'", "INSERT", true, None),
|
||||
("'oi_grant_writer'@'%'", "UPDATE", true, None),
|
||||
]
|
||||
);
|
||||
assert!(db.table_grants("m", "oi_grants", "private").await?.is_empty());
|
||||
for stmt in ["DROP DATABASE oi_grants", "DROP USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'"] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,11 +5,174 @@ use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_POSTGRES").ok()?;
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
}
|
||||
|
||||
fn endpoint(variable: &str) -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var(variable).ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
/// A disposable PgBouncer transaction pool which rejects default_transaction_read_only at startup
|
||||
/// (`OPENIDEA_TEST_PGBOUNCER`, same format). PgBouncer 1.24 rejects it; 1.26 tracks it per client,
|
||||
/// which keeps the startup option in use and fails the fallback assertion below.
|
||||
#[tokio::test]
|
||||
async fn transaction_pooler_runs_read_only_work_on_the_assigned_backend() -> IdeResult<()> {
|
||||
let Some((host, port, user, password)) = endpoint("OPENIDEA_TEST_PGBOUNCER") else { return Ok(()) };
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
let mut source = DataSource {
|
||||
id: "ro".into(),
|
||||
name: "Pooler".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let normal = DataSource { id: "rw".into(), read_only: false, ..source.clone() };
|
||||
source.options.startup_script =
|
||||
"SET search_path = pg_catalog, public; SET statement_timeout = '17s'; SELECT 1".into();
|
||||
db.save_sources(vec![source.clone(), normal]).await?;
|
||||
for id in ["rw", "ro"] {
|
||||
db.set_password(id, Some(password.clone()), false).await?;
|
||||
}
|
||||
let message = db.test(&source, Some(password.clone()), None).await?;
|
||||
assert!(message.contains("PostgreSQL") && message.contains("BEGIN READ ONLY"), "{message}");
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_pooler_{}", uuid::Uuid::new_v4().simple());
|
||||
let write = format!("INSERT INTO {table} VALUES (1)");
|
||||
pooler_modes(&db, &table, &write, &c).await?;
|
||||
pooler_rotation(&db, &c).await?;
|
||||
pooler_manual(&db, &write, &c).await?;
|
||||
pooler_paging(&db, &c).await?;
|
||||
pooler_cancellation(&db, &c).await?;
|
||||
source.options.time_zone = "Europe/Paris".into();
|
||||
source.options.startup_script = "SELECT 'read;only'".into();
|
||||
let configured = ide_db::Pool::connect(&source, Some(&password), None).await?;
|
||||
assert_eq!(configured.rows("SHOW TimeZone", 1).await?, [[Some("Europe/Paris".into())]]);
|
||||
configured.close().await;
|
||||
source.options.startup_script = "SELECT 1/0; COMMIT".into();
|
||||
let error = db.test(&source, Some(password), None).await.unwrap_err();
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
db.execute("rw", &format!("DROP TABLE {table}"), 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_modes(db: &DbManager, table: &str, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
assert_eq!(db.execute("rw", mode, 1, c).await?.rows, [[Some("off".into())]]);
|
||||
db.execute("rw", &format!("CREATE TABLE {table} (n int)"), 1, c).await?;
|
||||
assert!(db.execute("ro", write, 1, c).await.unwrap_err().message.contains("25006"));
|
||||
assert_eq!(db.pool("ro").await?.rows(mode, 1).await?, [[Some("on".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_rotation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let status = "SELECT pg_backend_pid(), current_setting('transaction_read_only'), current_setting('search_path'), current_setting('statement_timeout')";
|
||||
let pool = db.pool("ro").await?;
|
||||
let mut client = ide_db::Held::acquire(&pool).await?;
|
||||
let first_pid = client.execute(&pool, status, 1, c).await?.rows[0][0].clone();
|
||||
let writable = db.pool("rw").await?;
|
||||
let mut blockers = Vec::new();
|
||||
let mut previous_backend = loop {
|
||||
let mut other = ide_db::Held::acquire(&writable).await?;
|
||||
other.command("BEGIN").await?;
|
||||
let pid = other.execute(&writable, status, 1, c).await?.rows[0][0].clone();
|
||||
if pid == first_pid {
|
||||
break other;
|
||||
}
|
||||
blockers.push(other);
|
||||
assert!(blockers.len() < 4, "the fixture must offer the original backend");
|
||||
};
|
||||
for mut other in blockers {
|
||||
other.command("ROLLBACK").await?;
|
||||
}
|
||||
let rerouted = client.execute(&pool, status, 1, c).await?;
|
||||
assert_ne!(rerouted.rows[0][0], first_pid);
|
||||
assert_eq!(rerouted.rows[0][1..], [Some("on".into()), Some("pg_catalog, public".into()), Some("17s".into())]);
|
||||
let ordinary = previous_backend.execute(&writable, status, 1, c).await?;
|
||||
assert_ne!(ordinary.rows[0][2].as_deref(), Some("pg_catalog, public"));
|
||||
assert_ne!(ordinary.rows[0][3].as_deref(), Some("17s"));
|
||||
previous_backend.command("ROLLBACK").await?;
|
||||
drop(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_manual(db: &DbManager, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
db.set_manual_commit("ro", true).await?;
|
||||
for commit in [true, false] {
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
db.finish_transaction("ro", commit).await?;
|
||||
}
|
||||
db.execute("ro", write, 1, c).await.unwrap_err();
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let timestamp = "SELECT transaction_timestamp()";
|
||||
for batch in [false, true] {
|
||||
let before = db.execute("ro", timestamp, 1, c).await?.rows;
|
||||
let error = if batch {
|
||||
let script = ide_db::split::split("SELECT 1/0; COMMIT", DbDriver::Postgres);
|
||||
db.validate_script("ro", &script).await.unwrap_err()
|
||||
} else {
|
||||
db.execute("ro", "COMMIT", 1, c).await.unwrap_err()
|
||||
};
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
assert_ne!(db.execute("ro", timestamp, 1, c).await?.rows, before);
|
||||
}
|
||||
db.set_manual_commit("ro", false).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_paging(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let query = "SELECT current_setting('transaction_read_only'), pg_backend_pid(), transaction_timestamp(), n FROM generate_series(1, 12) n";
|
||||
let first = db.execute_from("ro", query, 0, 2, c, None).await?;
|
||||
let page = db.execute_from("ro", query, 2, 2, c, None).await?;
|
||||
let next = db.execute_from("ro", query, 4, 2, c, None).await?;
|
||||
assert_eq!(page.rows[0][0].as_deref(), Some("on"));
|
||||
assert_eq!(page.rows[0][..3], first.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][..3], page.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][3].as_deref(), Some("5"));
|
||||
db.release_result("ro", query, None);
|
||||
let expired = db.execute_from("ro", query, 6, 2, c, None).await.unwrap_err();
|
||||
assert!(expired.message.contains("Run the query again"), "{}", expired.message);
|
||||
let chosen = db.execute_from("ro", "SELECT current_schema()", 0, 1, c, Some("public")).await?;
|
||||
assert_eq!(chosen.rows, [[Some("public".into())]]);
|
||||
assert_eq!(db.execute("ro", "SELECT current_schema()", 1, c).await?.rows, [[Some("pg_catalog".into())]]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_cancellation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let writable = db.pool("rw").await?;
|
||||
let mode = "SHOW transaction_read_only";
|
||||
let stop = CancellationToken::new();
|
||||
let slow = "SELECT pg_sleep(10) AS oi_pooler_cancel";
|
||||
let (outcome, observed) = tokio::join!(db.execute("ro", slow, 1, &stop), async {
|
||||
for _ in 0..40 {
|
||||
let live = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await.unwrap();
|
||||
if live[0][0].as_deref() == Some("1") {
|
||||
stop.cancel();
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
stop.cancel();
|
||||
false
|
||||
});
|
||||
assert!(observed, "the slow statement reached PostgreSQL before cancellation");
|
||||
assert_eq!(outcome.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let active = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await?;
|
||||
assert_eq!(active, [[Some("0".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
@@ -572,3 +735,47 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
|
||||
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP SCHEMA IF EXISTS oi_grants CASCADE",
|
||||
"DROP ROLE IF EXISTS oi_grant_reader",
|
||||
"DROP ROLE IF EXISTS oi_grant_writer",
|
||||
"CREATE ROLE oi_grant_reader",
|
||||
"CREATE ROLE oi_grant_writer",
|
||||
"CREATE SCHEMA oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO oi_grant_reader, PUBLIC",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO oi_grant_writer WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
|
||||
let grants = db.table_grants("p", "oi_grants", "shared").await?;
|
||||
let of = |grantee: &str| {
|
||||
let mut v: Vec<_> = grants
|
||||
.iter()
|
||||
.filter(|g| g.grantee == grantee)
|
||||
.map(|g| (g.privilege.as_str(), g.grantable, g.grantor.as_deref() == Some(owner.as_str())))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(of("oi_grant_reader"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("PUBLIC"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("oi_grant_writer"), [("INSERT", true, true), ("UPDATE", true, true)], "{grants:?}");
|
||||
assert!(of(&owner).contains(&("TRUNCATE", false, true)), "{grants:?}");
|
||||
// No ACL yet: the owner's implicit privileges.
|
||||
let private = db.table_grants("p", "oi_grants", "private").await?;
|
||||
assert!(private.iter().all(|g| g.grantee == owner), "{private:?}");
|
||||
assert!(private.iter().any(|g| g.privilege == "SELECT"), "{private:?}");
|
||||
for stmt in ["DROP SCHEMA oi_grants CASCADE", "DROP ROLE oi_grant_reader", "DROP ROLE oi_grant_writer"] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.16.0";
|
||||
pub const ENGINE_VERSION: &str = "1.17.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -283,6 +283,47 @@ fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The edits on the lines of `range`. Some servers (Intelephense, #6055) answer a range request
|
||||
/// with edits across the whole file; Reformat Code with a selection changes only the selected
|
||||
/// lines. An edit that reaches past them and keeps its line count is split into one per line.
|
||||
fn within_lines(text: &str, edits: Vec<TextEdit>, range: Range) -> Vec<TextEdit> {
|
||||
let from = Pos::new(range.start.line, 0);
|
||||
// A selection ending at a line start leaves that line out.
|
||||
let to = if range.end.col == 0 && range.end.line > range.start.line {
|
||||
range.end
|
||||
} else {
|
||||
Pos::new(range.end.line + 1, 0)
|
||||
};
|
||||
let doc = ide_text::Document::new(text);
|
||||
edits
|
||||
.into_iter()
|
||||
.flat_map(|e| if e.range.start >= from && e.range.end <= to { vec![e] } else { per_line(&doc, e) })
|
||||
.filter(|e| e.range.start >= from && e.range.end <= to)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `edit` as one edit per line when it replaces as many lines as it inserts, else nothing.
|
||||
fn per_line(doc: &ide_text::Document, edit: TextEdit) -> Vec<TextEdit> {
|
||||
let Range { start, end } = edit.range;
|
||||
let lines: Vec<&str> = edit.new_text.split('\n').collect();
|
||||
if lines.len() as u32 != end.line - start.line + 1 {
|
||||
return Vec::new();
|
||||
}
|
||||
let width = |line: u32| doc.line(line).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
lines
|
||||
.into_iter()
|
||||
.zip(start.line..=end.line)
|
||||
.map(|(new_text, line)| TextEdit {
|
||||
range: Range::new(
|
||||
Pos::new(line, if line == start.line { start.col } else { 0 }),
|
||||
Pos::new(line, if line == end.line { end.col } else { width(line) }),
|
||||
),
|
||||
new_text: new_text.to_owned(),
|
||||
})
|
||||
.filter(|e| doc.slice(doc.pos_to_offset(e.range.start), doc.pos_to_offset(e.range.end)) != e.new_text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn format(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -514,9 +555,15 @@ async fn provider_edits(
|
||||
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
|
||||
};
|
||||
let text = snap.text;
|
||||
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let edits = minimal_edits(&text, edits);
|
||||
Some(match range {
|
||||
Some(range) => within_lines(&text, edits, range),
|
||||
None => edits,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
@@ -1050,6 +1097,26 @@ mod tests {
|
||||
|
||||
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
|
||||
#[test]
|
||||
fn range_formatting_changes_only_the_selected_lines() {
|
||||
// Intelephense answers a range request for lines 2-3 with edits across the file (#6055).
|
||||
let text = "<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n";
|
||||
let formatted = "<?php\nf('a');\n$x = 1;\n$y = 2;\nf('b');\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let edits = minimal_edits(text, whole);
|
||||
let selected = Range::new(Pos::new(2, 0), Pos::new(3, 8));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits.clone(), selected)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
// Selected up to the start of line 4: line 4 stays as it is.
|
||||
let to_line_start = Range::new(Pos::new(2, 3), Pos::new(3, 0));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits, to_line_start)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
|
||||
@@ -971,6 +971,7 @@ pub async fn build_run(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let file = file.map(|f| ide_core::project_roots::resolve(&root, &f));
|
||||
let settings = project.settings.effective();
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
|
||||
@@ -9,7 +9,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::{
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -293,6 +293,19 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<Vec<TableGrant>> {
|
||||
// Who may read or change `table` (PostgreSQL and MySQL; empty elsewhere).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.table_grants(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_ddl(host: &Host, window: &str, id: String, schema: String, table: String) -> IdeResult<String> {
|
||||
// The DDL of table or view `table` (Go to DDL, Generate DDL).
|
||||
@@ -481,6 +494,7 @@ async fn execute_statements(
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = async {
|
||||
db.validate_script(id, &statements).await?;
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -690,6 +704,7 @@ ide_command::domain!(
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
db_table_grants,
|
||||
db_table_page,
|
||||
db_tables,
|
||||
db_test,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! HTTP Client commands shared by the desktop shell's IPC commands and the remote server: a remote
|
||||
//! window sends its requests from the project host and keeps their history there.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, IpcPath, Location, RequestId};
|
||||
use ide_http::{HistoryEntry, HttpExchange};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::blocking;
|
||||
|
||||
/// The root of the window's project, when one is open.
|
||||
fn root(host: &Host, window: &str) -> Option<PathBuf> {
|
||||
host.project(window).ok().map(|p| p.root.clone())
|
||||
}
|
||||
|
||||
/// Environment names from the `http-client(.private).env.json` files that apply to `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environments(host: &Host, window: &str, path: Option<IpcPath>) -> IdeResult<Vec<String>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::environments(path.as_deref(), root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Sends request `index` of `text` (the editor buffer of `path`) and records
|
||||
/// the exchange in the response history. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_execute(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<HttpExchange> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let input = ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: Some(&project.root),
|
||||
env: env.as_deref(),
|
||||
};
|
||||
let result = ide_http::run(input, &cancel).await;
|
||||
host.end_request(request);
|
||||
let exchange = result?;
|
||||
let history = project.http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Err(e) = history.add(&saved) {
|
||||
tracing::warn!("http history: {}", e.message);
|
||||
}
|
||||
});
|
||||
Ok(exchange)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history(host: &Host, window: &str) -> IdeResult<Vec<HistoryEntry>> {
|
||||
Ok(host.project(window)?.http_history.list())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_get(host: &Host, window: &str, id: String) -> IdeResult<HttpExchange> {
|
||||
host.project(window)?.http_history.get(&id)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_clear(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.http_history.clear()
|
||||
}
|
||||
|
||||
/// Convert to cURL and Copy: request `index` of `text` (the editor buffer of `path`), with
|
||||
/// the variables of `env` substituted, as a cURL command.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_curl(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let root = root(host, window);
|
||||
blocking(move || {
|
||||
ide_http::curl(&ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: root.as_deref(),
|
||||
env: env.as_deref(),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The environment file for the request file `path` (`is_private`: the private one): the nearest
|
||||
/// existing one, else a new one next to it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_private: bool) -> IdeResult<IpcPath> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::env::environment_file(&path, root.as_deref(), is_private).map(IpcPath::from)).await
|
||||
}
|
||||
|
||||
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
|
||||
/// (Navigate › Declaration on a variable), private file first.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_variable_definitions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: IpcPath,
|
||||
name: String,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
http: http_curl,
|
||||
http_environment_file,
|
||||
http_environments,
|
||||
http_execute,
|
||||
http_history,
|
||||
http_history_clear,
|
||||
http_history_get,
|
||||
http_variable_definitions,
|
||||
);
|
||||
@@ -902,7 +902,8 @@ pub async fn java_build_workspace(
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -926,13 +927,13 @@ pub async fn java_junit_runner(
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
through Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
@@ -92,6 +93,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
|
||||
@@ -122,6 +122,9 @@ pub fn settings_set(
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
|
||||
@@ -319,6 +319,7 @@ pub async fn run_start(
|
||||
on_output: Channel<OutputChunk>,
|
||||
request: Option<ide_core::RequestId>,
|
||||
) -> IdeResult<RunInfo> {
|
||||
super::term::apply_output_rate(host, window);
|
||||
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
|
||||
let _ = on_output.send(chunk);
|
||||
});
|
||||
|
||||
@@ -29,6 +29,7 @@ pub async fn term_spawn(
|
||||
mut options: TerminalOptions,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<TerminalInfo> {
|
||||
apply_output_rate(host, window);
|
||||
if !host.project(window).is_ok_and(|p| p.is_trusted()) {
|
||||
// Project terminal settings can otherwise start a command as soon as a tab restores.
|
||||
let global = host.global_settings.effective().terminal;
|
||||
@@ -61,6 +62,17 @@ pub async fn term_spawn(
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Terminal › Max FPS also paces the terminal and Run console output
|
||||
/// pumps (#5897): applied from the window's effective settings when a session starts and
|
||||
/// when the setting changes. The rate is process-wide; the last window to apply it wins.
|
||||
pub(crate) fn apply_output_rate(host: &Host, window: &str) {
|
||||
let terminal = match host.project(window) {
|
||||
Ok(project) => project.settings.effective().terminal,
|
||||
Err(_) => host.global_settings.effective().terminal,
|
||||
};
|
||||
ide_core::output_rate::set_max_fps(&terminal.max_fps);
|
||||
}
|
||||
|
||||
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
|
||||
/// built-in client with the configuration's saved password, key or agent.
|
||||
pub async fn spawn_ssh(
|
||||
|
||||
@@ -8,7 +8,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxySettings};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Whether `url` names this machine (`localhost` or a loopback address).
|
||||
pub fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
|
||||
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
|
||||
}
|
||||
|
||||
@@ -4826,7 +4826,18 @@ impl PluginApi {
|
||||
if let Some(icon) = file.as_ref().and_then(|f| f.icon.as_ref()) {
|
||||
ide_extension::validate_item_id(icon, "file icon id").map_err(HostError::Invalid)?;
|
||||
}
|
||||
items.retain(|d| decoration_style(&d.style));
|
||||
for colors in items.iter_mut().filter_map(|d| d.colors.as_mut()) {
|
||||
for color in [&mut colors.foreground, &mut colors.background].into_iter().flatten() {
|
||||
*color = decoration_color(color).ok_or_else(|| {
|
||||
HostError::Invalid(format!("decoration color '{color}' is not #rrggbb or #rrggbbaa"))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
items
|
||||
.iter_mut()
|
||||
.for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some()));
|
||||
// An item with its own colors (API 1.17) may leave the style empty.
|
||||
items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some()));
|
||||
if items.iter().any(|d| d.range.start > d.range.end) {
|
||||
return Err(HostError::Invalid("reversed decoration range".into()));
|
||||
}
|
||||
@@ -4924,6 +4935,13 @@ impl PluginApi {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A `set-styled` color as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case.
|
||||
fn decoration_color(color: &str) -> Option<String> {
|
||||
let hex = color.strip_prefix('#')?;
|
||||
((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.then(|| format!("#{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
fn decoration_style(style: &str) -> bool {
|
||||
matches!(
|
||||
style,
|
||||
@@ -5058,9 +5076,38 @@ mod workbench_tests {
|
||||
hover: None,
|
||||
after: Some("after".into()),
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
};
|
||||
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
|
||||
// Styled items (API 1.17): colors are validated and normalized; an empty style needs colors.
|
||||
let colored = |style: &str, foreground: Option<&str>, background: Option<&str>| ide_plugin::Decoration {
|
||||
colors: Some(ide_plugin::DecorationColors {
|
||||
foreground: foreground.map(Into::into),
|
||||
background: background.map(Into::into),
|
||||
}),
|
||||
..item(style)
|
||||
};
|
||||
api.decorations(
|
||||
Some(&path),
|
||||
"styled",
|
||||
vec![
|
||||
colored("", Some("#1A1A1A"), Some("#FFEB3BFF")),
|
||||
colored("highlight", None, Some("#00e5ff")),
|
||||
colored("", None, None),
|
||||
item(""),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let styled = api.shared.decoration_sets()["test"].iter().find(|s| s.set_id == "styled").unwrap().items.clone();
|
||||
assert_eq!(styled.len(), 2);
|
||||
let first = styled[0].colors.as_ref().unwrap();
|
||||
assert_eq!((first.foreground.as_deref(), first.background.as_deref()), (Some("#1a1a1a"), Some("#ffeb3bff")));
|
||||
for bad in ["red", "#fff", "#12345g", "rgb(0,0,0)", "#1234567", "#ffffff; x: y"] {
|
||||
let err = api.decorations(Some(&path), "styled", vec![colored("", Some(bad), None)]).unwrap_err();
|
||||
assert!(matches!(err, HostError::Invalid(ref m) if m.contains("#rrggbb")), "{bad}: {err}");
|
||||
}
|
||||
api.decorations(None, "styled", vec![]).unwrap();
|
||||
// Decorations follow the file: a path outside the open project is accepted too.
|
||||
api.decorations(Some(&root.join("../outside.txt")), "set", vec![]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"].len(), 2);
|
||||
|
||||
@@ -385,6 +385,9 @@ impl PluginHost {
|
||||
}
|
||||
);
|
||||
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
|
||||
if let Some(mirror) = &candidate.mirror {
|
||||
mirror::report(mirror, fetched.is_ok());
|
||||
}
|
||||
if let Err(e) = &fetched {
|
||||
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
|
||||
}
|
||||
|
||||
@@ -2006,7 +2006,7 @@ fn with_gradle_roots(
|
||||
use ide_build::gradle::ReportedRoot;
|
||||
use ide_workspace::roots::RootKind;
|
||||
let mut out: Vec<SourceFolder> = Vec::new();
|
||||
for (dir, kind) in ide_build::gradle_source_roots(root, build_cache, settings) {
|
||||
for (dir, kind, project) in ide_build::gradle_source_roots(root, build_cache, settings) {
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
@@ -2019,7 +2019,16 @@ fn with_gradle_roots(
|
||||
ReportedRoot::Excluded => RootKind::Excluded,
|
||||
};
|
||||
if !out.iter().any(|f| f.path == path) {
|
||||
out.push(SourceFolder { path, kind, detected_from: Some("Gradle".into()) });
|
||||
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
|
||||
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
|
||||
// the UI reads the folder as project-relative.
|
||||
let detected_from = match project.strip_prefix(root) {
|
||||
Ok(rel) if !rel.as_os_str().is_empty() => {
|
||||
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
|
||||
}
|
||||
_ => "Gradle".into(),
|
||||
};
|
||||
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
|
||||
}
|
||||
}
|
||||
out.extend(detected.iter().filter(|d| !out.iter().any(|o| o.path == d.path)).cloned().collect::<Vec<_>>());
|
||||
@@ -2399,6 +2408,48 @@ mod gradle_roots_tests {
|
||||
use super::*;
|
||||
use ide_workspace::RootKind;
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_keep_the_module_they_belong_to() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let cache = root.join(".cache");
|
||||
for d in [root.join("src/main/java"), root.join("lib/src/main/java"), root.join("lib/build"), cache.clone()] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(root.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(root.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":lib", "dir": s(root.join("lib")), "buildDir": s(root.join("lib/build")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(root.join("lib/src/main/java"))], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
// What static detection reports for this layout before the first sync.
|
||||
let detected = [
|
||||
SourceFolder {
|
||||
path: "src/main/java".into(),
|
||||
kind: RootKind::Source,
|
||||
detected_from: Some("build.gradle".into()),
|
||||
},
|
||||
SourceFolder {
|
||||
path: "lib/src/main/java".into(),
|
||||
kind: RootKind::Source,
|
||||
detected_from: Some("lib/build.gradle".into()),
|
||||
},
|
||||
];
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &detected);
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.as_str(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/main/java", Some("Gradle")),
|
||||
("lib/src/main/java", Some("lib/Gradle")),
|
||||
("lib/build", Some("lib/Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_win_and_reach_outside_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2422,14 +2473,15 @@ mod gradle_roots_tests {
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<(String, RootKind)> = out.iter().map(|f| (f.path.clone(), f.kind)).collect();
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
|
||||
// A project outside the root is not a module the UI could address.
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/it/java".into(), RootKind::Test),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source),
|
||||
(abs(svc.join("build")), RootKind::Excluded),
|
||||
("web".into(), RootKind::Source),
|
||||
("src/it/java".into(), RootKind::Test, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
|
||||
("web".into(), RootKind::Source, None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
|
||||
pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
|
||||
use std::io::Read;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -182,6 +183,11 @@ pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Optio
|
||||
cmd.env_remove(k);
|
||||
}
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
// An interactive shell takes job control from its inherited terminal. A new session leaves it
|
||||
// without a controlling terminal, so it cannot stop its parent's process group with SIGTTIN.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| rustix::process::setsid().map(|_| ()).map_err(Into::into));
|
||||
}
|
||||
let mut child = cmd
|
||||
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
|
||||
.stdin(Stdio::null())
|
||||
@@ -271,6 +277,36 @@ mod tests {
|
||||
assert_eq!(get(&third, "OPENIDEA_TEST_SEEN").as_deref(), Some("unset"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_shell_gets_a_new_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (shell, rc) = fake_shell(tmp.path());
|
||||
// macOS `ps` has no session id column; a session leader also leads its own process group.
|
||||
let column = if cfg!(target_os = "linux") { "sid" } else { "pgid" };
|
||||
std::fs::write(
|
||||
&rc,
|
||||
format!("export OPENIDEA_TEST_PID=$$\nexport OPENIDEA_TEST_SID=$(ps -o {column}= -p $$)\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let env = read_login_env(&shell, Duration::from_secs(10)).unwrap();
|
||||
let get = |k: &str| {
|
||||
env.iter()
|
||||
.find(|(name, _)| name == k)
|
||||
.map(|(_, value)| value.to_string_lossy().trim().parse::<i32>().unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let shell_pid = get("OPENIDEA_TEST_PID");
|
||||
let shell_sid = get("OPENIDEA_TEST_SID");
|
||||
let test_sid = if cfg!(target_os = "linux") {
|
||||
rustix::process::getsid(None).unwrap().as_raw_nonzero().get()
|
||||
} else {
|
||||
rustix::process::getpgrp().as_raw_nonzero().get()
|
||||
};
|
||||
|
||||
assert_eq!(shell_sid, shell_pid);
|
||||
assert_ne!(shell_sid, test_sid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shell_that_hangs_times_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1572,7 +1572,7 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
|
||||
id: "serve".into(),
|
||||
name: "serve stock".into(),
|
||||
kind: "shell".into(),
|
||||
command: "sleep 30".into(),
|
||||
command: "cat".into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
@@ -1598,11 +1598,11 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
|
||||
// The call still waits for the run: it holds the project first, the run second.
|
||||
let held = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
|
||||
assert_eq!(held.kept_open_by, Some(ide_host::mcp::McpBackgroundHold::Request));
|
||||
h.host.processes.stop(run.id).unwrap();
|
||||
h.host.processes.close_stdin(run.id).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(call, observe);
|
||||
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
|
||||
assert!(result["exitCode"].is_number() || result["exitCode"].is_null(), "{result}");
|
||||
assert_eq!(result["exitCode"], 0, "{result}");
|
||||
let loaded = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
|
||||
assert_eq!(loaded.kept_open_by, None, "the call is over and the run has exited");
|
||||
}
|
||||
@@ -7010,6 +7010,31 @@ fn markdown_decorations_publish_a_hover_card_and_clear() {
|
||||
assert!(f.host.decoration_sets()["decorations"].is_empty());
|
||||
}
|
||||
|
||||
/// API 1.17: `set-styled` items carry their own colors, normalized by the host, and replace
|
||||
/// the set's earlier kind of items.
|
||||
#[test]
|
||||
fn styled_decorations_carry_normalized_colors() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("decorations"));
|
||||
f.run("decorations", "publish", Some("src/notes.txt")).unwrap();
|
||||
f.run("decorations", "styled", Some("src/notes.txt")).unwrap();
|
||||
let sets = f.host.decoration_sets();
|
||||
let set = &sets["decorations"][0];
|
||||
assert_eq!(set.set_id, "example");
|
||||
let colors: Vec<_> = set.items.iter().map(|d| (d.style.as_str(), d.colors.clone().unwrap())).collect();
|
||||
assert_eq!(
|
||||
colors,
|
||||
[
|
||||
(
|
||||
"",
|
||||
ide_plugin::DecorationColors { foreground: Some("#1a1a1a".into()), background: Some("#ffeb3b".into()) }
|
||||
),
|
||||
("", ide_plugin::DecorationColors { foreground: None, background: Some("#00e5ff80".into()) }),
|
||||
]
|
||||
);
|
||||
f.run("decorations", "clear", None).unwrap();
|
||||
}
|
||||
|
||||
// ─── Project window groups ────────────────────────────────────────────────────
|
||||
// A group's container root holds only `.openidea` metadata; the files live in
|
||||
// the member projects. The plugin surface reaches them like the editor and the
|
||||
|
||||
@@ -745,7 +745,18 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let old_open = || async {
|
||||
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
|
||||
// bind() creates the socket file before listen(): a connect in between is refused.
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
|
||||
@@ -308,6 +308,18 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
assert!(found.iter().any(|d| d["type"] == "file"), "{found:?}");
|
||||
assert_eq!(found.last().unwrap()["type"], "done");
|
||||
|
||||
// HTTP Client requests and their history are served by the project host.
|
||||
let history = invoke(&peer, "http_history", json!({})).await.unwrap();
|
||||
assert_eq!(history, json!([]));
|
||||
let curl = invoke(
|
||||
&peer,
|
||||
"http_curl",
|
||||
json!({ "path": null, "text": "GET http://localhost/x\n", "index": 0, "env": null }),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(curl.as_str().unwrap().contains("http://localhost/x"), "{curl}");
|
||||
|
||||
// A run's output streams through a channel and its exit is an event.
|
||||
let config = json!({ "id": "echo", "name": "echo", "kind": "shell", "command": "echo", "args": ["remote-hi"],
|
||||
"cwd": null, "env": {}, "detected": false, "isTest": false, "debugAdapter": null });
|
||||
@@ -371,6 +383,14 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"remote_mkdir",
|
||||
"remote_rename",
|
||||
"remote_download_into",
|
||||
"http_environments",
|
||||
"http_execute",
|
||||
"http_history",
|
||||
"http_history_get",
|
||||
"http_history_clear",
|
||||
"http_curl",
|
||||
"http_environment_file",
|
||||
"http_variable_definitions",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
@@ -387,6 +407,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_schemas",
|
||||
"db_tables",
|
||||
"db_table_details",
|
||||
"db_table_grants",
|
||||
"db_ddl",
|
||||
"db_schema_objects",
|
||||
"db_object_ddl",
|
||||
|
||||
@@ -378,6 +378,23 @@ fn binary_and_huge_files_are_listed_without_symbols() {
|
||||
assert_eq!(idx.status().symbols, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_files_are_classified_from_their_head_and_text_is_read_past_it() {
|
||||
let fx = Fixture::new(&[("img/logo.rs", "")]);
|
||||
let mut binary = b"fn head() {}\0".to_vec();
|
||||
binary.extend(std::iter::repeat_n(b'x', 64 * 1024));
|
||||
std::fs::write(fx.root.join("img/logo.rs"), &binary).unwrap();
|
||||
let long = format!("{}fn past_the_sniff() {{}}\n", "// pad\n".repeat(2000));
|
||||
assert!(long.len() > 8192);
|
||||
fx.write("src/long.rs", &long);
|
||||
let idx = fx.open();
|
||||
assert_eq!(symbols(&idx, "past_the_sniff", SymbolFilter::All), vec!["past_the_sniff"]);
|
||||
assert!(symbols(&idx, "head", SymbolFilter::All).is_empty());
|
||||
let data = idx.shared.data.read();
|
||||
let logo = data.files.iter().flatten().find(|entry| entry.rel.as_ref() == "img/logo.rs").unwrap();
|
||||
assert_eq!(logo.hash, [0; 32], "a binary file is not read whole to be hashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_to_file_finds_ignored_files_but_not_their_symbols() {
|
||||
let fx = Fixture::new(&[
|
||||
|
||||
@@ -29,6 +29,8 @@ static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
|
||||
|
||||
/// Files larger than this are listed but not parsed for symbols.
|
||||
pub const MAX_SYMBOL_FILE: u64 = 2 * 1024 * 1024;
|
||||
/// Leading bytes checked for NUL to tell a binary file from text.
|
||||
const BINARY_SNIFF: usize = 8192;
|
||||
const CHUNK: usize = 512;
|
||||
/// Insert/persist batch of the initial scan's streaming pass.
|
||||
const SCAN_BATCH: usize = 2048;
|
||||
@@ -180,7 +182,7 @@ impl Shared {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if !fast {
|
||||
if let Err(reason) = fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
@@ -192,6 +194,7 @@ impl Shared {
|
||||
if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "fallback",
|
||||
reason,
|
||||
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
|
||||
walk_ms = walk_elapsed.as_millis() as u64,
|
||||
hydration_ms = hydration_elapsed.as_millis() as u64,
|
||||
@@ -259,25 +262,26 @@ impl Shared {
|
||||
|
||||
/// Warm start: validate the snapshot's flat directory/file manifest and hydrate
|
||||
/// without walking the tree. A changed scope, symlink, directory mtime, file
|
||||
/// mtime or file size falls back to the full walk.
|
||||
fn try_fast_start(&self) -> bool {
|
||||
/// mtime or file size falls back to the full walk; the error says which, for
|
||||
/// the start-up log.
|
||||
fn try_fast_start(&self) -> Result<(), &'static str> {
|
||||
let started = Instant::now();
|
||||
let Some(store) = &self.store else { return false };
|
||||
let Some(store) = &self.store else { return Err("no cache") };
|
||||
let load_started = Instant::now();
|
||||
let Some(snapshot) = store.load_snapshot() else { return false };
|
||||
let Some(snapshot) = store.load_snapshot() else { return Err("no snapshot for this build") };
|
||||
let loaded = load_started.elapsed();
|
||||
let filter = self.filter();
|
||||
if filter.has_extra_roots() || snapshot.filter() != filter.stamp() {
|
||||
return false;
|
||||
return Err("index scope changed");
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return false };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
|
||||
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
|
||||
return false;
|
||||
return Err("directory changed");
|
||||
}
|
||||
}
|
||||
let external = crate::store::external_ignore_candidates(root);
|
||||
@@ -288,19 +292,19 @@ impl Shared {
|
||||
if external.len() != saved_external.len()
|
||||
|| external.iter().zip(&saved_external).any(|(path, saved)| path.to_string_lossy() != **saved)
|
||||
{
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
for i in 0..snapshot.ignore_len() {
|
||||
let path = Path::new(snapshot.ignore_path(i));
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let present = meta.is_some();
|
||||
if present != snapshot.ignore_present(i) {
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
if let Some(meta) = meta
|
||||
&& (mtime_of(&meta) != snapshot.ignore_mtime(i) || meta.len() != snapshot.ignore_size(i))
|
||||
{
|
||||
return false;
|
||||
return Err("ignore files changed");
|
||||
}
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
@@ -320,7 +324,7 @@ impl Shared {
|
||||
});
|
||||
let built = build_started.elapsed();
|
||||
if entries.iter().any(Option::is_none) {
|
||||
return false;
|
||||
return Err("file changed");
|
||||
}
|
||||
let validated = entries;
|
||||
let mut entries = Vec::with_capacity(validated.len());
|
||||
@@ -372,7 +376,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
r.truncate(MAX_RECENT);
|
||||
true
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_recent(&self, store: &Store, root: &Path) {
|
||||
@@ -902,22 +906,32 @@ impl Shared {
|
||||
if f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec, Extraction::Oversized);
|
||||
}
|
||||
// Sniff the head first: a binary file is classified from its first
|
||||
// `BINARY_SNIFF` bytes alone, so it is never read whole or hashed.
|
||||
let mut bytes = Vec::with_capacity(f.size as usize);
|
||||
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
|
||||
Ok(_) => {}
|
||||
let read = std::fs::File::open(&f.path).and_then(|mut file| {
|
||||
(&mut file).take(BINARY_SNIFF as u64).read_to_end(&mut bytes)?;
|
||||
if bytes.contains(&0) {
|
||||
return Ok(true);
|
||||
}
|
||||
file.read_to_end(&mut bytes).map(|_| false)
|
||||
});
|
||||
let binary = match read {
|
||||
Ok(binary) => binary,
|
||||
Err(e) => {
|
||||
tracing::debug!("index: cannot read {}: {e}", f.path.display());
|
||||
return Extracted::New(rec, Extraction::ReadFailed);
|
||||
}
|
||||
};
|
||||
if binary {
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
rec.hash = *blake3::hash(&bytes).as_bytes();
|
||||
if prev_hash == Some(rec.hash) {
|
||||
return Extracted::Unchanged;
|
||||
}
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
if bytes[..bytes.len().min(8192)].contains(&0) {
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
|
||||
if self.syntax.has_symbols(&lang) {
|
||||
@@ -1462,7 +1476,7 @@ mod metric_tests {
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert!(index.try_fast_start());
|
||||
assert_eq!(index.try_fast_start(), Ok(()));
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
|
||||
@@ -357,7 +357,7 @@ const GRADLE_TOOLING_FAILURES: [&str; 4] = [
|
||||
fn launch_message(message: &str) -> String {
|
||||
let mut lines = message.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
let first = lines.next().unwrap_or_default();
|
||||
match lines.last() {
|
||||
match lines.next_back() {
|
||||
Some(cause) if GRADLE_TOOLING_FAILURES.iter().any(|m| first.contains(m)) => format!("{first} Cause: {cause}"),
|
||||
_ => first.to_owned(),
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.16";
|
||||
pub const API_VERSION: &str = "1.17";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
|
||||
@@ -1023,6 +1023,15 @@ pub struct Decoration {
|
||||
/// Markdown rendered in the editor's hover card (API 1.16); `hover` is the
|
||||
/// plain-text fallback shown when this is absent.
|
||||
pub markdown_hover: Option<String>,
|
||||
/// The item's own colors (API 1.17 `set-styled`), validated `#rrggbb` / `#rrggbbaa`.
|
||||
#[serde(default)]
|
||||
pub colors: Option<DecorationColors>,
|
||||
}
|
||||
/// Colors of a styled editor decoration (API 1.17).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct DecorationColors {
|
||||
pub foreground: Option<String>,
|
||||
pub background: Option<String>,
|
||||
}
|
||||
/// A tree decoration.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -2888,6 +2888,7 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
@@ -2906,6 +2907,28 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: d.markdown_hover,
|
||||
colors: None,
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
}
|
||||
fn set_styled(
|
||||
&mut self,
|
||||
path: String,
|
||||
set_id: String,
|
||||
items: Vec<bindings::openidea::plugin::decorations::StyledDecoration>,
|
||||
) -> Fallible<()> {
|
||||
let items = items
|
||||
.into_iter()
|
||||
.map(|d| crate::Decoration {
|
||||
range: core_range(d.range),
|
||||
style: d.style,
|
||||
hover: d.hover,
|
||||
after: d.after,
|
||||
markdown_hover: d.markdown_hover,
|
||||
colors: d
|
||||
.colors
|
||||
.map(|c| crate::DecorationColors { foreground: c.foreground, background: c.background }),
|
||||
})
|
||||
.collect();
|
||||
self.replace_decorations(path, set_id, items)
|
||||
|
||||
@@ -95,7 +95,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.16.0");
|
||||
let host = v("1.17.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -112,15 +112,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.14.0",
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
"1.17.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.17.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.17") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.18.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.18") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.16 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.17 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
|
||||
98e9c2b886df177bafb68a712fc1efadc4f3a7b82e8425cd1b3f4c2355bdb785
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
6edda84fad0ee7cd56a3a28b55e6c559db7b7f6b9c8c0ca645be805b545c01e7
|
||||
bb77bc0963451ca4259591bf68c72ae3eb70b1c6f855fa29dfc84d2be675404c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ecc6b6c52753b11521ae033a5a66c2a289119e09e07d22742203d3a13122dd97
|
||||
f381b0e20520bccf5acd46b95641f5542885184352e52ec2fed3fd53665c353b
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
4ec581c69a62bbf424983e241a79d0bfdb5d025a3e86d27eea745adcb1906253
|
||||
f72a53e7b800b8c5408c7ac67034821f814da7b1d66f527949450431bcf52e02
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
5fb89ee3d07e4275433ad9ad930ad781ef4f227af11aa5eb9dfc9174c015b1b8
|
||||
3cd2f02738b07d9a6294025cbcc6e906716d3e91db50a6f39485df9b1d6a4ead
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
236db5a85d3e7e9fee01c3ff0b9f5e66fad7e3d64fa618a0c1c980d9e5883839
|
||||
d77b80884163628791b292acc59324d3b9a7c2236034b88f87e8f56af5929a48
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
4f89bd09b571016cbb9feb0674e668aa66996997c6b53a91d1a4ffbf161083a3
|
||||
5a79d35e9fc1560a39b6459312a14c27c73739fd385f6c2568f9b1c1bf8fe4a1
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "decorations"
|
||||
name = "Decoration example"
|
||||
version = "0.1.0"
|
||||
description = "Minimal plugin API 1.16 example: line-end labels with Markdown hover cards."
|
||||
description = "Minimal plugin API 1.17 example: line-end labels with Markdown hover cards and their own colors."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
engines.openidea = "^1.16"
|
||||
engines.openidea = "^1.17"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
|
||||
@@ -15,6 +15,10 @@ required = ["project.read"]
|
||||
id = "publish"
|
||||
title = "Decorations: Publish"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "styled"
|
||||
title = "Decorations: Publish Styled"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "clear"
|
||||
title = "Decorations: Clear"
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Minimal plugin API 1.16 example: push a line-end label whose hover is Markdown.
|
||||
//! Minimal plugin API 1.17 example: push a line-end label whose hover is Markdown,
|
||||
//! and ranges painted in the plugin's own colors.
|
||||
|
||||
use openidea_plugin::{Error, Invocation, MarkdownDecoration, Plugin, Position, Range, host, register_plugin};
|
||||
use openidea_plugin::{
|
||||
DecorationColors, Error, Invocation, MarkdownDecoration, Plugin, Position, Range, StyledDecoration, host,
|
||||
register_plugin,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Decorations;
|
||||
@@ -23,6 +27,29 @@ impl Plugin for Decorations {
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"styled" => {
|
||||
let path = arg.ok_or_else(|| Error::Invalid("a project file path is required".into()))?;
|
||||
let todo = |range, foreground: Option<&str>, background: &str| StyledDecoration {
|
||||
range,
|
||||
style: String::new(),
|
||||
hover: Some("TODO".into()),
|
||||
after: None,
|
||||
markdown_hover: None,
|
||||
colors: Some(DecorationColors {
|
||||
foreground: foreground.map(Into::into),
|
||||
background: Some(background.into()),
|
||||
}),
|
||||
};
|
||||
host::set_styled_decorations(
|
||||
path,
|
||||
"example",
|
||||
&[
|
||||
todo(Range::new(Position::new(0, 0), Position::new(0, 1)), Some("#1A1A1A"), "#FFEB3B"),
|
||||
todo(Range::new(Position::new(0, 1), Position::new(0, 2)), None, "#00e5ff80"),
|
||||
],
|
||||
)?;
|
||||
Ok(None)
|
||||
}
|
||||
"clear" => {
|
||||
host::clear_decorations("example")?;
|
||||
Ok(None)
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
c5c3bac9e2b69e4957bd5049d4f560dd04faf4dfc2d7523bb7968aa29f3bdcfb
|
||||
264be0e527b0cc200e2d97e982b7b297ef6181a7669506ccf09159531f91124d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a75758a44e255b7df3adf53e5f81b8f1283270d28f78ad0d8b358d9feea98a99
|
||||
6230dce145f2cce3033c4797566cbbff8c98e5d8c85d41f9342693b19a10b638
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7e658a971fd58b84fcadc1f4939991d5f4506936989d4c8a7302ccebc0455e9c
|
||||
3d7d853fa40ce14ae6781dbf5607153c4f38b2663a31f1ca29a753e8eba79f03
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
6b7c0d8971cfd3ba1d80c5fc6428e5890c820350972597a11be4ea6f0324973f
|
||||
a128c5f640b42d323059a7be1bd2e89cb9de1ea1ea635b5af4e9f69b66bfd04c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
20e43b6ac3aaa1527874f98f4b502ef88dd4676b6096b989c7bfba7a521e723d
|
||||
9e00f4bcad39a99f05c35ac66962a574f7edd5713f1aa404ef72fd7ef945d1e8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f879df5a331ec439c7e74af4d9c7d249477239e3a0a59d5e612548623cf5e9e2
|
||||
7e0ae6bfc8217c37a68e9010920a5bd3478f654b6cfaf3f54e0ef5aacae546b8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
de1fc37d8fd5993164e0d903a0f1b4ba15005f2a90de325d7f4b4902a363fdf1
|
||||
97c4d6aaf88d552d736021e21bb1f1e1594800ceb771644eb1f3356c0efbc42a
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
367366c14b69d8f3837e731e061768ec5cb344d86fba89ced63fb196e5ca475e
|
||||
5a65f921bb1f0ed0f0f10811f8960d9ea9e7ded59d5172356e7cc93f05b4bd5e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b7bccc7f93b409263293d2dff8a31dbdcfcdfba133815f3ff60bc70a073257de
|
||||
2d148151a9b0a2ab4c479183e3d2ab07d0432d8645dbf95c0e04385ef25830d8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f28d85f2004adcdf4e43faa57b7a5b52ab5d8233579979062461b0c5b4c63e10
|
||||
63136a78f4279b140c74ff07146b79ca2ce6c7a4fffd6176e811828aad911e0e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
23c2c5e6e208104979e1f5b8620d2279547d372f0accf893c2d7797399fe39b0
|
||||
e6bf5c74e18ab47577c1e88294fa4961fe8a1e56fb3e34fec5154dab74dfd805
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
57fc9ea26136a56fa2f502e4bb17531df3f5eed092fde1267199e2447c8fbc23
|
||||
ad5a9fef07a6e9db8fe0375d0ba9d2e92247c28303876ac52db2dbf938bf96ae
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
105017e20dd7a93cecb178576f2718ccf8433a6fac027b5708d6e2121f85e27a
|
||||
fdbcd1afce0d106be463ef43d31245fcb4b9e84287ede78fb8abe740ea28b247
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ae72f5db42f508bd8faac6134f6e9a785a8fdcdda823af32cb56e5936c157bf9
|
||||
c9eb17c9f7e334b05bc5104204fb12a88dceafe36dbd04510e439539f2a1d464
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
d773509ce0beebc88b769d8346aaafa39b1201d959c4afd16d680c63cef919d5
|
||||
14ba72bbc8013b8e2a7f87e85a7046edc4fb4a2256f3fae3ac735241096e4428
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1b15f24dc006f18260c746d9651cdaa2416e7871397e21f2935f50d316b88f67
|
||||
91b190eb62077bde52916a09d76a474584725e73cf3acf45613aecbc8c37c421
|
||||
Loaded 100 of 675 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача