дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
115
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c8757d9a5c | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a |
No files matched your search
@@ -39,6 +39,7 @@ on:
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -106,7 +107,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Створено
+49
-48
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4544,7 +4544,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4563,7 +4563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4586,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4598,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4614,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4623,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4634,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4693,7 +4693,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4704,6 +4704,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-jvm-inspect",
|
||||
"ide-language",
|
||||
"ide-sdk",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
@@ -4722,7 +4723,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4741,7 +4742,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4762,7 +4763,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4784,7 +4785,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4798,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4818,7 +4819,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4843,7 +4844,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4859,7 +4860,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4885,7 +4886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4906,7 +4907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4919,7 +4920,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4944,7 +4945,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4957,7 +4958,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4973,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4986,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4999,7 +5000,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5022,7 +5023,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5044,7 +5045,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5071,7 +5072,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5087,7 +5088,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6726,7 +6727,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -627,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -5105,7 +5105,8 @@ fn tool_event(
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
|
||||
entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
@@ -5120,6 +5121,7 @@ fn tool_event(
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
command: command.clone(),
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
|
||||
@@ -547,6 +547,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
|
||||
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
|
||||
@@ -455,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
|
||||
@@ -740,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -289,7 +289,18 @@ fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -1304,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -4369,6 +4369,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
|
||||
@@ -91,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -154,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -171,6 +172,11 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -471,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
|
||||
@@ -323,7 +323,8 @@ mod tests {
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let a = root.join("packages/a");
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
@@ -336,14 +337,14 @@ mod tests {
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages/b");
|
||||
let b = root.join("packages").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -505,6 +505,19 @@ pub struct LanguageCodeStyle {
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -562,6 +575,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -572,10 +604,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -13,13 +13,34 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -99,6 +99,20 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -1426,6 +1448,9 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1438,6 +1463,7 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -859,6 +859,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -901,6 +902,9 @@ impl DebugManager {
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
if debugpy::listens(&config.adapter, &config.request, &arguments) {
|
||||
debugpy::require_free_port(&arguments).await?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -1149,6 +1153,9 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
if debugpy::listens(&session.adapter, &session.request, &arguments) {
|
||||
session.debugpy_version_unchecked.store(true, Ordering::Release);
|
||||
}
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -316,6 +318,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
|
||||
@@ -127,7 +127,10 @@ mod tests {
|
||||
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
|
||||
CatalogSchema {
|
||||
name: name.into(),
|
||||
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
|
||||
tables: tables
|
||||
.iter()
|
||||
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -655,7 +655,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
@@ -664,12 +664,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
// Bridges built before the comment column send five fields.
|
||||
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
@@ -684,16 +687,18 @@ mod tests {
|
||||
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let mut commented = row("orders", "note", "1", Some("'none'"));
|
||||
commented.push(Some("free text".into()));
|
||||
let mut blank = row("items", "sku", "1", None);
|
||||
blank.push(Some(" ".into()));
|
||||
let by_table =
|
||||
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
|
||||
assert_eq!(by_table["items"][0].comment, None);
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -146,6 +146,10 @@ pub struct SchemaObject {
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub kind: DbTableKind,
|
||||
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -208,6 +212,10 @@ pub struct CompletionColumn {
|
||||
pub primary_key: bool,
|
||||
/// Has a default (or is generated): optional in INSERT.
|
||||
pub has_default: bool,
|
||||
/// The column's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -568,6 +576,18 @@ impl DbManager {
|
||||
None => {}
|
||||
}
|
||||
source::save(&self.root, &project)?;
|
||||
if let Ok(mut folders) = source::load_folders(&self.root) {
|
||||
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
|
||||
let mut changed = false;
|
||||
for folder in &mut folders {
|
||||
let before = folder.sources.len();
|
||||
folder.sources.retain(|id| known.contains(id.as_str()));
|
||||
changed |= folder.sources.len() != before;
|
||||
}
|
||||
if changed {
|
||||
source::save_folders(&self.root, &folders)?;
|
||||
}
|
||||
}
|
||||
old
|
||||
};
|
||||
for o in old {
|
||||
@@ -1103,7 +1123,11 @@ impl DbManager {
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
|
||||
Some(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
|
||||
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -1410,10 +1434,13 @@ impl DbManager {
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind)]) => {
|
||||
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
|
||||
}
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
comment.clone(),
|
||||
),
|
||||
_ => return Err(missing()),
|
||||
};
|
||||
if kind == "v" || kind == "m" {
|
||||
@@ -1434,6 +1461,7 @@ impl DbManager {
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -1447,7 +1475,18 @@ impl DbManager {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1495,6 +1534,7 @@ impl DbManager {
|
||||
nullable: flag(&Some(next())),
|
||||
primary_key: flag(&Some(next())),
|
||||
has_default: flag(&Some(next())),
|
||||
comment: Some(next()).filter(|c| !c.trim().is_empty()),
|
||||
};
|
||||
if name.is_empty() || column.name.is_empty() {
|
||||
continue;
|
||||
|
||||
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
|
||||
Ok(shown
|
||||
.records()
|
||||
.filter_map(|r| {
|
||||
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
|
||||
Some(TableInfo {
|
||||
name: r.get("name")?.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -238,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
|
||||
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
|
||||
continue;
|
||||
};
|
||||
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
|
||||
out[index].tables.push(TableInfo {
|
||||
name: name.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
for schema in &mut out {
|
||||
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
@@ -447,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
|
||||
primary_key: false,
|
||||
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|
||||
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
|
||||
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
Ok(tables)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
|
||||
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
|
||||
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
|
||||
//! Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! the others only in memory for the session.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A user folder grouping data sources in one project's Database tree.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbSourceFolder {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Reserved for nested folders; the first UI version only creates root folders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<String>,
|
||||
pub order: i32,
|
||||
pub sources: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SourceFoldersFile {
|
||||
#[serde(default = "folders_version")]
|
||||
version: u32,
|
||||
#[serde(default, rename = "folder")]
|
||||
folders: Vec<DbSourceFolder>,
|
||||
}
|
||||
|
||||
fn folders_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// The project's data source folders and their members.
|
||||
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let file: SourceFoldersFile =
|
||||
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
if file.version > 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: folder format version {} is newer than this OpenIDEA",
|
||||
path.display(),
|
||||
file.version
|
||||
)));
|
||||
}
|
||||
Ok(file.folders)
|
||||
}
|
||||
|
||||
/// Replaces the project's data source folders after validating ids, parents and memberships.
|
||||
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
validate_folders(folders)?;
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
|
||||
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&tmp, text)?;
|
||||
if let Err(e) = std::fs::rename(&tmp, &path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
let mut ids = HashSet::new();
|
||||
let mut members = HashSet::new();
|
||||
for folder in folders {
|
||||
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source folder needs an id and a name"));
|
||||
}
|
||||
if !ids.insert(folder.id.as_str()) {
|
||||
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
|
||||
}
|
||||
for source in &folder.sources {
|
||||
if source.is_empty() {
|
||||
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
|
||||
}
|
||||
if !members.insert(source.as_str()) {
|
||||
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for folder in folders {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parent = folder.parent.as_deref();
|
||||
while let Some(id) = parent {
|
||||
if id == folder.id || !seen.insert(id) {
|
||||
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
|
||||
}
|
||||
parent =
|
||||
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
|
||||
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"data source folder '{}' has an unknown parent '{id}'",
|
||||
folder.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
|
||||
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
|
||||
#[cfg(test)]
|
||||
@@ -724,6 +828,38 @@ mod tests {
|
||||
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_folders_round_trip_and_reject_invalid_memberships() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let folders = vec![
|
||||
DbSourceFolder {
|
||||
id: "prod".into(),
|
||||
name: "Production".into(),
|
||||
parent: None,
|
||||
order: 0,
|
||||
sources: vec!["pg".into(), "mysql".into()],
|
||||
},
|
||||
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
|
||||
];
|
||||
save_folders(tmp.path(), &folders).unwrap();
|
||||
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
|
||||
|
||||
let duplicate = vec![
|
||||
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
|
||||
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &duplicate).is_err());
|
||||
|
||||
let cycle = vec![
|
||||
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
|
||||
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &cycle).is_err());
|
||||
|
||||
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
|
||||
assert!(save_folders(tmp.path(), &missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_configs_written_before_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+158
-29
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
|
||||
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
|
||||
pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
|
||||
WHERE database = {} AND is_temporary = 0 ORDER BY name",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
|
||||
quote_ident(driver, schema)
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
|
||||
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
|
||||
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema),
|
||||
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
|
||||
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Postgres => format!(
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
|
||||
obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CAST(ep.value AS nvarchar(max)) \
|
||||
FROM INFORMATION_SCHEMA.TABLES t \
|
||||
LEFT JOIN sys.extended_properties ep \
|
||||
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
|
||||
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
|
||||
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -301,7 +307,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
@@ -312,7 +318,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
@@ -325,7 +331,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
|
||||
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
@@ -336,7 +342,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
@@ -351,7 +357,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
@@ -361,7 +367,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
@@ -372,8 +378,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
|
||||
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
@@ -658,21 +666,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relname = {}",
|
||||
quote_literal(DbDriver::Postgres, schema),
|
||||
quote_literal(DbDriver::Postgres, name)
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
|
||||
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
@@ -695,6 +704,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
|
||||
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
|
||||
/// changed (`relacl` null) grants none.
|
||||
pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
|
||||
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
|
||||
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
|
||||
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
|
||||
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
@@ -934,6 +964,18 @@ pub struct DdlColumn {
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
pub comment: Option<String>,
|
||||
pub owner: Option<String>,
|
||||
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
|
||||
pub grants: Vec<(String, String, bool)>,
|
||||
/// `CREATE TRIGGER …` statements.
|
||||
pub triggers: Vec<String>,
|
||||
}
|
||||
|
||||
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
|
||||
@@ -943,6 +985,7 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let mut items: Vec<String> = columns
|
||||
@@ -959,9 +1002,31 @@ pub fn postgres_table_ddl(
|
||||
})
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
|
||||
for i in indexes {
|
||||
out.push_str(&format!("\n{i};\n"));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
|
||||
if let Some(comment) = &extras.comment {
|
||||
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
for c in columns {
|
||||
if let Some(comment) = &c.comment {
|
||||
let column = format!("{target}.{}", quote_ident(d, &c.name));
|
||||
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
}
|
||||
if let Some(owner) = &extras.owner {
|
||||
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
|
||||
}
|
||||
if !extras.grants.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
for (grantee, privileges, grantable) in &extras.grants {
|
||||
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
|
||||
let option = if *grantable { " with grant option" } else { "" };
|
||||
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
|
||||
}
|
||||
for statement in indexes.iter().chain(&extras.triggers) {
|
||||
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -988,6 +1053,24 @@ mod tests {
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
|
||||
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
|
||||
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
|
||||
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
// Completion (the hover card of a table or column) carries them too, as the ninth field.
|
||||
let completion = |driver| completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
|
||||
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
|
||||
assert!(
|
||||
completion(DbDriver::Oracle).contains("cc.comments")
|
||||
&& completion(DbDriver::Oracle).contains("all_col_comments")
|
||||
);
|
||||
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
|
||||
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
|
||||
}
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
@@ -1015,6 +1098,7 @@ mod tests {
|
||||
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
|
||||
let relations = tables(driver, "event's\\db");
|
||||
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
|
||||
assert!(relations.contains(r"END, comment FROM system.tables"));
|
||||
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
|
||||
let fields = columns(driver, "default", "events");
|
||||
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
|
||||
@@ -1130,6 +1214,7 @@ mod tests {
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
@@ -1206,8 +1291,10 @@ mod tests {
|
||||
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
|
||||
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
|
||||
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
|
||||
let relations = tables(DbDriver::Oracle, "hr");
|
||||
assert!(relations.contains("all_tab_comments"));
|
||||
assert!(relations.contains("table_type = 'VIEW'"));
|
||||
assert!(relations.contains("comments"));
|
||||
let cols = columns(DbDriver::Oracle, "hr", "employees");
|
||||
assert!(cols.contains("all_tab_columns"));
|
||||
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
|
||||
@@ -1296,12 +1383,13 @@ mod tests {
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
@@ -1310,12 +1398,53 @@ mod tests {
|
||||
"t",
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlExtras::default(),
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
let extras = DdlExtras {
|
||||
comment: Some("Orders".into()),
|
||||
owner: Some("app owner".into()),
|
||||
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
|
||||
triggers: vec![
|
||||
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl(
|
||||
"public",
|
||||
"t",
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
\ncomment on table \"public\".\"t\" is 'Orders';\n\
|
||||
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
|
||||
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
|
||||
\ngrant select on \"public\".\"t\" to public;\n\
|
||||
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
|
||||
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
|
||||
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snowflake_quotes_names_and_reads_its_information_schema() {
|
||||
let driver = DbDriver::Snowflake;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Data source files edited outside the Database tool window (by hand, by a coding
|
||||
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! Data source and data source folder files edited outside the Database tool window
|
||||
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
|
||||
//! reports a modification inside a gitignored `.openidea/`.
|
||||
|
||||
use crate::source::FILE;
|
||||
use crate::source::{FILE, FOLDERS_FILE};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
@@ -15,8 +15,8 @@ use std::time::Duration;
|
||||
/// the files are read.
|
||||
const SETTLE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
|
||||
/// stops when dropped.
|
||||
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
|
||||
/// `<global>/data-sources.toml`; stops when dropped.
|
||||
pub struct SourcesWatch {
|
||||
_watcher: Arc<Mutex<RecommendedWatcher>>,
|
||||
}
|
||||
@@ -29,7 +29,7 @@ impl SourcesWatch {
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let relevant = {
|
||||
let config = config.clone();
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
|
||||
};
|
||||
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(e) = res
|
||||
@@ -131,6 +131,10 @@ mod tests {
|
||||
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project folders file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(global.join("data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "global file");
|
||||
|
||||
@@ -57,6 +57,7 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
|
||||
@@ -353,6 +353,9 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let listed = db.tables("p", "oi_meta").await?;
|
||||
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
|
||||
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
@@ -420,7 +423,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
|
||||
let objects = db.schema_objects("p", "oi_keys").await?;
|
||||
assert_eq!(objects.sequences.len(), 1);
|
||||
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
|
||||
let plain = db.ddl("p", "oi_keys", "refs").await?;
|
||||
assert!(plain.contains("FOREIGN KEY"), "{plain}");
|
||||
assert!(plain.contains("\n owner to "), "{plain}");
|
||||
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
|
||||
// Comments, privileges and triggers come back too, so the script rebuilds the table.
|
||||
for statement in [
|
||||
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
|
||||
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
|
||||
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
|
||||
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
|
||||
] {
|
||||
db.execute("p", statement, 10, &c).await?;
|
||||
}
|
||||
let full = db.ddl("p", "oi_keys", "refs").await?;
|
||||
for part in [
|
||||
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
|
||||
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
|
||||
"grant insert, select on \"oi_keys\".\"refs\" to public;",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
|
||||
] {
|
||||
assert!(full.contains(part), "{part}\n{full}");
|
||||
}
|
||||
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
|
||||
/// Stop / restart wait for the container's grace period (10 s by default).
|
||||
const LIFECYCLE: Duration = Duration::from_secs(90);
|
||||
|
||||
/// Locates the docker executable once per process. GUI apps on macOS start with a
|
||||
/// minimal `PATH`, so the usual install locations are probed after the lookup.
|
||||
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
|
||||
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
|
||||
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
|
||||
pub fn docker_executable() -> Option<PathBuf> {
|
||||
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DOCKER
|
||||
.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("docker") {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
|
||||
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
|
||||
return Some(cached.clone());
|
||||
}
|
||||
let found = which::which("docker")
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
let path = ide_core::process::host_var_os("PATH")?;
|
||||
which::which_in("docker", Some(path), ".").ok()
|
||||
})
|
||||
.or_else(|| {
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
|
||||
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
|
||||
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
|
||||
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
candidates.push(home.join(".docker/bin/docker"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
if let Some(ref path) = found {
|
||||
let _ = DOCKER.set(path.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Environment for docker command lines a run configuration launches: the endpoint's
|
||||
|
||||
@@ -82,6 +82,11 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.project_env
|
||||
}
|
||||
|
||||
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
|
||||
/// the background, unless another window of it already did. Its language servers wait.
|
||||
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
|
||||
|
||||
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -295,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -897,6 +904,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -223,9 +223,15 @@ impl KotlinBridge {
|
||||
let staging = directory.clone();
|
||||
let root = self.root.clone();
|
||||
let token = cancel.clone();
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
|
||||
.await;
|
||||
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
|
||||
// the status bar and can be stopped there (the next saved change builds again).
|
||||
let task = BuildTask::start(self.sink.clone(), &cancel);
|
||||
let progress = task.reporter();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
|
||||
})
|
||||
.await;
|
||||
drop(task);
|
||||
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
|
||||
remove_directory(directory).await;
|
||||
continue;
|
||||
@@ -306,6 +312,58 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar's background task for one bridge build; ends when dropped.
|
||||
struct BuildTask {
|
||||
id: TaskId,
|
||||
sink: SharedSink,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl BuildTask {
|
||||
const TITLE: &str = "Compiling Kotlin for Java";
|
||||
|
||||
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
|
||||
let id = TaskId::next();
|
||||
let cancel = cancel.clone();
|
||||
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
|
||||
let task = Self { id, sink, _cancel: handle };
|
||||
task.emit(None, None, false);
|
||||
task
|
||||
}
|
||||
|
||||
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: self.id,
|
||||
title: Self::TITLE.into(),
|
||||
message,
|
||||
fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
});
|
||||
}
|
||||
|
||||
/// Forwards Maven's progress to the task.
|
||||
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
|
||||
let (id, sink) = (self.id, self.sink.clone());
|
||||
move |message: &str, fraction| {
|
||||
sink.emit(IdeEvent::Task {
|
||||
id,
|
||||
title: Self::TITLE.into(),
|
||||
message: Some(message.to_owned()),
|
||||
fraction,
|
||||
done: false,
|
||||
cancellable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BuildTask {
|
||||
fn drop(&mut self) {
|
||||
self.emit(None, None, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
|
||||
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
|
||||
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
|
||||
@@ -369,6 +427,41 @@ impl DocumentObserver for KotlinBridge {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_build_shows_as_a_cancellable_background_task() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = Arc::new({
|
||||
let events = events.clone();
|
||||
move |e: IdeEvent| events.lock().push(e)
|
||||
});
|
||||
let cancel = CancellationToken::new();
|
||||
let task = BuildTask::start(sink, &cancel);
|
||||
let progress = task.reporter();
|
||||
progress("Building app 1.0 [2/3]", Some(0.5));
|
||||
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
|
||||
assert!(cancel.is_cancelled());
|
||||
drop(task);
|
||||
let seen: Vec<_> = events
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
|
||||
assert_eq!(title, "Compiling Kotlin for Java");
|
||||
(message.clone(), *fraction, *done, *cancellable)
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(None, None, false, true),
|
||||
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
|
||||
(None, None, true, false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_package_directory_does_not_trigger() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -125,6 +125,7 @@ pub struct Host {
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -255,6 +256,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
|
||||
@@ -38,6 +38,11 @@ impl Requests {
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
}
|
||||
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
|
||||
pub(super) fn window_ready(&self, window: &str) -> bool {
|
||||
self.0.lock().ready.contains(window)
|
||||
}
|
||||
|
||||
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -286,6 +287,79 @@ workingDirectory, envs).",
|
||||
/// not the user's own runs.
|
||||
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
|
||||
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
|
||||
|
||||
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
|
||||
struct ConfigLaunch {
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
started: Option<Result<ide_run::RunInfo, String>>,
|
||||
}
|
||||
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
|
||||
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
|
||||
/// the call's output file, and the call learns the run it started.
|
||||
pub(crate) struct ConfigRunLaunch {
|
||||
token: u64,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
}
|
||||
|
||||
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
|
||||
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
|
||||
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
|
||||
let launches = LAUNCHES.lock();
|
||||
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
|
||||
Some(ConfigRunLaunch { token, output: launch.output.clone() })
|
||||
}
|
||||
|
||||
impl ConfigRunLaunch {
|
||||
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
|
||||
let output = self.output.clone();
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
|
||||
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
|
||||
output.lock().append(text);
|
||||
}
|
||||
on_output(chunk);
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
|
||||
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
|
||||
launch.started = Some(result.clone().map_err(|e| e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
|
||||
/// Stop. Its before launch tasks already ran.
|
||||
async fn start_in_run_window(
|
||||
call: &Call,
|
||||
mut config: RunConfig,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
) -> IdeResult<ide_run::RunInfo> {
|
||||
struct Forget(u64);
|
||||
impl Drop for Forget {
|
||||
fn drop(&mut self) {
|
||||
LAUNCHES.lock().remove(&self.0);
|
||||
}
|
||||
}
|
||||
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
|
||||
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
|
||||
let _forget = Forget(token);
|
||||
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
|
||||
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
|
||||
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
|
||||
match (asked, started) {
|
||||
(_, Some(Ok(info))) => Ok(info),
|
||||
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
|
||||
(Err(e), None) => Err(e),
|
||||
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn started_by_mcp(id: RunId) -> bool {
|
||||
STARTED.lock().contains(&id)
|
||||
}
|
||||
@@ -753,9 +827,9 @@ Behavior:
|
||||
|
||||
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
|
||||
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
|
||||
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
|
||||
and deleted after a day.",
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
|
||||
window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \
|
||||
which `stop_run` stops; output files are private and deleted after a day.",
|
||||
|call| async move {
|
||||
let target = execution_target(
|
||||
call.opt_str("configurationName")?,
|
||||
@@ -811,9 +885,15 @@ one by one",
|
||||
};
|
||||
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
|
||||
let output_path = collector.lock().path.clone();
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
|
||||
let started = if call.has_window() {
|
||||
start_in_run_window(&call, config, collector.clone()).await
|
||||
} else {
|
||||
// A project loaded for MCP alone has no Run tool window to show it in.
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
|
||||
};
|
||||
let info = match started {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&output_path);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
pub(crate) mod agent;
|
||||
mod agent_tools;
|
||||
mod build;
|
||||
mod configs;
|
||||
pub(crate) mod configs;
|
||||
mod output;
|
||||
mod process;
|
||||
mod targets;
|
||||
|
||||
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
|
||||
if JS_FILE.is_match(rel) {
|
||||
&["npm", "deno", "bun"]
|
||||
} else if rel.ends_with(".py") {
|
||||
&["pytest", "python"]
|
||||
&["pytest", "unittest", "python"]
|
||||
} else if rel.ends_with(".go") {
|
||||
&["go"]
|
||||
} else if rel.ends_with(".rs") {
|
||||
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
|
||||
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
|
||||
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
|
||||
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
|
||||
// `python -m unittest <file>`; a `discover` selection gives way to the file.
|
||||
"unittest" => {
|
||||
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
|
||||
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
|
||||
}
|
||||
"go" => {
|
||||
let dir = dir_of(&file);
|
||||
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
|
||||
@@ -790,6 +795,11 @@ pub fn target_config(
|
||||
"pytest" | "python" => {
|
||||
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
|
||||
}
|
||||
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
|
||||
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
|
||||
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
|
||||
format!("{module}.{}", target.path.join("."))
|
||||
}))),
|
||||
"go" => {
|
||||
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
|
||||
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
|
||||
@@ -921,6 +931,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_unittest_configs_to_files_and_dotted_tests() {
|
||||
let root = Path::new("/p");
|
||||
let mut unittest =
|
||||
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
|
||||
unittest.is_test = true;
|
||||
let mut discover = unittest.clone();
|
||||
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
|
||||
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
|
||||
let rel = "tests/test_calc.py";
|
||||
for configs in [vec![unittest], vec![discover]] {
|
||||
let c = context_config(root, rel, &configs, src).unwrap();
|
||||
assert_eq!(
|
||||
(c.kind.as_str(), c.args.as_slice()),
|
||||
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
|
||||
);
|
||||
let ts = detect(src, rel);
|
||||
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
|
||||
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_cargo_test_configs() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -70,6 +70,10 @@ impl Call {
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
}
|
||||
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
|
||||
pub fn has_window(&self) -> bool {
|
||||
self.host.mcp_requests.window_ready(&self.window)
|
||||
}
|
||||
/// Asks the user before a tool changes the project or starts a process, unless brave mode
|
||||
/// is on — read from the IDE's own settings only, which a project's settings can't set.
|
||||
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
|
||||
|
||||
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
));
|
||||
|
||||
let mut tools = vec![
|
||||
act("code.saveAsLiveTemplate", "Save as Live Template…"),
|
||||
SEP,
|
||||
act("http.newRequest", "New HTTP Request"),
|
||||
act("http.showToolWindow", "HTTP Client"),
|
||||
SEP,
|
||||
|
||||
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_preview_copilot_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
account: String,
|
||||
model: Option<String>,
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
agents.preview_copilot_models(&account, model.as_deref()).await
|
||||
}
|
||||
|
||||
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -122,6 +135,39 @@ pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<C
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
|
||||
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
|
||||
|
||||
fn prepare_login_launch_env(
|
||||
is_remote: bool,
|
||||
target_is_gh: bool,
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
|
||||
env.insert("REMOTE_CONTAINERS".into(), "1".into());
|
||||
}
|
||||
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
|
||||
env.insert("GH_BROWSER".into(), "true".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
|
||||
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
|
||||
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -167,7 +213,7 @@ pub async fn agent_login_spawn(
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, launch) = match host.project(window) {
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
@@ -186,6 +232,7 @@ pub async fn agent_login_spawn(
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -204,7 +251,8 @@ pub async fn agent_gh_login_spawn(
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
apply_remote_login_env(host, &cwd, true, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -1549,6 +1597,29 @@ mod tests {
|
||||
assert!(reloaded.approved(&root, "extra", &extra));
|
||||
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
@@ -1584,6 +1655,7 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::blocking;
|
||||
use ide_core::{IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
|
||||
/// with paths mapped into this project.
|
||||
#[command(trust = always)]
|
||||
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
|
||||
// Also reads a SimpleCov resultset.
|
||||
let root = host.project(window)?.root.clone();
|
||||
blocking(move || ide_coverage::import(&path, &root)).await
|
||||
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, config_dir) =
|
||||
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
|
||||
let trusted = project.require_trust();
|
||||
blocking(move || {
|
||||
if !ide_coverage::is_data_file(&path) {
|
||||
return ide_coverage::import(&path, &root);
|
||||
}
|
||||
// coverage.py analyses the sources with the project's interpreter: that runs project code.
|
||||
trusted.map_err(|_| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
|
||||
ide_coverage::import_data(&path, &root, &python, &out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
|
||||
@@ -8,8 +8,8 @@ use ide_command::command;
|
||||
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, TableGrant, TableInfo, TablePage,
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
|
||||
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
ide_db::source::load_folders(&host.project(window)?.root)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
|
||||
// Replaces the project's data source folders; only grouping changes, never a source.
|
||||
let root = host.project(window)?.root.clone();
|
||||
ide_db::source::save_folders(&root, &folders)?;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_save_source_visibility(
|
||||
host: &Host,
|
||||
@@ -612,7 +626,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
|
||||
#[command(trust = always)]
|
||||
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
|
||||
let dir = host.data_dir.join("consoles").join("db");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
|
||||
/// `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
let (source, database) = ide_db::split_target(id);
|
||||
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
@@ -670,6 +693,7 @@ ide_command::domain!(
|
||||
db_connect,
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
@@ -692,6 +716,7 @@ ide_command::domain!(
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_folders,
|
||||
db_save_source_visibility,
|
||||
db_save_sources,
|
||||
db_saved_catalog,
|
||||
@@ -701,6 +726,7 @@ ide_command::domain!(
|
||||
db_set_manual_commit,
|
||||
db_set_password,
|
||||
db_set_ssh_secret,
|
||||
db_source_folders,
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
|
||||
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
|
||||
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
|
||||
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
|
||||
//! tunnelled through the host's own SSH client.
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_docker::{
|
||||
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
|
||||
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
|
||||
};
|
||||
use ide_ssh::Tunnel;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
|
||||
host.ssh.release(id);
|
||||
}
|
||||
|
||||
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
|
||||
async fn cancellable<T: Send + 'static>(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host.blocking(move || f(&cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
|
||||
/// (Services › Disconnect); other endpoints keep nothing open.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
|
||||
disconnect(host, &endpoint).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_op(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
ids: Vec<String>,
|
||||
op: ContainerOp,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_remove(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
ids: Vec<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
|
||||
}
|
||||
|
||||
/// Pretty-printed `docker inspect` JSON.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_inspect(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
id: String,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
|
||||
}
|
||||
|
||||
/// Layers of an image (`docker image history`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_image_history(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<Vec<DockerImageLayer>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Processes running inside a container (`docker top`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_stats(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<DockerContainerStats> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Disk usage per volume name (`docker system df -v`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
|
||||
}
|
||||
|
||||
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_logs(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
on_lines: Channel<Vec<DockerLogLine>>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
|
||||
let _ = on_lines.send(lines);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Follows `docker events` until the daemon goes away or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_events(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
on_event: Channel<DockerEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::watch_events(&endpoint, cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker pull`, logging in first when a saved registry with a password serves the image.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_pull(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
reference: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
cancellable(host, request, move |cancel| {
|
||||
let auth = ide_docker::auth_for(&data_dir, &reference);
|
||||
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_prune(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
target: PruneTarget,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::prune(&endpoint, target, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker compose` start / stop / restart / down of a project found through labels.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_compose_op(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
project: String,
|
||||
files: Vec<String>,
|
||||
working_dir: Option<String>,
|
||||
op: ComposeOp,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Docker connections and registries of the project host.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
|
||||
}
|
||||
|
||||
/// Saves (`None`: forgets) a registry's password.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
|
||||
}
|
||||
|
||||
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_registry_login(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
registry: DockerRegistry,
|
||||
password: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || {
|
||||
let password = password
|
||||
.or_else(|| ide_docker::registry_password(&data_dir, ®istry.id))
|
||||
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
|
||||
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
|
||||
ide_docker::login(&endpoint, &auth)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
|
||||
/// daemon and puts the docker executable on `PATH`.
|
||||
#[command(trust = always)]
|
||||
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
|
||||
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(docker: docker_run_env);
|
||||
ide_command::domain!(
|
||||
docker:
|
||||
docker_compose_op,
|
||||
docker_container_op,
|
||||
docker_container_stats,
|
||||
docker_container_top,
|
||||
docker_disconnect,
|
||||
docker_events,
|
||||
docker_image_history,
|
||||
docker_inspect,
|
||||
docker_logs,
|
||||
docker_prune,
|
||||
docker_pull,
|
||||
docker_registry_login,
|
||||
docker_remove,
|
||||
docker_run_env,
|
||||
docker_save_settings,
|
||||
docker_set_registry_password,
|
||||
docker_settings,
|
||||
docker_snapshot,
|
||||
docker_volume_sizes,
|
||||
);
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
|
||||
//! Resources status bar widget and popover dashboard.
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use ide_workspace::system::SystemSampler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostMetricsSampler {
|
||||
system: SystemSampler,
|
||||
cpu: CpuSampler,
|
||||
}
|
||||
|
||||
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostProcess {
|
||||
pub pid: u32,
|
||||
pub name: String,
|
||||
pub cpu_percent: Option<f32>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostMetrics {
|
||||
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
|
||||
pub cpu_percent: Option<f32>,
|
||||
/// Logical CPU cores available to this host or container.
|
||||
pub cpu_cores: u32,
|
||||
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
|
||||
pub load_average: Option<[f32; 3]>,
|
||||
/// Host or container memory in use, in bytes.
|
||||
pub memory_used_bytes: Option<u64>,
|
||||
/// Total physical (or container limit) memory, in bytes.
|
||||
pub memory_total_bytes: Option<u64>,
|
||||
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_rx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_tx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_read_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_write_bytes_per_sec: Option<f64>,
|
||||
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
|
||||
pub disk_available_bytes: Option<u64>,
|
||||
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
|
||||
pub disk_total_bytes: Option<u64>,
|
||||
/// Uptime of the backend process in milliseconds.
|
||||
pub uptime_ms: f64,
|
||||
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
|
||||
pub processes: Vec<ProcessMemory>,
|
||||
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
|
||||
pub external_processes: Vec<HostProcess>,
|
||||
}
|
||||
|
||||
const MAX_EXTERNAL_PROCESSES: usize = 5;
|
||||
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
|
||||
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
|
||||
|
||||
fn project_name(root: &Path) -> String {
|
||||
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
|
||||
}
|
||||
|
||||
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
|
||||
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
|
||||
}
|
||||
|
||||
fn volume_path(host: &Host, window: &str) -> PathBuf {
|
||||
if let Ok(p) = host.project(window) {
|
||||
return p.root.clone();
|
||||
}
|
||||
if let Some(p) = host.projects().into_iter().next() {
|
||||
return p.root.clone();
|
||||
}
|
||||
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
|
||||
}
|
||||
|
||||
fn disk_space(path: &Path) -> Option<(u64, u64)> {
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
{
|
||||
let stat = rustix::fs::statvfs(path).ok()?;
|
||||
let frsize = stat.f_frsize as u64;
|
||||
let total = (stat.f_blocks as u64).saturating_mul(frsize);
|
||||
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
|
||||
(total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
|
||||
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
|
||||
wide.as_ptr(),
|
||||
&mut avail,
|
||||
&mut total,
|
||||
&mut free,
|
||||
)
|
||||
};
|
||||
(ok != 0 && total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
|
||||
let mut roots = Vec::new();
|
||||
for p in host.projects() {
|
||||
for s in p.lsp.servers() {
|
||||
if let Some(pid) = s.pid {
|
||||
roots.push(MemoryRoot {
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
detail: Some(project_name(s.root.as_ref())),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in host.processes.list().into_iter().filter(|r| r.running) {
|
||||
if let Some(pid) = r.pid {
|
||||
roots.push(process_root(pid, r.name, "Run"));
|
||||
}
|
||||
}
|
||||
for t in host.terminals.list() {
|
||||
if let Some(pid) = t.pid {
|
||||
roots.push(process_root(pid, t.title, "Terminal"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
|
||||
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
|
||||
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
|
||||
(Some(b), Some(t)) => b as f64 / t as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
cpu_share.max(mem_share)
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
|
||||
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
|
||||
#[command(trust = always)]
|
||||
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
|
||||
let disk_target = volume_path(host, window);
|
||||
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
let table = include_processes.then(ProcessTable::snapshot);
|
||||
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
|
||||
Some((a, t)) => (Some(a), Some(t)),
|
||||
None => (None, None),
|
||||
};
|
||||
let uptime_ms =
|
||||
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
|
||||
|
||||
let mut sampler = h.metrics_sampler.lock();
|
||||
let rates = sampler.system.sample();
|
||||
|
||||
let (processes, external_processes) = if let Some(table) = table {
|
||||
sampler.cpu.retain(&table);
|
||||
let me = std::process::id();
|
||||
let processes =
|
||||
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
|
||||
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
|
||||
let mut external: Vec<HostProcess> = table
|
||||
.entries()
|
||||
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
|
||||
.filter_map(|e| {
|
||||
let cpu_percent = sampler.cpu.percent(e.pid);
|
||||
let memory_bytes = memory::fast_resident_bytes(e.pid);
|
||||
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|
||||
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
|
||||
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
|
||||
})
|
||||
.collect();
|
||||
external.sort_by(|a, b| {
|
||||
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
|
||||
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
|
||||
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
|
||||
.then_with(|| a.pid.cmp(&b.pid))
|
||||
});
|
||||
external.truncate(MAX_EXTERNAL_PROCESSES);
|
||||
(processes, external)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
Ok(HostMetrics {
|
||||
cpu_percent: rates.cpu_percent,
|
||||
cpu_cores: rates.cpu_cores,
|
||||
load_average: rates.load_average,
|
||||
memory_used_bytes: rates.memory_used_bytes,
|
||||
memory_total_bytes: rates.memory_total_bytes,
|
||||
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
|
||||
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
|
||||
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
|
||||
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
|
||||
disk_available_bytes,
|
||||
disk_total_bytes,
|
||||
uptime_ms,
|
||||
processes,
|
||||
external_processes,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
|
||||
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
|
||||
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(host_metrics: host_metrics, host_end_process);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_light_and_detailed_host_metrics() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
|
||||
|
||||
let light = host_metrics(&host, "main", false).await.unwrap();
|
||||
assert!(light.cpu_cores >= 1);
|
||||
assert!(light.processes.is_empty());
|
||||
assert!(light.external_processes.is_empty());
|
||||
if cfg!(any(unix, windows)) {
|
||||
let avail = light.disk_available_bytes.expect("disk_available_bytes");
|
||||
let total = light.disk_total_bytes.expect("disk_total_bytes");
|
||||
assert!(total > 0 && avail <= total, "{avail} / {total}");
|
||||
}
|
||||
|
||||
let detailed = host_metrics(&host, "main", true).await.unwrap();
|
||||
assert!(!detailed.processes.is_empty());
|
||||
assert_eq!(detailed.processes[0].label, "Backend");
|
||||
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
|
||||
|
||||
// Refuses to terminate the backend itself or PID 1.
|
||||
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
|
||||
assert!(!host_end_process(&host, 1).await.unwrap());
|
||||
}
|
||||
}
|
||||
@@ -1881,6 +1881,29 @@ pub async fn lsp_snapshot_diagnostics(
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_snapshot_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: std::path::PathBuf,
|
||||
text: String,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<CompletionItem>> {
|
||||
let project = host.project(window)?;
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
@@ -3236,6 +3259,7 @@ ide_command::domain!(
|
||||
lsp_extract_interface_info,
|
||||
lsp_format,
|
||||
lsp_format_text,
|
||||
lsp_snapshot_completion,
|
||||
lsp_snapshot_diagnostics,
|
||||
lsp_source_action_text,
|
||||
lsp_goto,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
@@ -27,6 +28,7 @@ pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
@@ -93,6 +95,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::blocking;
|
||||
use super::pytest_fixtures::{PytestFixtureAt, fixture_at};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
@@ -478,6 +479,23 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
|
||||
.await
|
||||
}
|
||||
|
||||
/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
|
||||
/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
|
||||
/// fixtures visible where a fixture name goes, for completion.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<PytestFixtureAt> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
nav:
|
||||
find_dirs,
|
||||
@@ -491,6 +509,7 @@ ide_command::domain!(
|
||||
mark_recent,
|
||||
nav_index_definitions,
|
||||
nav_inheritance,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_stubs,
|
||||
nav_resolve_module,
|
||||
path_completions,
|
||||
|
||||
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
|
||||
/// crate's and the desktop's) call it after writing the value.
|
||||
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
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);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
|
||||
/// re-reads its effective settings.
|
||||
@@ -122,17 +138,7 @@ pub fn settings_set(
|
||||
value: String,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = set_settings(host, window, scope, &key, &value)?;
|
||||
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);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
apply_setting(host, window, &key);
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its
|
||||
//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed
|
||||
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
|
||||
//! and completion of fixture names.
|
||||
|
||||
use super::python_stubs::site_packages;
|
||||
use crate::Project;
|
||||
use ide_core::{IpcPath, LanguageId, Location, Pos, Range};
|
||||
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureAt {
|
||||
/// The fixture name at the position, and the definition pytest uses for it.
|
||||
pub reference: Option<PytestFixtureReference>,
|
||||
/// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the
|
||||
/// fixtures visible there, nearest first.
|
||||
pub completions: Option<Vec<PytestFixtureItem>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureReference {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
/// None when no visible module defines it (`request`, a fixture from a hook).
|
||||
pub definition: Option<Location>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureItem {
|
||||
pub name: String,
|
||||
/// The file defining it.
|
||||
pub path: IpcPath,
|
||||
}
|
||||
|
||||
/// Fixtures at `pos` of the Python document `path` / `text`.
|
||||
pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt {
|
||||
let own = syntax.pytest_module(&python(), text);
|
||||
let usage = own.use_at(pos).cloned();
|
||||
let slot = own.slot_at(pos).cloned();
|
||||
if usage.is_none() && slot.is_none() {
|
||||
return PytestFixtureAt::default();
|
||||
}
|
||||
let layers = layers(project, syntax, path, Arc::new(own));
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let reference = usage.map(|u| {
|
||||
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
|
||||
PytestFixtureReference {
|
||||
definition: found.map(|(l, f)| Location {
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
range: modules[l].fixtures[f].selection,
|
||||
uri: None,
|
||||
}),
|
||||
name: u.name,
|
||||
range: u.range,
|
||||
}
|
||||
});
|
||||
let completions = slot.map(|s| {
|
||||
visible_fixtures(&modules, s.class.as_deref())
|
||||
.into_iter()
|
||||
// `_name` fixtures are internal, as `pytest --fixtures` hides them.
|
||||
.filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_'))
|
||||
.map(|(l, f)| PytestFixtureItem {
|
||||
name: modules[l].fixtures[f].name.clone(),
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
PytestFixtureAt { reference, completions }
|
||||
}
|
||||
|
||||
fn python() -> LanguageId {
|
||||
LanguageId::new("python")
|
||||
}
|
||||
|
||||
type Layer = (PathBuf, Arc<PytestModule>);
|
||||
|
||||
/// The modules `path` sees, nearest first, `own` being its own.
|
||||
fn layers(project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
|
||||
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
|
||||
// conftest.py files from the file's folder up to the project root.
|
||||
let mut dir = path.parent();
|
||||
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
|
||||
let conftest = d.join("conftest.py");
|
||||
if conftest != path
|
||||
&& let Some(m) = module_of(project, syntax, &conftest)
|
||||
{
|
||||
out.push((conftest, m));
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
let packages = interpreter_site_packages(project);
|
||||
let mut search = super::python::paths(project);
|
||||
search.extend(packages.iter().cloned());
|
||||
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
|
||||
search.extend(packages.iter().map(|p| p.join("_pytest")));
|
||||
// Modules named by `pytest_plugins` in those files.
|
||||
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
|
||||
let mut extra: Vec<PathBuf> = named.iter().filter_map(|module| module_file(module, &search)).collect();
|
||||
// Installed plugins, then pytest's own fixtures.
|
||||
for packages in &packages {
|
||||
extra.extend(
|
||||
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
|
||||
);
|
||||
}
|
||||
for packages in &packages {
|
||||
extra.extend(builtin_modules(&packages.join("_pytest")));
|
||||
}
|
||||
for file in extra {
|
||||
if !out.iter().any(|(p, _)| *p == file)
|
||||
&& let Some(m) = module_of(project, syntax, &file)
|
||||
{
|
||||
out.push((file, m));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
|
||||
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
|
||||
let settings = project.settings.effective();
|
||||
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
|
||||
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
|
||||
prefix.map(|p| site_packages(&p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
|
||||
fn module_file(module: &str, search: &[PathBuf]) -> Option<PathBuf> {
|
||||
let rel: PathBuf = module.split('.').collect();
|
||||
search.iter().find_map(|base| {
|
||||
let file = base.join(&rel).with_extension("py");
|
||||
let package = base.join(&rel).join("__init__.py");
|
||||
[file, package].into_iter().find(|p| p.is_file())
|
||||
})
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`.
|
||||
fn entry_point_modules(site_packages: &Path) -> Vec<String> {
|
||||
let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".dist-info") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue };
|
||||
out.extend(pytest11_modules(&text));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`).
|
||||
fn pytest11_modules(text: &str) -> Vec<String> {
|
||||
let mut section = "";
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
section = name;
|
||||
} else if section == "pytest11"
|
||||
&& let Some((_, value)) = line.split_once('=')
|
||||
{
|
||||
let module = value.trim().split(':').next().unwrap_or_default().trim();
|
||||
if !module.is_empty() {
|
||||
out.push(module.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// pytest's own plugins that are off unless `pytest_plugins` names them.
|
||||
const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"];
|
||||
|
||||
/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages.
|
||||
fn builtin_modules(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
if path.extension().is_some_and(|e| e == "py") {
|
||||
out.push(path);
|
||||
} else if path.is_dir() {
|
||||
out.extend(
|
||||
std::fs::read_dir(&path)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "py")),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// A parsed file and the modification time and length it was read at.
|
||||
type Cached = (SystemTime, u64, Arc<PytestModule>);
|
||||
|
||||
/// The fixtures of a file: from its open editor, else from disk, parsed once per modification.
|
||||
fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<PytestModule>> {
|
||||
if let Some(text) = project.documents.text_of(path) {
|
||||
return Some(Arc::new(syntax.pytest_module(&python(), &text)));
|
||||
}
|
||||
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
|
||||
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
|
||||
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
let stamp = (meta.modified().ok()?, meta.len());
|
||||
if let Some((time, len, m)) = CACHE.lock().ok()?.get(path)
|
||||
&& (*time, *len) == stamp
|
||||
{
|
||||
return Some(m.clone());
|
||||
}
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text)));
|
||||
CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone()));
|
||||
Some(module)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_pytest11_entry_points() {
|
||||
let text =
|
||||
"[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n";
|
||||
assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_module_files_and_packages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap();
|
||||
std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap();
|
||||
std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap();
|
||||
let search = [dir.path().to_path_buf()];
|
||||
assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py")));
|
||||
assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py")));
|
||||
assert_eq!(module_file("pkg.none", &search), None);
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,9 @@ use ide_command::command;
|
||||
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_language::Syntax;
|
||||
use ide_lsp::types::FileRenameEdits;
|
||||
use ide_workspace::file_moves::moved_path;
|
||||
use ide_workspace::roots::{ProjectRoots, RootKind};
|
||||
use ide_workspace::Documents;
|
||||
use ide_workspace::file_moves::{moved_path, read_text};
|
||||
use ide_workspace::roots::{PYTHON_FILES, ProjectRoots, RootKind, SourceFolder};
|
||||
use ide_workspace::{FileMove, UndoOutcome};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +19,8 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
|
||||
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
|
||||
}
|
||||
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move). Cancellable.
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
|
||||
/// Python import updates the IDE makes itself. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn refactor_file_move_edits(
|
||||
host: &Host,
|
||||
@@ -28,46 +30,72 @@ pub async fn refactor_file_move_edits(
|
||||
) -> IdeResult<FileRenameEdits> {
|
||||
let project = host.project(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
let result = async {
|
||||
let mut result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await?;
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(
|
||||
&project.root,
|
||||
&project.roots(),
|
||||
&project.exclude_globs(),
|
||||
&project.documents,
|
||||
&syntax,
|
||||
&moves,
|
||||
&|| token.is_cancelled(),
|
||||
);
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
fn is_python(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "py" || e == "pyi")
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder, from its project's Python roots
|
||||
/// (`src/a/b.py` → `a.b` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
|
||||
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
|
||||
let base = roots
|
||||
.root_for(&rel)
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map_or("", |r| r.path.as_str());
|
||||
/// The folders Python imports modules from: source and test roots of Python projects (or marked
|
||||
/// by the user), else the project root. Other languages' roots (`frontend/src`) don't count.
|
||||
fn python_root<'a>(roots: &'a ProjectRoots, rel: &str) -> &'a str {
|
||||
let python = |r: &&SourceFolder| {
|
||||
matches!(r.kind, RootKind::Source | RootKind::Test)
|
||||
&& r.detected_from.as_deref().is_none_or(|f| PYTHON_FILES.iter().any(|p| f.rsplit('/').next() == Some(*p)))
|
||||
};
|
||||
let inside = |r: &&SourceFolder| r.path.is_empty() || rel == r.path || rel.starts_with(&format!("{}/", r.path));
|
||||
roots.roots.iter().filter(python).filter(inside).max_by_key(|r| r.path.len()).map_or("", |r| r.path.as_str())
|
||||
}
|
||||
|
||||
fn rel_path(root: &Path, path: &Path) -> Option<String> {
|
||||
Some(path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder and the root it is imported from
|
||||
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
|
||||
let rel = rel_path(root, path)?;
|
||||
let base = python_root(roots, &rel);
|
||||
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
|
||||
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
|
||||
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
|
||||
let valid = |s: &str| {
|
||||
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
|
||||
};
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| (inner.replace('/', "."), base.to_owned()))
|
||||
}
|
||||
|
||||
/// The package relative imports in `file` start from.
|
||||
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
|
||||
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
|
||||
if file.file_stem().is_some_and(|s| s == "__init__") {
|
||||
module
|
||||
} else {
|
||||
@@ -75,52 +103,91 @@ fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` holds Python modules (a package or namespace package), at any depth.
|
||||
fn has_python(dir: &Path) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "__pycache__") && has_python(&path)
|
||||
} else {
|
||||
is_python(&path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Import updates in the project's Python files for `moves` (paths before the move).
|
||||
fn python_import_edits(
|
||||
project: &crate::project::Project,
|
||||
root: &Path,
|
||||
roots: &ProjectRoots,
|
||||
excludes: &[String],
|
||||
documents: &Documents,
|
||||
syntax: &Syntax,
|
||||
moves: &[FileMove],
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> WorkspaceEdit {
|
||||
let root = &project.root;
|
||||
let roots = project.roots();
|
||||
let renames: Vec<(String, String)> = moves
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let is_dir = m.from.is_dir();
|
||||
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
|
||||
return None;
|
||||
}
|
||||
let old = python_module(root, &roots, &m.from, is_dir)?;
|
||||
let new = python_module(root, &roots, &m.to, is_dir)?;
|
||||
(old != new).then_some((old, new))
|
||||
})
|
||||
.collect();
|
||||
// (old, new, root the old module is imported from)
|
||||
let mut renames: Vec<(String, String, String)> = Vec::new();
|
||||
for m in moves {
|
||||
let is_dir = m.from.is_dir();
|
||||
let module = if is_dir {
|
||||
has_python(&m.from)
|
||||
} else {
|
||||
let stub_only = m.from.extension().is_some_and(|e| e == "pyi")
|
||||
&& !moves.iter().any(|o| *o.from == m.from.with_extension("py"));
|
||||
// A stub may describe a compiled module that stays where it is.
|
||||
is_python(&m.from) && !stub_only && m.from.file_stem().is_some_and(|s| s != "__init__")
|
||||
};
|
||||
if !module {
|
||||
continue;
|
||||
}
|
||||
let (Some((old, base)), Some((new, _))) =
|
||||
(python_module(root, roots, &m.from, is_dir), python_module(root, roots, &m.to, is_dir))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if old != new && !renames.iter().any(|r| r.0 == old) {
|
||||
renames.push((old, new, base));
|
||||
}
|
||||
}
|
||||
if renames.is_empty() {
|
||||
return WorkspaceEdit::default();
|
||||
}
|
||||
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
// `import utils` in `backend/app.py` means `backend/utils.py`, not `backend/tests/utils.py`.
|
||||
let shadowed = |base: &str, module: &str| {
|
||||
let p = root.join(base).join(module.replace('.', "/"));
|
||||
p.with_extension("py").is_file() || p.with_extension("pyi").is_file() || p.is_dir()
|
||||
};
|
||||
let names: Vec<&str> = renames.iter().map(|(old, ..)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
|
||||
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if cancelled() || !is_python(path) {
|
||||
return;
|
||||
}
|
||||
let moved = moved_path(path, moves);
|
||||
let text = match project.documents.text_of(path) {
|
||||
Some(t) => t,
|
||||
None => match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
if moved == path && !names.iter().any(|n| text.contains(n)) {
|
||||
return;
|
||||
if moved == path {
|
||||
let Ok(bytes) = std::fs::read(path) else { return };
|
||||
let raw = String::from_utf8_lossy(&bytes);
|
||||
if !names.iter().any(|n| raw.contains(n)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Through the documents layer: unsaved edits, BOM and encodings as the edits will see them.
|
||||
let Ok(text) = read_text(documents, path) else { return };
|
||||
let Some(rel) = rel_path(root, path) else { return };
|
||||
let base = python_root(roots, &rel);
|
||||
let visible: Vec<(String, String)> = renames
|
||||
.iter()
|
||||
.filter(|(old, _, from)| from == base || !shadowed(base, old))
|
||||
.map(|(old, new, _)| (old.clone(), new.clone()))
|
||||
.collect();
|
||||
let edits = syntax.python_import_edits(
|
||||
&text,
|
||||
&python_package(root, &roots, path),
|
||||
&python_package(root, &roots, &moved),
|
||||
&renames,
|
||||
&python_package(root, roots, path),
|
||||
&python_package(root, roots, &moved),
|
||||
&visible,
|
||||
);
|
||||
if !edits.is_empty() {
|
||||
found.lock().push((path.to_path_buf(), edits));
|
||||
@@ -213,7 +280,6 @@ ide_command::domain!(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_workspace::roots::SourceFolder;
|
||||
|
||||
#[test]
|
||||
fn python_module_names_follow_the_roots() {
|
||||
@@ -223,7 +289,7 @@ mod tests {
|
||||
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
|
||||
&Default::default(),
|
||||
);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir).map(|(m, _)| m);
|
||||
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
|
||||
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
|
||||
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
|
||||
@@ -234,4 +300,54 @@ mod tests {
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_imports_in_a_mixed_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let write = |p: &str, text: &str| {
|
||||
let path = root.join(p);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("backend/pyproject.toml", "[project]\nname = \"b\"\n");
|
||||
write("backend/utils.py", "");
|
||||
write("backend/app.py", "import utils\nfrom api import routes\n");
|
||||
write("backend/api/__init__.py", "");
|
||||
write("backend/api/routes.py", "");
|
||||
write("backend/bom.py", "\u{feff}from api import routes\n");
|
||||
write("backend/tests/utils.py", "");
|
||||
write("backend/tests/test_a.py", "import utils\n");
|
||||
write("backend/native/_ext.pyi", "");
|
||||
write("backend/uses_ext.py", "from native import _ext\n");
|
||||
write("frontend/package.json", "{}");
|
||||
write("frontend/src/api/index.js", "");
|
||||
let roots = ProjectRoots::compute(ide_workspace::roots::detect(root), &Default::default());
|
||||
let documents = Documents::new(
|
||||
std::sync::Arc::new(|_| {}),
|
||||
Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("python")),
|
||||
);
|
||||
let edits = |from: &str, to: &str| {
|
||||
let moves = vec![FileMove { from: root.join(from).into(), to: root.join(to).into() }];
|
||||
let edit = python_import_edits(root, &roots, &[], &documents, &Syntax::new(), &moves, &|| false);
|
||||
edit.files
|
||||
.into_iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path, edits, .. } => Some((rel_path(root, &path).unwrap(), edits)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Not Python: a JavaScript folder of the same name.
|
||||
assert!(edits("frontend/src/api", "frontend/src/client").is_empty());
|
||||
// Same-named modules of different roots.
|
||||
let files = edits("backend/tests/utils.py", "backend/tests/helpers.py");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/tests/test_a.py"]);
|
||||
// A BOM doesn't shift the edit.
|
||||
let files = edits("backend/api", "backend/web");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/app.py", "backend/bom.py"]);
|
||||
assert_eq!(files[1].1[0].range.start, ide_core::Pos { line: 0, col: 5 });
|
||||
// A stub without its module.
|
||||
assert!(edits("backend/native/_ext.pyi", "backend/native/_ext2.pyi").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -334,10 +334,19 @@ pub async fn run_start(
|
||||
Some(agent) => agent.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
// `execute_run_configuration` asked the Run tool window to start it.
|
||||
let mcp = crate::mcp::run::configs::config_run_launch(&config);
|
||||
let on_output = match &mcp {
|
||||
Some(mcp) => mcp.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
|
||||
if let Some(agent) = &agent {
|
||||
agent.started(&result);
|
||||
}
|
||||
if let Some(mcp) = &mcp {
|
||||
mcp.started(&result);
|
||||
}
|
||||
if let Some(id) = request {
|
||||
host.end_request(id);
|
||||
}
|
||||
@@ -493,7 +502,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
|
||||
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
|
||||
// Search's UTF-8 fast path does not need to resolve the configured encoding.
|
||||
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Languages checked as prose (all text but code spans).
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
|
||||
|
||||
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
|
||||
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
@@ -211,6 +211,10 @@ impl Host {
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
|
||||
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
// Attached dependency projects are source, so basedpyright/Pyright should
|
||||
@@ -360,8 +364,13 @@ impl Host {
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let data_dir = self.local_data_dir.clone();
|
||||
lsp.set_servers_hook(Box::new(move |language, defined| {
|
||||
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
|
||||
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
|
||||
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
|
||||
ide_sdk::apply::drop_css_modules_route(&mut servers);
|
||||
}
|
||||
servers
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -452,7 +461,9 @@ impl Host {
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
// Not while loading: a first `use flake` may write `flake.lock` itself.
|
||||
@@ -1040,9 +1051,8 @@ fn db_sources_watch(
|
||||
let Some(db) = weak.upgrade() else { return };
|
||||
let sink = sink.clone();
|
||||
runtime.spawn(async move {
|
||||
if db.reconcile_sources().await {
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
}
|
||||
db.reconcile_sources().await;
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
});
|
||||
}))
|
||||
.inspect_err(|e| tracing::warn!("{}", e.message))
|
||||
@@ -1530,8 +1540,7 @@ impl Project {
|
||||
}
|
||||
|
||||
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
|
||||
let defaults = self.documents.file_defaults();
|
||||
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
|
||||
let charset = self.documents.detect_encoding(path, bytes);
|
||||
self.vcs_text_encoding(path, charset)
|
||||
}
|
||||
|
||||
@@ -1890,7 +1899,9 @@ fn content_root_watcher(
|
||||
index.ignore_rules_changed(&batch.ignore_rules);
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
// A workspace member's PHP language level follows its own composer.json.
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
if let Some(bridge) = &kotlin_bridge {
|
||||
@@ -1912,6 +1923,17 @@ fn content_root_watcher(
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
|
||||
/// plugins it declares are part of vtsls' configuration.
|
||||
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
paths.any(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
!p.components().any(|c| c.as_os_str() == "node_modules")
|
||||
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
|
||||
&& name.ends_with(".json")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
|
||||
/// (`ide_sdk::php`).
|
||||
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
@@ -2737,9 +2759,20 @@ mod agent_worktree_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod composer_tests {
|
||||
use super::composer_changed;
|
||||
use super::{composer_changed, ts_config_changed};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[test]
|
||||
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
|
||||
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
|
||||
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
|
||||
assert!(changed(yes), "{yes}");
|
||||
}
|
||||
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
|
||||
assert!(!changed(no), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_roots_own_composer_json_counts() {
|
||||
let root = Path::new("/work/app");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
@@ -96,10 +91,30 @@ fn section(
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
|
||||
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
|
||||
let mut preferences = Map::new();
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
preferences.insert("quoteStyle".into(), json!(quotes));
|
||||
preferences.insert("quotePreference".into(), json!(quotes));
|
||||
}
|
||||
let paths = ["shortest", "relative", "non-relative", "project-relative"];
|
||||
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
|
||||
preferences.insert("importModuleSpecifier".into(), json!(paths));
|
||||
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
|
||||
}
|
||||
let endings = ["auto", "minimal", "index", "js"];
|
||||
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
|
||||
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
|
||||
}
|
||||
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
|
||||
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
|
||||
let none = Vec::new();
|
||||
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
|
||||
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
|
||||
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
|
||||
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
|
||||
section.insert("preferences".into(), Value::Object(preferences));
|
||||
section
|
||||
}
|
||||
|
||||
@@ -133,9 +148,17 @@ mod tests {
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
"preferences": {
|
||||
"quoteStyle": "double",
|
||||
"quotePreference": "single",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
},
|
||||
},
|
||||
"javascript": {
|
||||
"format": { "semicolons": "insert" },
|
||||
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
@@ -144,7 +167,52 @@ mod tests {
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
|
||||
// a running server.
|
||||
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
|
||||
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
|
||||
assert_eq!(untouched.settings, Some(empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_style_reaches_the_preferences_of_each_language() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
import_module_specifier: Some("relative".into()),
|
||||
import_module_specifier_ending: Some("index".into()),
|
||||
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
|
||||
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle {
|
||||
import_module_specifier: Some("non-relative".into()),
|
||||
// Not a tsserver value: left out.
|
||||
import_module_specifier_ending: Some("ts".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": { "preferences": {
|
||||
"importModuleSpecifier": "relative",
|
||||
"importModuleSpecifierPreference": "relative",
|
||||
"importModuleSpecifierEnding": "index",
|
||||
"autoImportFileExcludePatterns": ["**/index.ts"],
|
||||
"autoImportSpecifierExcludeRegexes": ["^node:"],
|
||||
} },
|
||||
"javascript": { "preferences": {
|
||||
"importModuleSpecifier": "non-relative",
|
||||
"importModuleSpecifierPreference": "non-relative",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
} },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,6 +246,6 @@ mod tests {
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
assert_eq!(s["javascript"].get("format"), None);
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = base.join("data/consoles/db/pg");
|
||||
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
|
||||
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
|
||||
};
|
||||
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
|
||||
// The first new console is the default one, then console_1, console_2…
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
|
||||
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(first.clone()), ["console.sql"]);
|
||||
assert_eq!(first[0].0, root.join("console.sql"));
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
|
||||
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
|
||||
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
|
||||
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = db::db_consoles_dir(&host).unwrap();
|
||||
assert_eq!(root.0, base.join("data/consoles/db"));
|
||||
assert!(root.0.is_dir());
|
||||
}
|
||||
@@ -542,6 +542,23 @@ impl Smoke {
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
|
||||
/// none labelled `label`.
|
||||
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
|
||||
let (doc, pos, before) = self.type_line(typed).await;
|
||||
self.retry("completion without the item", self.warm_up, || async {
|
||||
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
|
||||
let labels: Vec<String> = match list {
|
||||
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
|
||||
Err(e) => vec![e.to_string()],
|
||||
};
|
||||
let has = |name: &str| labels.iter().any(|l| l == name);
|
||||
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
|
||||
})
|
||||
.await;
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
async fn organize_imports(&self, import: Typed, expect: Imports) {
|
||||
let (doc, _, before) = self.type_line(import).await;
|
||||
let typed = import.text.trim();
|
||||
@@ -696,6 +713,71 @@ async fn typescript() {
|
||||
smoke("typescript", TYPESCRIPT).await;
|
||||
}
|
||||
|
||||
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
|
||||
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
|
||||
/// specifiers left out.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "language smoke: needs vtsls"]
|
||||
async fn typescript_import_style() {
|
||||
let checks = Checks {
|
||||
files: &[
|
||||
(
|
||||
"tsconfig.json",
|
||||
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
|
||||
"include": ["src"]}"#,
|
||||
),
|
||||
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
|
||||
// Never excluded, and matching what is typed (tsserver offers only those): the
|
||||
// auto-import candidates are in the completion list.
|
||||
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
|
||||
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
|
||||
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
|
||||
("src/app/main.ts", "export const ready = true;\n"),
|
||||
("src/app/other.ts", "export const other = true;\n"),
|
||||
("src/app/third.ts", "export const third = true;\n"),
|
||||
("src/app/fourth.ts", "export const fourth = true;\n"),
|
||||
("src/app/fifth.ts", "export const fifth = true;\n"),
|
||||
],
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
let key = format!("editor.codeStyle.languages.typescript.{key}");
|
||||
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
|
||||
};
|
||||
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
|
||||
let beta = typed("src/app/main.ts", "export const ready", "betaW");
|
||||
let import = |typed, label, result| AutoImport { typed, label, result };
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
|
||||
// tsserver keeps the auto-import candidates of the file it last completed in until the
|
||||
// program changes; other files see an exclusion at once.
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
|
||||
|
||||
// Emptied lists reach the server too: the symbols are offered again.
|
||||
set("autoImportFileExcludePatterns", "[]");
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
#[cfg(unix)]
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
|
||||
@@ -731,6 +731,38 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
|
||||
assert!(p.documents.is_dirty(doc.id).unwrap());
|
||||
}
|
||||
|
||||
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
|
||||
/// starts the configuration in a tab and says whether it started. Returns what it started.
|
||||
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
|
||||
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
|
||||
if !handled.contains(id) =>
|
||||
{
|
||||
Some((*id, config.clone()))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Some((id, config)) = request else {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
continue;
|
||||
};
|
||||
handled.insert(id);
|
||||
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
|
||||
out.lock().unwrap().push(config.clone());
|
||||
let result =
|
||||
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
|
||||
let error = result.err().map(|e| e.message);
|
||||
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
|
||||
}
|
||||
});
|
||||
started
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let h = Harness::new();
|
||||
@@ -765,6 +797,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert!(error.contains("denied by the user"));
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
h.events.lock().unwrap().clear();
|
||||
let tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
@@ -773,6 +806,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
assert_eq!(result["exitCode"], 7);
|
||||
assert!(result["output"].as_str().unwrap().contains("captured-output"));
|
||||
// It ran in a Run tool window tab, as the user's Run would.
|
||||
let tabs = tabs.lock().unwrap();
|
||||
assert_eq!(tabs.len(), 1);
|
||||
assert_eq!(tabs[0].name, "MCP test");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
.unwrap();
|
||||
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -795,6 +861,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let _tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
|
||||
@@ -429,9 +429,10 @@ fn gutter_actions_see_the_editors_window_project() {
|
||||
assert_eq!(actions.len(), 1);
|
||||
actions[0].1.argument.clone().unwrap()
|
||||
};
|
||||
// The outer project's window: the file is its, though the inner project holds it too.
|
||||
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
|
||||
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
|
||||
// The outer project's window: the file is its, though the inner project holds it too. Compared
|
||||
// as paths: the plugin sees Windows paths `/`-separated.
|
||||
assert_eq!(Path::new(&argument(Some(&outer))), outer);
|
||||
assert_eq!(Path::new(&argument(Some(&inner))), inner);
|
||||
// No window, or a root that is no open project: no invoking project.
|
||||
assert_eq!(argument(None), "gutter");
|
||||
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
|
||||
|
||||
@@ -52,7 +52,8 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
|
||||
let config = "plugin:test.run-anything:tasks";
|
||||
// Not provided until its program is approved.
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
|
||||
// Any approved executable will do; the test binary exists on every host.
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).unwrap();
|
||||
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
|
||||
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
|
||||
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
|
||||
|
||||
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
// Recorded before the reply: the client may assert as soon as it reads it.
|
||||
seen.lock().push("served".into());
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ mod common;
|
||||
|
||||
use ide_core::{Pos, RequestId};
|
||||
use ide_host::{Host, ops};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery, SearchScope};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
@@ -145,9 +145,10 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let scope = base.join("scope");
|
||||
let root = scope.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
@@ -157,14 +158,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
// Open and clean, but changed on disk before the watcher reported it.
|
||||
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
|
||||
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
|
||||
// Search the parent folder so Replace All also covers a clean buffer outside the project watch.
|
||||
let stale_path = scope.join("stale.txt");
|
||||
std::fs::write(&stale_path, "TOKEN\n").unwrap();
|
||||
let stale = project.documents.open(&stale_path).unwrap().id;
|
||||
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
|
||||
let mut search = query("TOKEN", false);
|
||||
search.scope = SearchScope::Directory { path: scope.into() };
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
search,
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
@@ -178,7 +183,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(std::fs::read_to_string(&stale_path).unwrap(), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(project.documents.text_snapshot(stale).unwrap().text, "DONE\n");
|
||||
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
@@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
invoke(&peer, "index_status", json!({})).await.unwrap();
|
||||
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
|
||||
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
|
||||
assert_eq!(metrics["processes"][0]["label"], "Backend");
|
||||
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
|
||||
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
|
||||
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
|
||||
assert!(files.is_array());
|
||||
for command in
|
||||
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
|
||||
{
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
for (command, args) in [
|
||||
("build_sync", json!({})),
|
||||
("run_start", json!({})),
|
||||
("sdk_locate_tools", json!({})),
|
||||
("notebook_execute", json!({})),
|
||||
("debug_start", json!({})),
|
||||
("agent_refresh_models", json!({})),
|
||||
("host_end_process", json!({ "pid": 1 })),
|
||||
] {
|
||||
let error = invoke(&peer, command, args).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
@@ -271,6 +280,9 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
|
||||
// Services › Docker commands are served by the project host too.
|
||||
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
|
||||
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
|
||||
|
||||
// Real project-host ignore writes travel through the remote command dispatcher.
|
||||
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
|
||||
@@ -391,6 +403,8 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"http_curl",
|
||||
"http_environment_file",
|
||||
"http_variable_definitions",
|
||||
"db_source_folders",
|
||||
"db_save_source_folders",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
@@ -420,6 +434,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_table_page",
|
||||
"db_apply_edits",
|
||||
"db_console_path",
|
||||
"db_consoles_dir",
|
||||
"db_consoles",
|
||||
"ssh_test",
|
||||
"ssh_set_secret",
|
||||
|
||||
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(find(&host, "中文搜索验证").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
|
||||
let files = find(&host, "ação €").await;
|
||||
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
|
||||
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
|
||||
}
|
||||
@@ -29,7 +29,9 @@ pub use syntax::{
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{
|
||||
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
|
||||
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
|
||||
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
|
||||
visible_fixtures,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
|
||||
@@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
|
||||
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
|
||||
}
|
||||
|
||||
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
|
||||
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
|
||||
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
|
||||
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
|
||||
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
|
||||
fn has_json_key(file: &Path, key: &str) -> bool {
|
||||
let Ok(text) = std::fs::read_to_string(file) else { return false };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
|
||||
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
|
||||
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
|
||||
}
|
||||
|
||||
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
|
||||
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
|
||||
/// it winning, as CSS Modules Kit reads `cmkOptions`.
|
||||
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
|
||||
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
|
||||
const MAX_DEPTH: usize = 8;
|
||||
let text = std::fs::read_to_string(file).ok()?;
|
||||
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
|
||||
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let name = file.file_name()?.to_string_lossy();
|
||||
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
|
||||
return None;
|
||||
}
|
||||
let extends = match value.get("extends")? {
|
||||
serde_json::Value::String(s) => vec![s.as_str()],
|
||||
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
|
||||
let base = file.parent()?.join(e);
|
||||
let base = if base.is_file() {
|
||||
base
|
||||
} else {
|
||||
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
|
||||
};
|
||||
json_key(&base, key, depth + 1)
|
||||
})
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
@@ -191,6 +221,28 @@ mod tests {
|
||||
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
|
||||
assert!(!has_marker(dir, "package.json#eslintConfig"));
|
||||
assert!(is_marker_path(&dir.join("package.json"), marker));
|
||||
// tsconfig.json is JSON with comments; a switch that is off is no marker.
|
||||
let cmk = "tsconfig.json#cmkOptions.enabled";
|
||||
let tsconfig =
|
||||
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
assert!(has_marker(dir, cmk));
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
|
||||
assert!(!has_marker(dir, cmk));
|
||||
// Inherited through a local `extends`, which the file itself can turn off.
|
||||
std::fs::create_dir_all(dir.join("app")).unwrap();
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
|
||||
.unwrap();
|
||||
assert!(has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(
|
||||
dir.join("app/tsconfig.json"),
|
||||
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("lua", include_str!("../../../languages/lua.toml")),
|
||||
("makefile", include_str!("../../../languages/makefile.toml")),
|
||||
("markdown", include_str!("../../../languages/markdown.toml")),
|
||||
("mdx", include_str!("../../../languages/mdx.toml")),
|
||||
("nix", include_str!("../../../languages/nix.toml")),
|
||||
("objective-c", include_str!("../../../languages/objective-c.toml")),
|
||||
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
|
||||
@@ -1073,6 +1074,8 @@ mod tests {
|
||||
assert_eq!(detect("shop/templates/shop/product_list.html"), "django-html");
|
||||
assert_eq!(detect("shop/templates/shop/email/order.txt"), "django-html");
|
||||
assert_eq!(detect("pages/promo.html"), "html");
|
||||
// No `[debugger]` of its own: `find_config` would take it for debugpy instead of Python's.
|
||||
assert!(reg.get(&LanguageId::new("django-html")).unwrap().debugger.is_none());
|
||||
}
|
||||
|
||||
/// #4061: the project root is canonical; a template reached under another
|
||||
@@ -1281,6 +1284,7 @@ mod tests {
|
||||
("Views/MainWindow.axaml", "axaml"),
|
||||
("MainWindow.xaml", "xml"),
|
||||
("README.md", "markdown"),
|
||||
("Intro.mdx", "mdx"),
|
||||
("Dockerfile", "dockerfile"),
|
||||
("Dockerfile.dev", "dockerfile"),
|
||||
("Makefile", "makefile"),
|
||||
@@ -1362,6 +1366,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indented_sass_has_its_own_server() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
assert_eq!(names("sass"), ["some-sass-language-server"]);
|
||||
let sass = ®.get(&LanguageId::new("sass")).unwrap().language_servers[0];
|
||||
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
|
||||
for lang in ["scss", "css", "less"] {
|
||||
let names = names(lang);
|
||||
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
|
||||
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -13,6 +13,7 @@ mod literals;
|
||||
mod outline;
|
||||
mod php_align;
|
||||
mod python_facts;
|
||||
mod python_fixtures;
|
||||
mod python_imports;
|
||||
mod rearrange;
|
||||
mod rst;
|
||||
@@ -35,6 +36,10 @@ pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
|
||||
pub use python_fixtures::{
|
||||
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture,
|
||||
visible_fixtures,
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
//! pytest fixtures in one Python module: the fixtures it defines (`@pytest.fixture`), the
|
||||
//! places it names one (a test's or fixture's parameters, `usefixtures("x")`,
|
||||
//! `getfixturevalue("x")`) and the plugin modules it loads (`pytest_plugins`). From the
|
||||
//! syntax tree only; [`resolve_fixture`] then picks the definition pytest uses, given the
|
||||
//! modules a test sees, nearest first.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use crate::{LanguageId, Syntax};
|
||||
use ide_core::{Pos, Range};
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PytestModule {
|
||||
pub fixtures: Vec<PytestFixture>,
|
||||
pub uses: Vec<PytestFixtureUse>,
|
||||
/// Where a fixture name may be typed: completion offers the visible fixtures there.
|
||||
pub slots: Vec<PytestFixtureSlot>,
|
||||
/// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`).
|
||||
pub plugins: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixture {
|
||||
/// The name tests ask for: the `name=` argument, else the function's name.
|
||||
pub name: String,
|
||||
/// That name in the source: the function name, or the `name=` string's content.
|
||||
pub selection: Range,
|
||||
/// The class whose method it is; only that class's tests see it.
|
||||
pub class: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PytestFixtureUseKind {
|
||||
Parameter,
|
||||
UseFixtures,
|
||||
GetFixtureValue,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixtureUse {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
pub kind: PytestFixtureUseKind,
|
||||
pub class: Option<String>,
|
||||
/// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward.
|
||||
pub in_fixture: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixtureSlot {
|
||||
/// A test's or fixture's parameter list, or the content of a `usefixtures` /
|
||||
/// `getfixturevalue` string (empty strings included).
|
||||
pub range: Range,
|
||||
pub class: Option<String>,
|
||||
}
|
||||
|
||||
impl PytestModule {
|
||||
/// The use whose name covers `pos` (its end included, where a caret after the name sits).
|
||||
pub fn use_at(&self, pos: Pos) -> Option<&PytestFixtureUse> {
|
||||
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
|
||||
}
|
||||
|
||||
/// The slot holding `pos`.
|
||||
pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> {
|
||||
self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end)
|
||||
}
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// The pytest fixtures a Python `text` defines and names; empty for other languages.
|
||||
pub fn pytest_module(&self, lang: &LanguageId, text: &str) -> PytestModule {
|
||||
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixture pytest uses for a name asked in `layers[0]` (the module), `class` being the
|
||||
/// asking test's class, the later layers being the `conftest.py` files from the module's
|
||||
/// folder upward, then plugins and pytest's own modules. `overriding`: the asker is a fixture
|
||||
/// of that same name, which gets the next definition outward. Returns (layer, fixture) indexes.
|
||||
pub fn resolve_fixture(
|
||||
layers: &[&PytestModule],
|
||||
name: &str,
|
||||
class: Option<&str>,
|
||||
overriding: bool,
|
||||
) -> Option<(usize, usize)> {
|
||||
visible(layers, class).filter(|&(l, f)| layers[l].fixtures[f].name == name).nth(usize::from(overriding))
|
||||
}
|
||||
|
||||
/// The fixtures a test of `class` in `layers[0]` sees, nearest first, one per name.
|
||||
pub fn visible_fixtures(layers: &[&PytestModule], class: Option<&str>) -> Vec<(usize, usize)> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
visible(layers, class).filter(|&(l, f)| seen.insert(layers[l].fixtures[f].name.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Every fixture visible from `class` in `layers[0]`, nearest first: the class's own, then
|
||||
/// the module's, then each later layer's module-level ones. Within one scope the last
|
||||
/// definition of a name wins, as Python rebinds it.
|
||||
fn visible<'a>(layers: &'a [&'a PytestModule], class: Option<&'a str>) -> impl Iterator<Item = (usize, usize)> + 'a {
|
||||
let scopes = layers.iter().enumerate().flat_map(move |(l, m)| {
|
||||
let own = (l == 0).then_some(class).flatten().map(|c| (l, m, Some(c)));
|
||||
own.into_iter().chain(std::iter::once((l, m, None)))
|
||||
});
|
||||
scopes.flat_map(|(l, m, scope)| {
|
||||
let mut picked: Vec<(usize, usize)> = Vec::new();
|
||||
for (f, fixture) in m.fixtures.iter().enumerate().rev() {
|
||||
if fixture.class.as_deref() == scope && !picked.iter().any(|&(_, p)| m.fixtures[p].name == fixture.name) {
|
||||
picked.push((l, f));
|
||||
}
|
||||
}
|
||||
picked.reverse();
|
||||
picked
|
||||
})
|
||||
}
|
||||
|
||||
fn extract(tree: &Tree, text: &str) -> PytestModule {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut out = PytestModule::default();
|
||||
let root = tree.root_node();
|
||||
let mut cursor = root.walk();
|
||||
for node in root.named_children(&mut cursor) {
|
||||
statement(node, None, text, &idx, &mut out);
|
||||
}
|
||||
// `usefixtures` / `getfixturevalue` calls wherever they are.
|
||||
let mut walker = root.walk();
|
||||
visit(&mut walker, &mut |node| {
|
||||
if node.kind() == "call" {
|
||||
fixture_call(node, text, &idx, &mut out);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A top-level statement, or one in a class body (`class` set).
|
||||
fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out: &mut PytestModule) {
|
||||
let (definition, decorators) = match node.kind() {
|
||||
"decorated_definition" => {
|
||||
let mut c = node.walk();
|
||||
let decorators: Vec<Node> = node.children(&mut c).filter(|n| n.kind() == "decorator").collect();
|
||||
let Some(definition) = node.child_by_field_name("definition") else { return };
|
||||
(definition, decorators)
|
||||
}
|
||||
_ => (node, Vec::new()),
|
||||
};
|
||||
match definition.kind() {
|
||||
"function_definition" => function(definition, &decorators, class, &[], text, idx, out),
|
||||
"class_definition" if class.is_none() => {
|
||||
let Some(name) = definition.child_by_field_name("name") else { return };
|
||||
let name = text_of(name, text);
|
||||
let Some(body) = definition.child_by_field_name("body") else { return };
|
||||
// `@pytest.mark.parametrize` on the class names arguments of every test in it.
|
||||
let class_args = parametrized(&decorators, text, idx);
|
||||
let mut c = body.walk();
|
||||
for child in body.named_children(&mut c) {
|
||||
let (def, decs) = match child.kind() {
|
||||
"decorated_definition" => {
|
||||
let mut c2 = child.walk();
|
||||
let decs: Vec<Node> = child.children(&mut c2).filter(|n| n.kind() == "decorator").collect();
|
||||
match child.child_by_field_name("definition") {
|
||||
Some(d) => (d, decs),
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
_ => (child, Vec::new()),
|
||||
};
|
||||
if def.kind() == "function_definition" {
|
||||
function(def, &decs, Some(&name), &class_args, text, idx, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
"expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn function(
|
||||
def: Node,
|
||||
decorators: &[Node],
|
||||
class: Option<&str>,
|
||||
class_args: &[String],
|
||||
text: &str,
|
||||
idx: &LineIndex,
|
||||
out: &mut PytestModule,
|
||||
) {
|
||||
let Some(name_node) = def.child_by_field_name("name") else { return };
|
||||
let name = text_of(name_node, text);
|
||||
let fixture = decorators.iter().find_map(|d| fixture_decorator(*d, text, idx));
|
||||
let is_test = name.starts_with("test") && class.is_none_or(|c| c.starts_with("Test"));
|
||||
if fixture.is_none() && !is_test {
|
||||
return;
|
||||
}
|
||||
let fixture_name = fixture.as_ref().and_then(|f| f.as_ref().map(|(n, _)| n.clone())).unwrap_or(name.clone());
|
||||
if let Some(f) = &fixture {
|
||||
let selection = match f {
|
||||
Some((_, string)) => *string,
|
||||
None => idx.range(name_node.start_byte(), name_node.end_byte()),
|
||||
};
|
||||
out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) });
|
||||
}
|
||||
let Some(params) = def.child_by_field_name("parameters") else { return };
|
||||
out.slots.push(PytestFixtureSlot {
|
||||
range: idx.range(params.start_byte(), params.end_byte()),
|
||||
class: class.map(str::to_owned),
|
||||
});
|
||||
// Arguments `parametrize` supplies are no fixtures (unless indirect).
|
||||
let mut skip: Vec<String> = parametrized(decorators, text, idx);
|
||||
skip.extend_from_slice(class_args);
|
||||
let mut c = params.walk();
|
||||
for (i, param) in params.named_children(&mut c).enumerate() {
|
||||
let ident = match param.kind() {
|
||||
"identifier" => param,
|
||||
"typed_parameter" => match param.named_child(0) {
|
||||
Some(n) if n.kind() == "identifier" => n,
|
||||
_ => continue,
|
||||
},
|
||||
// Defaulted parameters, `*args`, `**kwargs`: no fixtures.
|
||||
_ => continue,
|
||||
};
|
||||
let param_name = text_of(ident, text);
|
||||
if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(¶m_name) {
|
||||
continue;
|
||||
}
|
||||
out.uses.push(PytestFixtureUse {
|
||||
name: param_name,
|
||||
range: idx.range(ident.start_byte(), ident.end_byte()),
|
||||
kind: PytestFixtureUseKind::Parameter,
|
||||
class: class.map(str::to_owned),
|
||||
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
|
||||
/// `name="…"` argument, `None` for any other decorator.
|
||||
fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option<Option<(String, Range)>> {
|
||||
let expr = decorator.named_child(0)?;
|
||||
let (callee, args) = match expr.kind() {
|
||||
"call" => (expr.child_by_field_name("function")?, expr.child_by_field_name("arguments")),
|
||||
_ => (expr, None),
|
||||
};
|
||||
let callee = text_of(callee, text);
|
||||
if callee != "fixture" && !callee.ends_with(".fixture") {
|
||||
return None;
|
||||
}
|
||||
let named = args.and_then(|args| {
|
||||
let mut c = args.walk();
|
||||
args.named_children(&mut c).find_map(|a| {
|
||||
if a.kind() != "keyword_argument" || a.child_by_field_name("name").map(|n| text_of(n, text))? != "name" {
|
||||
return None;
|
||||
}
|
||||
string_content(a.child_by_field_name("value")?, text, idx)
|
||||
})
|
||||
});
|
||||
Some(named)
|
||||
}
|
||||
|
||||
/// The argument names of `@pytest.mark.parametrize("a, b", …)` decorators that are passed
|
||||
/// directly (no `indirect=`).
|
||||
fn parametrized(decorators: &[Node], text: &str, idx: &LineIndex) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for d in decorators {
|
||||
let Some(call) = d.named_child(0).filter(|n| n.kind() == "call") else { continue };
|
||||
let Some(callee) = call.child_by_field_name("function") else { continue };
|
||||
if !text_of(callee, text).ends_with("parametrize") {
|
||||
continue;
|
||||
}
|
||||
let Some(args) = call.child_by_field_name("arguments") else { continue };
|
||||
let mut c = args.walk();
|
||||
let all: Vec<Node> = args.named_children(&mut c).collect();
|
||||
let indirect = all.iter().any(|a| {
|
||||
a.kind() == "keyword_argument"
|
||||
&& a.child_by_field_name("name").is_some_and(|n| text_of(n, text) == "indirect")
|
||||
&& a.child_by_field_name("value").is_some_and(|v| text_of(v, text) != "False")
|
||||
});
|
||||
if indirect {
|
||||
continue;
|
||||
}
|
||||
let first = all.iter().find(|a| a.kind() != "keyword_argument");
|
||||
let names: Vec<String> = match first {
|
||||
Some(n) if n.kind() == "string" => string_content(*n, text, idx)
|
||||
.map(|(s, _)| s.split(',').map(|p| p.trim().to_owned()).collect())
|
||||
.unwrap_or_default(),
|
||||
Some(n) if matches!(n.kind(), "list" | "tuple") => {
|
||||
let mut c = n.walk();
|
||||
n.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
out.extend(names.into_iter().filter(|n| !n.is_empty()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `usefixtures("a", "b")` and `request.getfixturevalue("a")`.
|
||||
fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule) {
|
||||
let Some(callee) = call.child_by_field_name("function") else { return };
|
||||
let callee_text = text_of(callee, text);
|
||||
let kind = if callee_text == "usefixtures" || callee_text.ends_with(".usefixtures") {
|
||||
PytestFixtureUseKind::UseFixtures
|
||||
} else if callee.kind() == "attribute"
|
||||
&& callee.child_by_field_name("attribute").is_some_and(|a| text_of(a, text) == "getfixturevalue")
|
||||
{
|
||||
PytestFixtureUseKind::GetFixtureValue
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let Some(args) = call.child_by_field_name("arguments") else { return };
|
||||
let class = enclosing_class(call, text);
|
||||
let mut c = args.walk();
|
||||
for (i, arg) in args.named_children(&mut c).enumerate() {
|
||||
if kind == PytestFixtureUseKind::GetFixtureValue && i > 0 {
|
||||
break;
|
||||
}
|
||||
let Some((name, range)) = string_content(arg, text, idx) else { continue };
|
||||
out.slots.push(PytestFixtureSlot { range, class: class.clone() });
|
||||
if !name.is_empty() {
|
||||
out.uses.push(PytestFixtureUse { name, range, kind, class: class.clone(), in_fixture: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The top-level class a node is in, if any.
|
||||
fn enclosing_class(node: Node, text: &str) -> Option<String> {
|
||||
let mut at = node.parent();
|
||||
let mut class = None;
|
||||
while let Some(n) = at {
|
||||
if n.kind() == "class_definition" {
|
||||
class = n.child_by_field_name("name").map(|c| text_of(c, text));
|
||||
}
|
||||
at = n.parent();
|
||||
}
|
||||
class
|
||||
}
|
||||
|
||||
/// `pytest_plugins = "a"`, `= ["a", "b"]` or `= ("a",)`.
|
||||
fn plugins(statement: Node, text: &str, idx: &LineIndex, out: &mut Vec<String>) {
|
||||
let Some(assign) = statement.named_child(0).filter(|n| n.kind() == "assignment") else { return };
|
||||
if assign.child_by_field_name("left").map(|l| text_of(l, text)).as_deref() != Some("pytest_plugins") {
|
||||
return;
|
||||
}
|
||||
let Some(right) = assign.child_by_field_name("right") else { return };
|
||||
match right.kind() {
|
||||
"string" => out.extend(string_content(right, text, idx).map(|(s, _)| s)),
|
||||
"list" | "tuple" => {
|
||||
let mut c = right.walk();
|
||||
out.extend(right.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of a plain string literal and its range (between the quotes); none for
|
||||
/// f-strings, byte strings and concatenations.
|
||||
fn string_content(node: Node, text: &str, idx: &LineIndex) -> Option<(String, Range)> {
|
||||
if node.kind() != "string" {
|
||||
return None;
|
||||
}
|
||||
let mut c = node.walk();
|
||||
let parts: Vec<Node> = node.children(&mut c).collect();
|
||||
let start = parts.iter().find(|p| p.kind() == "string_start")?;
|
||||
let end = parts.iter().find(|p| p.kind() == "string_end")?;
|
||||
if text_of(*start, text).chars().any(|ch| matches!(ch, 'f' | 'F' | 'b' | 'B')) {
|
||||
return None;
|
||||
}
|
||||
if parts.iter().any(|p| p.kind() == "interpolation" || p.kind() == "escape_sequence") {
|
||||
return None;
|
||||
}
|
||||
let (from, to) = (start.end_byte(), end.start_byte());
|
||||
Some((text.get(from..to)?.to_owned(), idx.range(from, to)))
|
||||
}
|
||||
|
||||
fn text_of(node: Node, text: &str) -> String {
|
||||
text.get(node.byte_range()).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
|
||||
loop {
|
||||
f(cursor.node());
|
||||
if cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn module(src: &str) -> PytestModule {
|
||||
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
|
||||
S.get_or_init(Syntax::new).pytest_module(&LanguageId::new("python"), src)
|
||||
}
|
||||
|
||||
fn names(m: &PytestModule) -> Vec<String> {
|
||||
m.fixtures
|
||||
.iter()
|
||||
.map(|f| format!("{}{}", f.class.as_deref().map(|c| format!("{c}.")).unwrap_or_default(), f.name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn uses(m: &PytestModule) -> Vec<String> {
|
||||
m.uses.iter().map(|u| format!("{:?} {}", u.kind, u.name)).collect()
|
||||
}
|
||||
|
||||
const TEST_MODULE: &str = r#"import pytest
|
||||
from pytest import fixture
|
||||
|
||||
pytest_plugins = ["pkg.fixtures", "other"]
|
||||
pytestmark = pytest.mark.usefixtures("db")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tasks(tmp_path):
|
||||
return []
|
||||
|
||||
|
||||
@fixture(scope="module", name="client")
|
||||
def make_client(tasks, request):
|
||||
return request.getfixturevalue("server")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("title, expected", [("a", "a")])
|
||||
def test_add(tasks, title, expected, monkeypatch, flag=False, *args):
|
||||
pass
|
||||
|
||||
|
||||
def helper(tasks):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("client", "")
|
||||
class TestTasks:
|
||||
@pytest.fixture
|
||||
def tasks(self, tasks):
|
||||
return tasks
|
||||
|
||||
def test_one(self, tasks: list, capsys):
|
||||
pass
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn reads_definitions_uses_and_plugins() {
|
||||
let m = module(TEST_MODULE);
|
||||
assert_eq!(names(&m), ["tasks", "client", "TestTasks.tasks"]);
|
||||
assert_eq!(m.plugins, ["pkg.fixtures", "other"]);
|
||||
assert_eq!(
|
||||
uses(&m),
|
||||
[
|
||||
"Parameter tmp_path",
|
||||
"Parameter tasks",
|
||||
"Parameter request",
|
||||
"Parameter tasks",
|
||||
"Parameter monkeypatch",
|
||||
"Parameter tasks",
|
||||
"Parameter tasks",
|
||||
"Parameter capsys",
|
||||
"UseFixtures db",
|
||||
"GetFixtureValue server",
|
||||
"UseFixtures client",
|
||||
]
|
||||
);
|
||||
// `name=` is found by its string; the overriding class fixture knows it overrides.
|
||||
let client = &m.fixtures[1];
|
||||
assert_eq!((client.selection.start.line, client.selection.start.col), (12, 31));
|
||||
let own = m.uses.iter().find(|u| u.class.as_deref() == Some("TestTasks") && u.in_fixture.is_some()).unwrap();
|
||||
assert_eq!(own.in_fixture.as_deref(), Some("tasks"));
|
||||
// The empty `usefixtures` string is still a place to complete.
|
||||
assert!(m.slots.iter().any(|s| s.range.start == s.range.end));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_nearest_first_and_overrides_outward() {
|
||||
let m = module(TEST_MODULE);
|
||||
let conftest = module(
|
||||
"import pytest\n\n@pytest.fixture\ndef tasks():\n return [1]\n\n@pytest.fixture\ndef db():\n pass\n",
|
||||
);
|
||||
let builtins = module("from _pytest.fixtures import fixture\n\n@fixture\ndef tmp_path():\n pass\n");
|
||||
let layers = [&m, &conftest, &builtins];
|
||||
// In the class: its own `tasks`; at module level: the module's.
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), false), Some((0, 2)));
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", None, false), Some((0, 0)));
|
||||
// The class fixture's `tasks` parameter: the module's; the module's own: conftest's.
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), true), Some((0, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", None, true), Some((1, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "db", None, false), Some((1, 1)));
|
||||
assert_eq!(resolve_fixture(&layers, "tmp_path", None, false), Some((2, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "missing", None, false), None);
|
||||
// Completion: one entry per name, nearest first; another class's fixtures are hidden.
|
||||
let visible: Vec<&str> =
|
||||
visible_fixtures(&layers, None).iter().map(|&(l, f)| layers[l].fixtures[f].name.as_str()).collect();
|
||||
assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_definition_replaces_an_earlier_one() {
|
||||
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
|
||||
assert_eq!(resolve_fixture(&[&m], "a", None, false), Some((0, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_use_and_slot_at_a_position() {
|
||||
let m = module(TEST_MODULE);
|
||||
// `def test_add(tasks, …` is on line 18; the caret right after `tasks`.
|
||||
let at = m.use_at(Pos::new(18, 18)).unwrap();
|
||||
assert_eq!(at.name, "tasks");
|
||||
assert!(m.slot_at(Pos::new(18, 13)).is_some());
|
||||
assert!(m.use_at(Pos::new(22, 11)).is_none(), "a plain function's parameters are no fixtures");
|
||||
}
|
||||
}
|
||||
@@ -38,27 +38,85 @@ struct Rewrite<'a> {
|
||||
impl Rewrite<'_> {
|
||||
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
|
||||
let mut imports = Vec::new();
|
||||
let mut chains = Vec::new();
|
||||
let mut idents = Vec::new();
|
||||
collect(tree.root_node(), &mut |n| match n.kind() {
|
||||
"import_statement" | "import_from_statement" => imports.push(n),
|
||||
"attribute" if !inside_import(n) => chains.push(n),
|
||||
"identifier" if !inside_import(n) => idents.push(n),
|
||||
_ => {}
|
||||
});
|
||||
let mut renamed: Vec<(String, String)> = Vec::new();
|
||||
// Unaliased `import a.b` that change: (name node, old, new). They bind `a`, used as `a.b.x`.
|
||||
let mut dotted: Vec<(Node, String, String)> = Vec::new();
|
||||
let mut kept: Vec<String> = Vec::new();
|
||||
for node in imports {
|
||||
if node.kind() == "import_statement" {
|
||||
self.import(node, &mut renamed);
|
||||
self.import(node, &mut dotted, &mut kept);
|
||||
} else {
|
||||
self.import_from(node);
|
||||
}
|
||||
}
|
||||
// `import a.b` is used as `a.b.x`: those chains follow the import.
|
||||
for node in chains {
|
||||
let t = self.src(node);
|
||||
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
|
||||
self.edit(node, new.clone());
|
||||
if dotted.is_empty() {
|
||||
return self.finish();
|
||||
}
|
||||
let root_of = |s: &str| s.split('.').next().unwrap_or_default().to_owned();
|
||||
let mut needed: Vec<(usize, String)> = Vec::new();
|
||||
for id in idents {
|
||||
let name = self.src(id);
|
||||
if !dotted.iter().any(|(_, old, _)| root_of(old) == name) || is_attribute_field(id) {
|
||||
continue;
|
||||
}
|
||||
// `a`, `a.b`, `a.b.x`: one edit per expression, on the longest prefix that moved.
|
||||
let mut spine = vec![id];
|
||||
while let Some(p) = spine
|
||||
.last()
|
||||
.and_then(|n| n.parent())
|
||||
.filter(|p| p.kind() == "attribute" && p.child_by_field_name("object") == spine.last().copied())
|
||||
{
|
||||
spine.push(p);
|
||||
}
|
||||
let key = |n: Node| self.src(n).chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
// ponytail: a bare `pkg` (no attribute) is never rewritten, it may be a parameter or a
|
||||
// local of the same name.
|
||||
if let Some((node, new)) =
|
||||
spine.iter().skip(1).rev().find_map(|&n| Some((n, map_module(&key(n), self.moves)?)))
|
||||
{
|
||||
self.edit(node, new);
|
||||
continue;
|
||||
}
|
||||
// A use the rewritten imports no longer bind (`pkg.helper()` after `import pkg.models` moved).
|
||||
if spine.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let used = key(*spine.last().unwrap_or(&id));
|
||||
for (i, (_, old, new)) in dotted.iter().enumerate() {
|
||||
let common: Vec<&str> = old
|
||||
.split('.')
|
||||
.zip(used.split('.'))
|
||||
.take(old.split('.').count() - 1)
|
||||
.take_while(|(a, b)| a == b)
|
||||
.map(|(a, _)| a)
|
||||
.collect();
|
||||
if common.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let prefix = common.join(".");
|
||||
let covered = |m: &String| *m == prefix || m.starts_with(&format!("{prefix}."));
|
||||
let gone = map_module(&prefix, self.moves).is_some();
|
||||
if !gone && !covered(new) && !kept.iter().any(covered) && !needed.contains(&(i, prefix.clone())) {
|
||||
needed.push((i, prefix));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (node, _, new)) in dotted.iter().enumerate() {
|
||||
let extra: String = needed.iter().filter(|(j, _)| *j == i).map(|(_, p)| format!(", {p}")).collect();
|
||||
self.edits.push(TextEdit {
|
||||
range: self.idx.range(node.start_byte(), node.end_byte()),
|
||||
new_text: format!("{new}{extra}"),
|
||||
});
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<TextEdit> {
|
||||
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
|
||||
self.edits
|
||||
}
|
||||
@@ -72,7 +130,7 @@ impl Rewrite<'_> {
|
||||
}
|
||||
|
||||
/// `import a.b`, `import a.b as c`.
|
||||
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
|
||||
fn import<'t>(&mut self, node: Node<'t>, dotted: &mut Vec<(Node<'t>, String, String)>, kept: &mut Vec<String>) {
|
||||
let mut cursor = node.walk();
|
||||
for item in node.children_by_field_name("name", &mut cursor) {
|
||||
let (name, aliased) = match item.kind() {
|
||||
@@ -83,12 +141,16 @@ impl Rewrite<'_> {
|
||||
_ => (item, false),
|
||||
};
|
||||
let old = self.src(name).to_owned();
|
||||
let Some(new) = map_module(&old, self.moves) else { continue };
|
||||
let Some(new) = map_module(&old, self.moves) else {
|
||||
if !aliased {
|
||||
kept.push(old);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if aliased {
|
||||
self.edit(name, new);
|
||||
} else if old.contains('.') {
|
||||
renamed.push((old, new.clone()));
|
||||
self.edit(name, new);
|
||||
dotted.push((name, old, new));
|
||||
} else {
|
||||
// The bound name stays, so the rest of the file needs no change.
|
||||
self.edit(name, format!("{new} as {old}"));
|
||||
@@ -166,18 +228,20 @@ impl Rewrite<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (item, text) in &in_place {
|
||||
self.edit(*item, text.clone());
|
||||
}
|
||||
if moved.is_empty() {
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
for (item, text) in in_place {
|
||||
self.edit(item, text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
|
||||
// "some names of one `from` moved elsewhere" case.
|
||||
let indent = line_indent(self.text, node.start_byte());
|
||||
// Names imported from elsewhere now go to statements of their own, after this one (or
|
||||
// after `;` when the statement shares its line: `try: from a import b, c`).
|
||||
let line_start = self.text[..node.start_byte()].rfind('\n').map_or(0, |i| i + 1);
|
||||
let before = &self.text[line_start..node.start_byte()];
|
||||
let sep = if before.trim().is_empty() { format!("\n{before}") } else { "; ".to_owned() };
|
||||
let mut parents: Vec<&str> = Vec::new();
|
||||
for m in &moved {
|
||||
if !parents.contains(&m.1.as_str()) {
|
||||
@@ -194,28 +258,46 @@ impl Rewrite<'_> {
|
||||
format!("from {from} import {}", items.join(", "))
|
||||
});
|
||||
}
|
||||
let kept: Vec<String> = names
|
||||
.iter()
|
||||
.filter(|n| !moved.iter().any(|m| m.0 == **n))
|
||||
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
|
||||
.collect();
|
||||
let sep = format!("\n{indent}");
|
||||
if kept.is_empty() {
|
||||
let is_moved = |n: &Node| moved.iter().any(|m| m.0 == *n);
|
||||
let Some(last_kept) = names.iter().rposition(|n| !is_moved(n)) else {
|
||||
self.edit(node, added.join(&sep));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
let (first, last) = (names[0], names[names.len() - 1]);
|
||||
let range = self.idx.range(first.start_byte(), last.end_byte());
|
||||
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
|
||||
let mut trailing_done = false;
|
||||
for (i, item) in names.iter().enumerate().filter(|(_, n)| is_moved(n)) {
|
||||
let (start, end) = if let Some(line) = self.own_lines(*item) {
|
||||
line
|
||||
} else if i < last_kept {
|
||||
(item.start_byte(), names[i + 1].start_byte())
|
||||
} else if !trailing_done {
|
||||
trailing_done = true;
|
||||
(names[last_kept].end_byte(), names[names.len() - 1].end_byte())
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
self.edits.push(TextEdit { range: self.idx.range(start, end), new_text: String::new() });
|
||||
}
|
||||
let end = self.idx.pos(node.end_byte());
|
||||
self.edits.push(TextEdit {
|
||||
range: ide_core::Range { start: end, end },
|
||||
new_text: format!("{sep}{}", added.join(&sep)),
|
||||
});
|
||||
}
|
||||
|
||||
/// The whole lines of an import list item that has them to itself (` models, # noqa`).
|
||||
fn own_lines(&self, item: Node) -> Option<(usize, usize)> {
|
||||
let start = self.text[..item.start_byte()].rfind('\n').map_or(0, |i| i + 1);
|
||||
if !self.text[start..item.start_byte()].trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = self.text[item.end_byte()..].find('\n').map_or(self.text.len(), |i| item.end_byte() + i + 1);
|
||||
let rest = self.text[item.end_byte()..end].trim_start();
|
||||
let rest = rest.strip_prefix(',').unwrap_or(rest).trim();
|
||||
(rest.is_empty() || rest.starts_with('#')).then_some((start, end))
|
||||
}
|
||||
}
|
||||
|
||||
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
|
||||
@@ -236,9 +318,9 @@ fn inside_import(mut n: Node) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn line_indent(text: &str, byte: usize) -> &str {
|
||||
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
|
||||
&text[start..byte]
|
||||
/// `x` in `obj.x`.
|
||||
fn is_attribute_field(n: Node) -> bool {
|
||||
n.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(n))
|
||||
}
|
||||
|
||||
fn join(a: &str, b: &str) -> String {
|
||||
@@ -288,6 +370,11 @@ mod tests {
|
||||
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
|
||||
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
|
||||
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
|
||||
// Like `ide-text`, which rejects a set of overlapping edits.
|
||||
for w in edits.windows(2) {
|
||||
let (later, earlier) = (&w[0].range, &w[1].range);
|
||||
assert!((earlier.end.line, earlier.end.col) <= (later.start.line, later.start.col), "overlap: {edits:?}");
|
||||
}
|
||||
let mut out = text.to_owned();
|
||||
for e in edits {
|
||||
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
|
||||
@@ -388,6 +475,64 @@ mod tests {
|
||||
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_chains_get_one_edit() {
|
||||
let src = "import pkg.models\nimport pkg.models.sub\npkg.models.sub.f()\npkg.models.g()\n";
|
||||
assert_eq!(
|
||||
apply(src, "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\nimport lib.pkg.models.sub\nlib.pkg.models.sub.f()\nlib.pkg.models.g()\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_uses_of_the_old_prefix_keep_their_binding() {
|
||||
let moves = &[("pkg.models", "core.models")];
|
||||
assert_eq!(
|
||||
apply("import pkg.models\n\npkg.models.Task()\npkg.helper()\n", "", "", moves),
|
||||
"import core.models, pkg\n\ncore.models.Task()\npkg.helper()\n"
|
||||
);
|
||||
let moves = &[("a.b.c", "a.x.c")];
|
||||
assert_eq!(
|
||||
apply("import a.b.c\na.b.c.f()\na.b.g()\n", "", "", moves),
|
||||
"import a.x.c, a.b\na.x.c.f()\na.b.g()\n"
|
||||
);
|
||||
// Inside a moved package the other uses follow it.
|
||||
assert_eq!(
|
||||
apply("import pkg.models\npkg.helper()\n", "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\nlib.pkg.helper()\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_names_are_left_alone() {
|
||||
let src = "import pkg.models\ndef f(pkg):\n return pkg.models.x\n";
|
||||
assert_eq!(
|
||||
apply(src, "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\ndef f(pkg):\n return lib.pkg.models.x\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_statements_stay_valid() {
|
||||
let moves = &[("pkg.models", "core.models")];
|
||||
assert_eq!(
|
||||
apply("try: from pkg import cli, models\nexcept ImportError: pass\n", "", "", moves),
|
||||
"try: from pkg import cli; from core import models\nexcept ImportError: pass\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("import os; from pkg import cli, models\n", "", "", moves),
|
||||
"import os; from pkg import cli; from core import models\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("from pkg import (\n models, # noqa: F401\n cli, # used below\n)\n", "", "", moves),
|
||||
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("from pkg import (\n cli, # used below\n models,\n)\n", "", "", moves),
|
||||
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers() {
|
||||
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
|
||||
|
||||
@@ -28,6 +28,7 @@ percent-encoding = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ide-sdk.workspace = true
|
||||
tempfile.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
|
||||
|
||||
@@ -352,6 +352,9 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
|
||||
/// No target for `feature`: names the running servers that lack it, so the UI can
|
||||
/// tell "the server can't do this" from "no server is running" (the UI's
|
||||
/// `unavailableText` matches the "… doesn't support …" wording).
|
||||
/// vscode-css-language-server, which lists a selector's own rule among its references.
|
||||
const CSS_SERVER: &str = "vscode-css-language-server";
|
||||
|
||||
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
|
||||
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
|
||||
if running.is_empty() {
|
||||
@@ -2229,7 +2232,19 @@ impl LspManager {
|
||||
// A library method has thousands of usages in the dependencies and the JDK,
|
||||
// which take seconds to search: those in the sources (where scope widening
|
||||
// searches again) are shown first, then the rest are searched once.
|
||||
let sources = self.widened(snap, t, pos, cancel, || query(true), files).await?;
|
||||
let shown = |first: &Vec<ClassifiedReference>| {
|
||||
if let Some(partial) = partial
|
||||
&& !first.is_empty()
|
||||
{
|
||||
partial(References {
|
||||
locations: first.iter().map(|r| r.location.clone()).collect(),
|
||||
classified: first.clone(),
|
||||
incomplete: None,
|
||||
libraries_skipped: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
let sources = self.widened(snap, t, pos, cancel, || query(true), files, shown).await?;
|
||||
if let Some(e) = extension_error.lock().take() {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -2304,6 +2319,7 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
let single = targets.len() == 1;
|
||||
let requests = targets.iter().map(|t| {
|
||||
let (snap, cancel) = (&snap, &cancel);
|
||||
async move {
|
||||
@@ -2320,8 +2336,20 @@ impl LspManager {
|
||||
};
|
||||
let files =
|
||||
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
|
||||
// With one server, what it finds in its own scope is shown while the files beyond
|
||||
// it are searched. The CSS server's answer still loses the rule's own selector.
|
||||
let shown = |first: &Vec<Location>| {
|
||||
if let Some(partial) = partial
|
||||
&& single
|
||||
&& t.server.name != CSS_SERVER
|
||||
&& !first.is_empty()
|
||||
{
|
||||
self.note_virtual(&t.server, first.iter().map(|l| l.uri.as_deref()));
|
||||
partial(References { locations: first.clone(), ..Default::default() });
|
||||
}
|
||||
};
|
||||
let result = if project_wide && !angular {
|
||||
self.widened(snap, t, pos, cancel, query, files).await
|
||||
self.widened(snap, t, pos, cancel, query, files, shown).await
|
||||
} else {
|
||||
query().await.map(|first| {
|
||||
let empty = first.is_empty();
|
||||
@@ -2332,9 +2360,13 @@ impl LspManager {
|
||||
}
|
||||
});
|
||||
// The Angular server lists the declaration even when not asked to: the one
|
||||
// the definition at `pos` points to is taken out of its answer.
|
||||
// the definition at `pos` points to is taken out of its answer. So does the CSS server
|
||||
// with a selector's own rule (`.button`), always: where CSS Modules Kit defines the class
|
||||
// name (`button`), vtsls lists the declaration itself when asked.
|
||||
let declarations = async {
|
||||
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
|
||||
let listed =
|
||||
|t: &Target| (t.server.name == angular::SERVER && !include_declaration) || t.server.name == CSS_SERVER;
|
||||
if !targets.iter().any(listed) {
|
||||
return Vec::new();
|
||||
}
|
||||
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
|
||||
@@ -2351,6 +2383,14 @@ impl LspManager {
|
||||
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
|
||||
if t.server.name == angular::SERVER {
|
||||
locs.retain(|l| !declarations.contains(l));
|
||||
} else if t.server.name == CSS_SERVER {
|
||||
let overlaps = |a: &Location, b: &Location| {
|
||||
a.path == b.path
|
||||
&& a.uri == b.uri
|
||||
&& a.range.start <= b.range.end
|
||||
&& b.range.start <= a.range.end
|
||||
};
|
||||
locs.retain(|l| !declarations.iter().any(|d| overlaps(d, l)));
|
||||
}
|
||||
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
|
||||
self.note_arduino_sources(&t.server, &locs);
|
||||
@@ -2922,6 +2962,11 @@ impl LspManager {
|
||||
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
|
||||
let able: Vec<&Target> =
|
||||
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
|
||||
// CSS Modules Kit (vtsls) renames a class in the stylesheet and its scripts; the CSS
|
||||
// server's own edit replaces the whole selector (`.button`) and would drop the dot.
|
||||
if able.iter().any(|t| t.server.name == "vtsls") {
|
||||
return able.into_iter().filter(|t| t.server.name != CSS_SERVER).collect();
|
||||
}
|
||||
if !able.is_empty() {
|
||||
return able;
|
||||
}
|
||||
@@ -2977,7 +3022,7 @@ impl LspManager {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let w = self.widened(snap, t, pos, cancel, query, files).await?;
|
||||
let w = self.widened(snap, t, pos, cancel, query, files, |_| {}).await?;
|
||||
// The second edit covers the first: its files stay analysed.
|
||||
let mut edit = w.second.unwrap_or(w.first);
|
||||
let mut more: BTreeMap<PathBuf, Vec<TextEdit>> = BTreeMap::new();
|
||||
@@ -3616,7 +3661,7 @@ impl LspManager {
|
||||
let files = |v: &Vec<HierarchyItem>| {
|
||||
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
|
||||
};
|
||||
let w = self.widened(&snap, t, pos, cancel, query, files).await?;
|
||||
let w = self.widened(&snap, t, pos, cancel, query, files, |_| {}).await?;
|
||||
(w.second.unwrap_or(w.first), w.incomplete)
|
||||
}
|
||||
HierarchyDirection::Outgoing => (query().await?, None),
|
||||
|
||||
@@ -116,7 +116,8 @@ impl LspManager {
|
||||
/// Runs `query` on `t`; then again with the project files that mention the
|
||||
/// symbol at `pos` outside `covered(first)` and the server's analysis scope opened.
|
||||
/// A first answer that is empty while the server indexes is retried once
|
||||
/// indexing ends.
|
||||
/// indexing ends. `first_found` gets the first answer before the other files are searched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn widened<R, F, Fut>(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
@@ -125,6 +126,7 @@ impl LspManager {
|
||||
cancel: &CancellationToken,
|
||||
query: F,
|
||||
covered: impl Fn(&R) -> Vec<PathBuf>,
|
||||
first_found: impl Fn(&R),
|
||||
) -> IdeResult<Widened<R>>
|
||||
where
|
||||
F: Fn() -> Fut,
|
||||
@@ -156,6 +158,9 @@ impl LspManager {
|
||||
if candidates.limit_hit {
|
||||
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
|
||||
}
|
||||
// Opening the other candidate files and asking again takes the server a while: what it
|
||||
// found in its own scope can be shown meanwhile.
|
||||
first_found(&first);
|
||||
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
|
||||
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
|
||||
let mut files = self.files_beyond_scope(t, files, cancel).await;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::convert::Conv;
|
||||
use crate::text::DocText;
|
||||
use crate::{DEFAULT_TIMEOUT, LspManager, Outcome, Target, scope};
|
||||
use crate::types::CompletionItem;
|
||||
use crate::{COMPLETION_TIMEOUT, DEFAULT_TIMEOUT, LspManager, Outcome, Target, convert, scope};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos, TextEdit};
|
||||
use lsp_types as lsp;
|
||||
use serde_json::json;
|
||||
@@ -8,6 +9,49 @@ use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl LspManager {
|
||||
/// Completion at `pos` in an isolated text snapshot of `path`, such as a breakpoint condition
|
||||
/// spliced into its line; the open document and its diagnostics stay untouched.
|
||||
pub async fn snapshot_completion(
|
||||
&self,
|
||||
path: &Path,
|
||||
language: &LanguageId,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<CompletionItem>> {
|
||||
let targets =
|
||||
self.snapshot_targets(path, language, "snapshot completion", |c| c.has("completionProvider")).await?;
|
||||
let snapshot = scope::snapshot_path(path, "completion")?;
|
||||
let doc = Arc::new(DocText::new(text));
|
||||
let requests = targets.iter().map(|t| {
|
||||
let (snapshot, doc) = (&snapshot, &doc);
|
||||
async move {
|
||||
let mut opened = scope::TransientFiles::empty(self, t);
|
||||
opened.hold(snapshot, language, text);
|
||||
let params = json!({
|
||||
"textDocument": { "uri": opened.files[0].1 },
|
||||
"position": doc.ide_to_lsp(t.enc(), pos),
|
||||
"context": { "triggerKind": 1 },
|
||||
});
|
||||
let r = self.call(t, "textDocument/completion", params, Some(cancel), COMPLETION_TIMEOUT).await;
|
||||
r.map(|v| {
|
||||
let conv = Conv::new(t.enc(), |_| Some(doc.clone()));
|
||||
let items = convert::parse_completion_response(v).1.into_iter();
|
||||
items.map(|i| convert::completion_item(&conv, path, i, t.server.id)).collect::<Vec<_>>()
|
||||
})
|
||||
}
|
||||
});
|
||||
let mut out = Outcome::<Vec<_>>::new();
|
||||
for result in futures::future::join_all(requests).await {
|
||||
match result {
|
||||
Ok(items) => out.value.get_or_insert_with(Vec::new).extend(items),
|
||||
Err(error) if cancel.is_cancelled() => return Err(error),
|
||||
Err(error) => out.fail(error),
|
||||
}
|
||||
}
|
||||
out.finish(Vec::new())
|
||||
}
|
||||
|
||||
/// Reads a source action for an isolated text snapshot. The caller owns the text and applies the edits.
|
||||
pub async fn source_action_text(
|
||||
&self,
|
||||
|
||||
@@ -4436,6 +4436,45 @@ async fn snapshot_diagnostics_collect_pull_and_push_without_publishing_problems(
|
||||
)));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn snapshot_completion_asks_a_transient_copy_and_leaves_the_live_document() {
|
||||
let caps = json!({
|
||||
"positionEncoding": "utf-8",
|
||||
"textDocumentSync": { "openClose": true, "change": 2 },
|
||||
"completionProvider": {},
|
||||
});
|
||||
let h = harness(&[("mock", caps)]);
|
||||
let (_, path) = h.open("a.mk", "the live editor\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let uri = uri_of(&path);
|
||||
let live = uri.clone();
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, params| {
|
||||
(method == "textDocument/completion").then(|| {
|
||||
assert_ne!(params["textDocument"]["uri"], live);
|
||||
// UTF-16 column 4 after the emoji is UTF-8 byte 6.
|
||||
assert_eq!(params["position"], json!({ "line": 1, "character": 6 }));
|
||||
json!([{ "label": "total", "kind": 5 }])
|
||||
})
|
||||
}));
|
||||
let items = h
|
||||
.mgr
|
||||
.snapshot_completion(&path, &LanguageId("mock".into()), "a\n🙂o.\nb", Pos::new(1, 4), &Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
items.iter().map(|i| (i.label.as_str(), i.kind)).collect::<Vec<_>>(),
|
||||
[("total", Some(CompletionKind::Field))]
|
||||
);
|
||||
assert!(s.notified("textDocument/didChange").is_empty());
|
||||
eventually(|| s.notified("textDocument/didClose").len() == 1).await;
|
||||
let opened: Vec<_> =
|
||||
s.notified("textDocument/didOpen").into_iter().filter(|notice| notice["textDocument"]["uri"] != uri).collect();
|
||||
assert_eq!(opened.len(), 1);
|
||||
assert_eq!(opened[0]["textDocument"]["text"], "a\n🙂o.\nb");
|
||||
assert!(s.docs.lock().contains_key(&uri));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn source_actions_use_snapshot_text_and_accept_only_its_passive_edits() {
|
||||
let caps = json!({
|
||||
@@ -4768,6 +4807,57 @@ async fn angular_references_leave_out_the_declaration_unless_asked() {
|
||||
assert_eq!(vtsls.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn css_references_leave_out_the_selector_where_css_modules_kit_defines_it() {
|
||||
let servers = [("vscode-css-language-server", incremental_caps()), ("vtsls", incremental_caps())];
|
||||
let h = harness_for("css", "css", &servers, &[]);
|
||||
let (doc, path) = h.open("a.module.css", ".button { color: red; }\n");
|
||||
h.wait_status("vscode-css-language-server", ServerStatus::Ready).await;
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
let tsx = h.root.join("a.tsx");
|
||||
let at = |uri: &str, line: u32, from: u32, to: u32| json!({ "uri": uri, "range": {"start":{"line":line,"character":from},"end":{"line":line,"character":to}} });
|
||||
let (css, tsx_uri) = (uri_of(&path), uri_of(&tsx));
|
||||
// The CSS server lists the rule itself (`.button`) whatever `includeDeclaration` says;
|
||||
// CSS Modules Kit (vtsls) defines the class at `button` and lists the TSX use.
|
||||
h.launcher.state("vscode-css-language-server").respond("textDocument/references", json!([at(&css, 0, 0, 7)]));
|
||||
let vtsls = h.launcher.state("vtsls");
|
||||
vtsls.respond("textDocument/references", json!([at(&tsx_uri, 4, 30, 36)]));
|
||||
vtsls.respond("textDocument/definition", json!([at(&css, 0, 1, 7)]));
|
||||
let mgr = &h.mgr;
|
||||
let found = |include_declaration: bool| async move {
|
||||
let refs =
|
||||
mgr.references_streaming(doc, Pos::new(0, 3), include_declaration, false, true, Default::default(), None);
|
||||
let mut v: Vec<(PathBuf, Range)> =
|
||||
refs.await.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(found(false).await, [(tsx.clone(), rng(4, 30, 4, 36))]);
|
||||
// Asked for the declaration, vtsls lists it once, as the class name.
|
||||
vtsls.respond("textDocument/references", json!([at(&css, 0, 1, 7), at(&tsx_uri, 4, 30, 36)]));
|
||||
assert_eq!(found(true).await, [(path.clone(), rng(0, 1, 0, 7)), (tsx, rng(4, 30, 4, 36))]);
|
||||
|
||||
// Rename: CSS Modules Kit's edit, not the CSS server's, which would replace `.button`.
|
||||
let css_server = h.launcher.state("vscode-css-language-server");
|
||||
let range = |from: u32, to: u32| json!({"start":{"line":0,"character":from},"end":{"line":0,"character":to}});
|
||||
css_server.respond("textDocument/prepareRename", range(0, 7));
|
||||
css_server.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": { css.clone(): [{ "range": range(0, 7), "newText": "primary" }] } }),
|
||||
);
|
||||
vtsls.respond("textDocument/prepareRename", range(1, 7));
|
||||
vtsls.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": { css.clone(): [{ "range": range(1, 7), "newText": "primary" }] } }),
|
||||
);
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit;
|
||||
assert!(
|
||||
matches!(&edit.files[..], [FileEdit::Edit { edits, .. }] if edits.len() == 1 && edits[0].range == rng(0, 1, 0, 7)),
|
||||
"{edit:?}"
|
||||
);
|
||||
assert!(css_server.requested("textDocument/rename").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn utf8_server_positions_are_converted() {
|
||||
let h = harness(&[(
|
||||
@@ -6076,12 +6166,23 @@ async fn references_open_unopened_files_that_mention_the_name() {
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 2).await;
|
||||
|
||||
let refs =
|
||||
h.mgr.references_streaming(doc, Pos::new(0, 5), true, true, true, Default::default(), None).await.unwrap();
|
||||
let partial = Mutex::new(Vec::new());
|
||||
let shown = |found: ide_lsp::types::References| {
|
||||
let mut paths: Vec<PathBuf> = found.locations.iter().map(|l| l.path.to_path_buf()).collect();
|
||||
paths.sort();
|
||||
partial.lock().push(paths);
|
||||
};
|
||||
let refs = h
|
||||
.mgr
|
||||
.references_streaming(doc, Pos::new(0, 5), true, true, true, Default::default(), Some(&shown))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut paths: Vec<PathBuf> = refs.locations.iter().map(|l| l.path.to_path_buf()).collect();
|
||||
paths.sort();
|
||||
assert_eq!(paths, vec![a.clone(), b.clone(), d.clone()]);
|
||||
assert_eq!(refs.incomplete, None);
|
||||
// What the server found in the open files is shown before the candidate files are searched.
|
||||
assert_eq!(*partial.lock(), vec![vec![a.clone(), d.clone()]]);
|
||||
|
||||
let q = seen.lock()[0].clone();
|
||||
assert_eq!((q.word.as_str(), q.root.as_path(), q.limit), (WORD, h.root.as_path(), ide_lsp::MAX_CANDIDATES));
|
||||
@@ -6477,13 +6578,15 @@ async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
|
||||
.await
|
||||
.unwrap();
|
||||
let partials = partials.into_inner();
|
||||
assert_eq!(partials.len(), 1);
|
||||
assert_eq!(partials.len(), 2);
|
||||
let paths =
|
||||
|r: &References| r.locations.iter().map(|l| (l.path.to_path_buf(), l.uri.is_some())).collect::<Vec<_>>();
|
||||
let mut shown = paths(&partials[0]);
|
||||
// The open file's usages, then the sources' once the candidate files were searched.
|
||||
assert_eq!(paths(&partials[0]), [(a.clone(), false)]);
|
||||
let mut shown = paths(&partials[1]);
|
||||
shown.sort();
|
||||
assert_eq!(shown, [(a.clone(), false), (b.clone(), false)]);
|
||||
assert_eq!(partials[0].classified.len(), 2);
|
||||
assert_eq!(partials[1].classified.len(), 2);
|
||||
// All of them, those in the sources first.
|
||||
assert_eq!(refs.locations.len(), 3);
|
||||
assert!(refs.locations[..2].iter().all(|l| l.uri.is_none()));
|
||||
@@ -6495,7 +6598,7 @@ async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
|
||||
let scopes: Vec<_> =
|
||||
s.requested("workspace/executeCommand").iter().map(|p| p["arguments"].get(4).cloned()).collect();
|
||||
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources")), None]);
|
||||
// Without the libraries: the sources alone, widened, and no partial answer.
|
||||
// Without the libraries: the sources alone, widened, the open file's shown first.
|
||||
let partials = Mutex::new(Vec::new());
|
||||
let project = h
|
||||
.mgr
|
||||
@@ -6510,7 +6613,8 @@ async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(partials.into_inner().is_empty());
|
||||
let partials = partials.into_inner();
|
||||
assert_eq!(partials.iter().map(paths).collect::<Vec<_>>(), [[(a.clone(), false)]]);
|
||||
assert!(project.libraries_skipped);
|
||||
assert_eq!(project.locations.len(), 2);
|
||||
assert!(project.locations.iter().all(|l| l.uri.is_none()));
|
||||
|
||||
@@ -969,6 +969,258 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
|
||||
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
|
||||
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
|
||||
/// IDE's copy loads, once: also when the project has the package in its `node_modules`, and when
|
||||
/// its tsconfig declares it in `compilerOptions.plugins` (#6336's probe location leaves it out,
|
||||
/// and tsserver resolves the declared name from the global plugin's location). Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server typescript@6 @css-modules-kit/[email protected]`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server and @css-modules-kit/ts-plugin (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn css_modules_kit_navigates_between_tsx_and_module_css() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
// (the project has its own package, its tsconfig declares the plugin)
|
||||
for (project_copy, declared) in [(false, false), (true, false), (true, true)] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
|
||||
if project_copy {
|
||||
// Says so in every file if it is ever loaded.
|
||||
let package = root.join("node_modules/@css-modules-kit/ts-plugin");
|
||||
std::fs::create_dir_all(&package).unwrap();
|
||||
std::fs::write(package.join("package.json"), r#"{"name":"@css-modules-kit/ts-plugin","version":"0.0.1"}"#)
|
||||
.unwrap();
|
||||
std::fs::write(package.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", "'the project copy'")).unwrap();
|
||||
}
|
||||
let plugins = if declared { r#", "plugins": [{ "name": "@css-modules-kit/ts-plugin" }]"# } else { "" };
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
format!(
|
||||
"{{\n // JSON with comments\n \"compilerOptions\": {{ \"strict\": true, \"jsx\": \"preserve\", \"module\": \"ESNext\", \"moduleResolution\": \"Bundler\"{plugins} }},\n \"include\": [\"src\"],\n \"cmkOptions\": {{ \"enabled\": true }}\n}}\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let css_path = root.join("src/Button.module.css");
|
||||
let css = ".button { color: red; }\n.label { color: blue; }\n";
|
||||
std::fs::write(&css_path, css).unwrap();
|
||||
let tsx_path = root.join("src/Button.tsx");
|
||||
let tsx =
|
||||
"import styles from './Button.module.css';\nexport const a = styles.button;\nexport const b = styles.";
|
||||
std::fs::write(&tsx_path, tsx).unwrap();
|
||||
let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None);
|
||||
vtsls.tsserver_project = true;
|
||||
assert!(ide_sdk::apply::configure_css_modules(&mut vtsls, &root, Some(&tools)));
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
// The plugin is the IDE's global one: no probe location for it.
|
||||
assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path()));
|
||||
let registry = LanguageRegistry::from_configs(vec![
|
||||
lang("typescriptreact", "tsx", vtsls.clone()),
|
||||
lang("css", "css", vtsls),
|
||||
]);
|
||||
let (mgr, events) = manager(&root, registry);
|
||||
let tsx_doc = DocId::next();
|
||||
mgr.did_open(tsx_doc, &tsx_path, &LanguageId::new("typescriptreact"), 1, tsx);
|
||||
let css_doc = DocId::next();
|
||||
mgr.did_open(css_doc, &css_path, &LanguageId::new("css"), 1, css);
|
||||
assert_eq!(mgr.servers().iter().filter(|s| s.name == "vtsls").count(), 1, "one vtsls for both");
|
||||
let case = format!("project copy: {project_copy}, declared: {declared}");
|
||||
|
||||
// `styles.button` → `.button`.
|
||||
let defs = retry("definition in the stylesheet", Duration::from_secs(90), || {
|
||||
let (mgr, css_path) = (mgr.clone(), css_path.clone());
|
||||
async move {
|
||||
let defs = mgr.goto(tsx_doc, Pos::new(1, 26), GotoKind::Definition).await.ok()?;
|
||||
defs.iter().any(|d| d.path == css_path).then_some(defs)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs.len(), 1, "{case}: {defs:?}");
|
||||
assert_eq!((defs[0].range.start.line, defs[0].range.start.col), (0, 1), "{case}");
|
||||
let list = retry("class name completion", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(tsx_doc, Pos::new(2, 24), Some(".".into()), Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == "label").then_some(list)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let labels: Vec<&str> =
|
||||
list.items.iter().map(|i| i.label.as_str()).filter(|l| ["button", "label"].contains(l)).collect();
|
||||
assert_eq!(labels.len(), 2, "{case}: each class once, {labels:?}");
|
||||
|
||||
// `.button` in the stylesheet → its use in the component, once.
|
||||
let refs = retry("references from the stylesheet", Duration::from_secs(30), || {
|
||||
let (mgr, tsx_path) = (mgr.clone(), tsx_path.clone());
|
||||
async move {
|
||||
let refs = mgr
|
||||
.references_streaming(css_doc, Pos::new(0, 3), false, true, false, Default::default(), None)
|
||||
.await
|
||||
.ok()?;
|
||||
Some(refs.locations).filter(|l| l.iter().any(|l| l.path == tsx_path))
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(refs.len(), 1, "{case}: {refs:?}");
|
||||
assert_eq!((refs[0].path.to_path_buf(), refs[0].range.start.line), (tsx_path.clone(), 1), "{case}");
|
||||
let renamed = mgr.rename(css_doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit;
|
||||
assert_eq!(edited_lines(&renamed, &css_path), [0], "{case}");
|
||||
assert_eq!(edited_lines(&renamed, &tsx_path), [1], "{case}");
|
||||
// The component's diagnostics are in: the plugins have run on it.
|
||||
retry("diagnostics of the component", Duration::from_secs(30), || {
|
||||
let found =
|
||||
events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { path, .. } if path == &tsx_path));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
let project_copy_loaded = events.lock().iter().any(|e| {
|
||||
matches!(e, IdeEvent::Diagnostics { items, .. } if items.iter().any(|d| d.message.contains("the project copy")))
|
||||
});
|
||||
assert!(!project_copy_loaded, "{case}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const MDX_BUTTON: &str =
|
||||
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
|
||||
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
|
||||
|
||||
/// The MDX Language Server with the `typescript.tsdk` the launcher adds. Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @mdx-js/language-server
|
||||
/// typescript@6 @types/react`; the project is created inside it, so that it
|
||||
/// resolves the React types.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @mdx-js/language-server, typescript and @types/react (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn mdx_language_server_end_to_end() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir_in(&tools).unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
"{\"compilerOptions\":{\"strict\":true,\"jsx\":\"react-jsx\",\"moduleResolution\":\"bundler\",\"module\":\"esnext\"},\"mdx\":{\"checkMdx\":true}}",
|
||||
)
|
||||
.unwrap();
|
||||
let (button, file) = (root.join("Button.tsx"), root.join("doc.mdx"));
|
||||
std::fs::write(&button, MDX_BUTTON).unwrap();
|
||||
std::fs::write(&file, MDX_DOC).unwrap();
|
||||
|
||||
let mut mdx = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("mdx")).unwrap();
|
||||
let server = &mut mdx.language_servers[0];
|
||||
server.command = tools.join("node_modules/.bin/mdx-language-server").to_string_lossy().into_owned();
|
||||
let tsdk = tools.join("node_modules/typescript/lib").to_string_lossy().into_owned();
|
||||
server.initialization_options.as_mut().unwrap()["typescript"]
|
||||
.as_table_mut()
|
||||
.unwrap()
|
||||
.insert("tsdk".into(), toml::Value::String(tsdk));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![mdx]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &file, &LanguageId::new("mdx"), 1, MDX_DOC);
|
||||
|
||||
// `Button` in `<Button label="hi" />`.
|
||||
let hover = retry("hover", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(doc, Pos::new(6, 3), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("label: string"), "{}", hover.contents.value);
|
||||
let defs = mgr.goto(doc, Pos::new(6, 3), GotoKind::Definition).await.unwrap();
|
||||
assert!(defs.iter().any(|d| d.path == button), "{defs:?}");
|
||||
|
||||
// Members of `count` inside `{…}`, and the imported component in JSX.
|
||||
for (pos, label) in [(Pos::new(10, 7), "toFixed"), (Pos::new(6, 3), "Button")] {
|
||||
retry(label, Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == label).then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
// Markdown headings come from the server too (marksman skips `.mdx` by default).
|
||||
let symbols = mgr.document_symbols(doc).await.unwrap().unwrap();
|
||||
assert!(symbols.iter().any(|s| s.name.contains("Hello")), "{symbols:?}");
|
||||
|
||||
// `label={count}`: number is not assignable to string.
|
||||
retry("prop type error", Duration::from_secs(60), || {
|
||||
let found = events.lock().iter().any(|e| {
|
||||
matches!(e, IdeEvent::Diagnostics { path, items, .. }
|
||||
if path == &file && items.iter().any(|d| d.range.start.line == 8 && d.message.contains("string")))
|
||||
});
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// A tsserver plugin reporting `from <name>` at the start of every file.
|
||||
const DIAGNOSTIC_PLUGIN: &str = "module.exports = () => ({ create(info) {\n const ls = info.languageService;\n const proxy = Object.create(null);\n for (const k of Object.keys(ls)) proxy[k] = (...a) => ls[k](...a);\n proxy.getSemanticDiagnostics = (f) => [...ls.getSemanticDiagnostics(f), { file: ls.getProgram().getSourceFile(f), start: 0, length: 1, messageText: 'from ' + NAME, category: 1, code: 99001 }];\n return proxy;\n} });\n";
|
||||
|
||||
/// tsconfig `compilerOptions.plugins` load from the project's `node_modules` with vtsls' own
|
||||
/// TypeScript through the probe location `configure_tsconfig_plugins` writes (#6336); one that
|
||||
/// isn't installed is skipped, and the IDE's global plugins keep loading their own copies,
|
||||
/// also when the project has a package of the same name. Set `OPENIDEA_TEST_NPM_TOOLS` to a
|
||||
/// dir with `npm i @vtsls/language-server typescript@5`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn tsconfig_plugins_load_from_the_project_with_the_bundled_typescript() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
// Outside the project: a probe location resolves plugins from its ancestors' node_modules too.
|
||||
let ide = tempfile::tempdir().unwrap();
|
||||
let ide = dunce::canonicalize(ide.path()).unwrap();
|
||||
let plugin = |dir: &Path, name: &str, says: &str| {
|
||||
let dir = dir.join("node_modules").join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", &format!("'{says}'"))).unwrap();
|
||||
};
|
||||
plugin(&root, "project-plugin", "project-plugin");
|
||||
plugin(&root, "global-plugin", "the project's global-plugin");
|
||||
plugin(&ide, "global-plugin", "global-plugin");
|
||||
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
|
||||
let plugins = r#"[{"name":"not-installed"},{"name":"project-plugin"}]"#;
|
||||
std::fs::write(root.join("tsconfig.json"), format!("{{\"compilerOptions\":{{\"plugins\":{plugins}}}}}")).unwrap();
|
||||
let main = root.join("main.ts");
|
||||
let text = "export const n: number = 1;\n";
|
||||
std::fs::write(&main, text).unwrap();
|
||||
let global = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
|
||||
"name": "global-plugin",
|
||||
"location": ide.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}] } } });
|
||||
|
||||
for configured in [false, true] {
|
||||
let mut server = npm_server(&tools, "vtsls", "vtsls", Some(global.clone()));
|
||||
server.tsserver_project = true;
|
||||
if configured {
|
||||
assert!(ide_sdk::apply::configure_tsconfig_plugins(&mut server, &root, &ide.join("data")));
|
||||
}
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
|
||||
let mut messages = retry("the plugins' diagnostics", Duration::from_secs(90), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => {
|
||||
Some(items.iter().map(|d| d.message.clone()).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
messages.sort();
|
||||
let expected: &[&str] =
|
||||
if configured { &["from global-plugin", "from project-plugin"] } else { &["from global-plugin"] };
|
||||
assert_eq!(messages, expected);
|
||||
let crashed = matches!(last_status(&events, "vtsls"), Some((ServerStatus::Crashed, _)));
|
||||
assert!(!crashed, "{:?}", last_status(&events, "vtsls"));
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
@@ -1425,3 +1677,81 @@ async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// Indented Sass through the built-in `sass` definition: completion, Go to
|
||||
/// Declaration and hover across `@use`, and syntax errors as diagnostics.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires some-sass-language-server on PATH"]
|
||||
async fn some_sass_indented_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let theme = root.join("_theme.sass");
|
||||
std::fs::write(
|
||||
&theme,
|
||||
"/// Brand colour\n$brand: #336699\n\n/// Rounded corners\n@mixin rounded($r: 4px)\n border-radius: $r\n",
|
||||
)
|
||||
.unwrap();
|
||||
let main = root.join("main.sass");
|
||||
let source = "@use \"theme\"\n\n.button\n color: theme.$brand\n +theme.rounded(2px)\n";
|
||||
std::fs::write(&main, source).unwrap();
|
||||
let sass = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("sass")).unwrap();
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![sass]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("sass"), 1, source);
|
||||
let name = "some-sass-language-server";
|
||||
retry("some-sass ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, name);
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("some-sass failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
|
||||
// `theme.$brand` and the `+theme.rounded` mixin, both in `_theme.sass`.
|
||||
for (pos, line) in [(Pos::new(3, 17), 1), (Pos::new(4, 10), 4)] {
|
||||
let defs = retry("definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, pos, GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (theme.clone(), line), "{pos:?}");
|
||||
}
|
||||
// The `@use` path is a document link, which Go to Declaration follows.
|
||||
let links = mgr.document_links(doc).await.unwrap();
|
||||
assert!(
|
||||
links
|
||||
.iter()
|
||||
.any(|l| l.range.start.line == 0 && l.path.as_ref().map(|p| p.to_path_buf()) == Some(theme.clone())),
|
||||
"{links:?}"
|
||||
);
|
||||
let hover = mgr.hover(doc, Pos::new(3, 17), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("#336699") && hover.contents.value.contains("Brand colour"));
|
||||
let hover = mgr.hover(doc, Pos::new(4, 10), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("Rounded corners"), "{}", hover.contents.value);
|
||||
|
||||
// `$` lists the module's variables, `+` its mixins.
|
||||
let edited = format!("{source} margin: theme.$\n +theme.\n");
|
||||
mgr.did_change(
|
||||
doc,
|
||||
2,
|
||||
&[AppliedChange { range: Range::point(Pos::new(5, 0)), text: edited[source.len()..].into() }],
|
||||
&|| unreachable!(),
|
||||
);
|
||||
let labels = |list: ide_lsp::types::CompletionList| list.items.into_iter().map(|i| i.label).collect::<Vec<_>>();
|
||||
let vars = labels(mgr.completion(doc, Pos::new(5, 16), Some("$".into()), Default::default()).await.unwrap());
|
||||
assert!(vars.iter().any(|l| l.contains("$brand")), "{vars:?}");
|
||||
let mixins = labels(mgr.completion(doc, Pos::new(6, 9), Some(".".into()), Default::default()).await.unwrap());
|
||||
assert!(mixins.iter().any(|l| l.contains("rounded")), "{mixins:?}");
|
||||
|
||||
let errors = retry("diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().rev().find_map(|event| match event {
|
||||
IdeEvent::Diagnostics { source, items, .. } if source == name && !items.is_empty() => Some(items.clone()),
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
db06d81fb37a51711e2b76ab0192eb23293ef498e8ff6e5e46e0b5099d6ba038
|
||||
@@ -10,11 +10,14 @@
|
||||
//! | Python | `py-spy record --format raw` | collapsed stacks |
|
||||
//! | JVM applications | async-profiler agent (`JAVA_TOOL_OPTIONS`) | collapsed stacks |
|
||||
//! | native / `cargo run` (Linux) | `perf record -g`, then `perf script` | perf script text |
|
||||
//!
|
||||
//! Saved snapshots open too: V8 `.cpuprofile` files and cProfile / profile `pstats` files.
|
||||
|
||||
mod formats;
|
||||
mod jvm;
|
||||
mod live;
|
||||
mod plan;
|
||||
mod pstats;
|
||||
mod tree;
|
||||
|
||||
pub use live::gc_before_stop;
|
||||
@@ -83,6 +86,27 @@ pub struct MethodStat {
|
||||
pub frame: u32,
|
||||
pub self_weight: f64,
|
||||
pub total: f64,
|
||||
/// Calls, when the profiler counts them (cProfile); sampling profilers don't.
|
||||
pub calls: Option<f64>,
|
||||
/// Calls that were not recursive (`pstats`' primitive calls).
|
||||
pub primitive_calls: Option<f64>,
|
||||
}
|
||||
|
||||
/// What one function spent when called from another, as a call-graph profiler (cProfile)
|
||||
/// records it. Sampling profilers leave [`Profile::calls`] empty; their callers and callees
|
||||
/// come from the call tree.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CallEdge {
|
||||
/// Index into [`Profile::frames`].
|
||||
pub caller: u32,
|
||||
pub callee: u32,
|
||||
/// Weight spent in the callee itself on these calls.
|
||||
pub self_weight: f64,
|
||||
/// Weight of these calls, including what the callee called.
|
||||
pub total: f64,
|
||||
pub calls: f64,
|
||||
pub primitive_calls: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -99,6 +123,9 @@ pub struct Profile {
|
||||
pub nodes: Vec<ProfileNode>,
|
||||
/// Sorted by self weight, heaviest first.
|
||||
pub methods: Vec<MethodStat>,
|
||||
/// Exact caller → callee totals of a call-graph profile; its call tree is then rebuilt
|
||||
/// from them, so below the first level it is an estimate. Empty for sampled profiles.
|
||||
pub calls: Vec<CallEdge>,
|
||||
}
|
||||
|
||||
/// Where a prepared run's profile will be, and how to read it.
|
||||
@@ -109,8 +136,10 @@ pub enum ProfileSpec {
|
||||
/// ran no code of `root` (the package manager of an npm script) are left
|
||||
/// out when another one did.
|
||||
CpuProfiles { dir: IpcPath, root: IpcPath },
|
||||
/// One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI).
|
||||
CpuProfileFile { path: IpcPath },
|
||||
/// A snapshot file the user opened: a V8 `.cpuprofile` (`node --cpu-prof`, Chrome
|
||||
/// DevTools, CI) or a `pstats` file (cProfile, profile, yappi), told apart by content.
|
||||
/// Relative source files of a `pstats` file resolve against `root`, then its directory.
|
||||
SnapshotFile { path: IpcPath, root: Option<IpcPath> },
|
||||
/// Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve
|
||||
/// against `base`. `jvm_root`: map JVM class frames to sources below it. For the
|
||||
/// allocation modes the last frame of a JVM stack is the allocated type.
|
||||
@@ -174,12 +203,25 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
}
|
||||
Ok(b.finish("node --cpu-prof", "ms", ProfileMode::Cpu))
|
||||
}
|
||||
ProfileSpec::CpuProfileFile { path } => {
|
||||
ProfileSpec::SnapshotFile { path, root } => {
|
||||
let path: &Path = path.as_ref();
|
||||
let name =
|
||||
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
|
||||
let text =
|
||||
std::fs::read_to_string(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?;
|
||||
let bytes = std::fs::read(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?;
|
||||
let ext = path.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
// The content decides (`node --cpu-prof-name=cpu.prof` writes JSON); the extension only
|
||||
// names what a file that is neither failed to be.
|
||||
let json = bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{');
|
||||
if pstats::looks_like_pstats(&bytes) || (!json && matches!(ext.as_str(), "pstats" | "pstat" | "prof")) {
|
||||
let bases: Vec<&Path> = root.iter().map(|r| r.as_ref()).chain(path.parent()).collect();
|
||||
let profile = pstats::read(&bytes, &bases, "cProfile")
|
||||
.map_err(|e| IdeError::invalid(format!("{name} is not a cProfile snapshot ({e}).")))?;
|
||||
if profile.methods.is_empty() {
|
||||
return Err(IdeError::invalid(format!("{name} has no calls.")));
|
||||
}
|
||||
return Ok(profile);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
formats::add_cpuprofile(&mut b, &text)
|
||||
.map_err(|e| IdeError::invalid(format!("{name} is not a V8 CPU profile ({e}).")))?;
|
||||
if b.is_empty() {
|
||||
@@ -289,7 +331,7 @@ mod tests {
|
||||
);
|
||||
let path = dir.path().join("CPU.cpuprofile");
|
||||
std::fs::write(&path, json).unwrap();
|
||||
let p = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap();
|
||||
let p = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap();
|
||||
assert_eq!((p.unit.as_str(), p.mode), ("ms", ProfileMode::Cpu));
|
||||
let frame = |name: &str| p.frames.iter().find(|f| f.name == name).unwrap();
|
||||
assert_eq!(frame("here").file.as_deref(), Some(src.as_path()));
|
||||
@@ -307,14 +349,42 @@ mod tests {
|
||||
] {
|
||||
let path = dir.path().join(file);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let err = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap_err();
|
||||
let err = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap_err();
|
||||
assert_eq!(err.message.split_once(' ').unwrap().0, file);
|
||||
assert!(err.message.contains(says), "{}", err.message);
|
||||
}
|
||||
let missing = collect(&ProfileSpec::CpuProfileFile { path: dir.path().join("gone.cpuprofile").into() });
|
||||
let missing =
|
||||
collect(&ProfileSpec::SnapshotFile { path: dir.path().join("gone.cpuprofile").into(), root: None });
|
||||
assert!(missing.unwrap_err().message.starts_with("Cannot read gone.cpuprofile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_pstats_file_is_told_apart_by_content() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("run.out");
|
||||
std::fs::write(&path, include_bytes!("../testdata/fib.prof")).unwrap();
|
||||
std::fs::write(dir.path().join("work.py"), "").unwrap();
|
||||
let p = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap();
|
||||
assert_eq!((p.profiler.as_str(), p.unit.as_str()), ("cProfile", "ms"));
|
||||
assert!(!p.calls.is_empty());
|
||||
let fib = p.frames.iter().find(|f| f.name == "fib").unwrap();
|
||||
assert_eq!(fib.file.as_deref(), Some(dir.path().join("work.py").as_path()), "relative to the snapshot");
|
||||
|
||||
// A Go pprof profile (gzip) named `.prof`.
|
||||
let bad = dir.path().join("bad.prof");
|
||||
std::fs::write(&bad, b"\x1f\x8b\x08\x00").unwrap();
|
||||
let err = collect(&ProfileSpec::SnapshotFile { path: bad.into(), root: None }).unwrap_err();
|
||||
assert!(err.message.starts_with("bad.prof is not a cProfile snapshot"), "{}", err.message);
|
||||
|
||||
// `node --cpu-prof --cpu-prof-name=cpu.prof`.
|
||||
let v8 = dir.path().join("cpu.prof");
|
||||
let json = r#"{"nodes":[{"id":1,"callFrame":{"functionName":"(root)","url":"","lineNumber":-1},"children":[2]},
|
||||
{"id":2,"callFrame":{"functionName":"work","url":"","lineNumber":0}}],"samples":[2,2],"timeDeltas":[0,1000]}"#;
|
||||
std::fs::write(&v8, json).unwrap();
|
||||
let p = collect(&ProfileSpec::SnapshotFile { path: v8.into(), root: None }).unwrap();
|
||||
assert_eq!(p.profiler, "V8 CPU profile");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_profile_stays_in_samples() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,746 @@
|
||||
//! cProfile / profile snapshots (`pstats` files): a marshal'd dict
|
||||
//! `{(file, line, name): (cc, nc, tt, ct, {caller: (nc, cc, tt, ct)})}` in seconds,
|
||||
//! read without a Python interpreter. `profile` (the pure-Python module) stores a bare
|
||||
//! call count per caller instead of the tuple.
|
||||
|
||||
use crate::tree::{FrameKey, TreeBuilder};
|
||||
use crate::{CallEdge, MethodStat, Profile, ProfileMode};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Whether `bytes` start like a marshal'd pstats dict rather than JSON (`{"nodes"…`).
|
||||
pub(crate) fn looks_like_pstats(bytes: &[u8]) -> bool {
|
||||
// A dict (`{`, with or without the ref flag) whose first key is a tuple, or empty (`0`).
|
||||
matches!(bytes, [first, second, ..] if first & 0x7f == b'{' && matches!(second & 0x7f, b'(' | b')' | b'0'))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Value {
|
||||
None,
|
||||
Int(f64),
|
||||
Float(f64),
|
||||
// Shared: a reference (`r`) to a key or file name is a cheap clone.
|
||||
Str(Rc<str>),
|
||||
Seq(Rc<[Value]>),
|
||||
Dict(Vec<(Value, Value)>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
fn num(&self) -> Option<f64> {
|
||||
match self {
|
||||
Value::Int(v) | Value::Float(v) => Some(*v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The subset of marshal that Python 3 writes pstats files with (formats 2–5; Python 2's
|
||||
/// `R` and `I` are not read).
|
||||
struct Reader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
refs: Vec<Value>,
|
||||
}
|
||||
|
||||
const MAX_DEPTH: u32 = 32;
|
||||
|
||||
impl Reader<'_> {
|
||||
fn take(&mut self, n: usize) -> Result<&[u8], String> {
|
||||
let end = self.pos.checked_add(n).filter(|e| *e <= self.data.len()).ok_or("truncated")?;
|
||||
let s = &self.data[self.pos..end];
|
||||
self.pos = end;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn u8(&mut self) -> Result<u8, String> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
|
||||
fn i32(&mut self) -> Result<i32, String> {
|
||||
Ok(i32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
|
||||
fn len(&mut self, short: bool) -> Result<usize, String> {
|
||||
if short {
|
||||
return Ok(self.u8()? as usize);
|
||||
}
|
||||
usize::try_from(self.i32()?).map_err(|_| "negative length".to_owned())
|
||||
}
|
||||
|
||||
fn str(&mut self, n: usize) -> Result<Value, String> {
|
||||
Ok(Value::Str(String::from_utf8_lossy(self.take(n)?).into()))
|
||||
}
|
||||
|
||||
fn read(&mut self, depth: u32) -> Result<Value, String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err("nested too deeply".into());
|
||||
}
|
||||
let code = self.u8()?;
|
||||
// FLAG_REF: the object is remembered for later `r` references. Containers take
|
||||
// their slot before their items, as CPython numbers them.
|
||||
let slot = (code & 0x80 != 0).then(|| {
|
||||
self.refs.push(Value::None);
|
||||
self.refs.len() - 1
|
||||
});
|
||||
let value = match code & 0x7f {
|
||||
b'N' | b'F' | b'T' => Value::None,
|
||||
b'i' => Value::Int(self.i32()? as f64),
|
||||
b'l' => {
|
||||
let n = self.i32()?;
|
||||
let mut v = 0.0;
|
||||
for i in 0..n.unsigned_abs() {
|
||||
let digit = u16::from_le_bytes(self.take(2)?.try_into().unwrap());
|
||||
v += f64::from(digit) * 2f64.powi(15 * i as i32);
|
||||
}
|
||||
Value::Int(if n < 0 { -v } else { v })
|
||||
}
|
||||
b'g' => Value::Float(f64::from_le_bytes(self.take(8)?.try_into().unwrap())),
|
||||
b'f' => {
|
||||
let n = self.len(true)?;
|
||||
let text = String::from_utf8_lossy(self.take(n)?).into_owned();
|
||||
Value::Float(text.trim().parse().map_err(|_| "bad float")?)
|
||||
}
|
||||
b'u' | b't' | b'a' | b'A' | b's' => {
|
||||
let n = self.len(false)?;
|
||||
self.str(n)?
|
||||
}
|
||||
b'z' | b'Z' => {
|
||||
let n = self.len(true)?;
|
||||
self.str(n)?
|
||||
}
|
||||
c @ (b'(' | b')' | b'[' | b'<' | b'>') => {
|
||||
let n = self.len(c == b')')?;
|
||||
let mut items = Vec::with_capacity(n.min(1024));
|
||||
for _ in 0..n {
|
||||
items.push(self.read(depth + 1)?);
|
||||
}
|
||||
Value::Seq(items.into())
|
||||
}
|
||||
b'{' => {
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
if self.data.get(self.pos) == Some(&b'0') {
|
||||
self.pos += 1;
|
||||
break;
|
||||
}
|
||||
let k = self.read(depth + 1)?;
|
||||
let v = self.read(depth + 1)?;
|
||||
items.push((k, v));
|
||||
}
|
||||
// pstats never refers back to a dict, so its slot stays empty instead of
|
||||
// holding a copy of the whole table.
|
||||
return Ok(Value::Dict(items));
|
||||
}
|
||||
b'r' => {
|
||||
let i = usize::try_from(self.i32()?).map_err(|_| "bad reference")?;
|
||||
self.refs.get(i).cloned().ok_or("bad reference")?
|
||||
}
|
||||
other => return Err(format!("unexpected marshal type {:?}", other as char)),
|
||||
};
|
||||
if let Some(s) = slot {
|
||||
self.refs[s] = value.clone();
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// `(file, line, name)` as cProfile records it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct Func {
|
||||
file: Rc<str>,
|
||||
line: u32,
|
||||
name: Rc<str>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Stat {
|
||||
cc: f64,
|
||||
nc: f64,
|
||||
tt: f64,
|
||||
ct: f64,
|
||||
}
|
||||
|
||||
struct Edge {
|
||||
caller: usize,
|
||||
callee: usize,
|
||||
nc: f64,
|
||||
cc: f64,
|
||||
tt: f64,
|
||||
ct: f64,
|
||||
}
|
||||
|
||||
fn func(key: &Value) -> Result<Func, String> {
|
||||
match key {
|
||||
Value::Seq(t) if t.len() == 3 => match (&t[0], t[1].num(), &t[2]) {
|
||||
(Value::Str(file), Some(line), Value::Str(name)) => {
|
||||
Ok(Func { file: file.clone(), line: line.max(0.0) as u32, name: name.clone() })
|
||||
}
|
||||
_ => Err("a function key is not (file, line, name)".into()),
|
||||
},
|
||||
_ => Err("a function key is not (file, line, name)".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Functions, their stats (same index) and caller edges.
|
||||
type Graph = (Vec<Func>, Vec<Stat>, Vec<Edge>);
|
||||
|
||||
/// Every function and caller edge of a pstats file.
|
||||
fn parse(bytes: &[u8]) -> Result<Graph, String> {
|
||||
let mut r = Reader { data: bytes, pos: 0, refs: Vec::new() };
|
||||
let Value::Dict(table) = r.read(0)? else { return Err("not a dict".into()) };
|
||||
let mut funcs: Vec<Func> = Vec::new();
|
||||
let mut ids: HashMap<Func, usize> = HashMap::new();
|
||||
let mut id = |f: Func, funcs: &mut Vec<Func>| {
|
||||
*ids.entry(f.clone()).or_insert_with(|| {
|
||||
funcs.push(f);
|
||||
funcs.len() - 1
|
||||
})
|
||||
};
|
||||
let mut stats: Vec<Stat> = Vec::new();
|
||||
let mut edges = Vec::new();
|
||||
for (key, value) in &table {
|
||||
let callee = id(func(key)?, &mut funcs);
|
||||
let Value::Seq(v) = value else { return Err("a function's stats are not a tuple".into()) };
|
||||
let n = |i: usize| v.get(i).and_then(Value::num).ok_or("a function's stats are not numbers");
|
||||
stats.resize_with(funcs.len(), Stat::default);
|
||||
stats[callee] = Stat { cc: n(0)?, nc: n(1)?, tt: n(2)?, ct: n(3)? };
|
||||
let Some(Value::Dict(callers)) = v.get(4) else { return Err("a function has no callers table".into()) };
|
||||
// References can make one callers table count for many functions: a small file could
|
||||
// otherwise unfold into more edges than memory holds. A real edge takes bytes of its own.
|
||||
if edges.len() + callers.len() > bytes.len() {
|
||||
return Err("more calls than the file can hold".into());
|
||||
}
|
||||
for (caller, e) in callers {
|
||||
let caller = id(func(caller)?, &mut funcs);
|
||||
let edge = match e {
|
||||
Value::Seq(t) => {
|
||||
let n = |i: usize| t.get(i).and_then(Value::num).ok_or("a caller's stats are not numbers");
|
||||
Edge { caller, callee, nc: n(0)?, cc: n(1)?, tt: n(2)?, ct: n(3)? }
|
||||
}
|
||||
// `profile` keeps only the call count.
|
||||
other => {
|
||||
let nc = other.num().ok_or("a caller's stats are not numbers")?;
|
||||
Edge { caller, callee, nc, cc: nc, tt: 0.0, ct: 0.0 }
|
||||
}
|
||||
};
|
||||
edges.push(edge);
|
||||
}
|
||||
}
|
||||
stats.resize_with(funcs.len(), Stat::default);
|
||||
Ok((funcs, stats, edges))
|
||||
}
|
||||
|
||||
/// Where a recorded file is here: absolute, or relative to `bases` (the profile was
|
||||
/// written with the run's working directory, which isn't recorded). `None` for
|
||||
/// built-ins (`~`), `<frozen …>` / `<string>` and files that aren't on this machine.
|
||||
fn source(file: &str, bases: &[&Path]) -> Option<PathBuf> {
|
||||
let p = Path::new(file);
|
||||
if file == "~" || file.starts_with('<') {
|
||||
return None;
|
||||
}
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
bases.iter().map(|b| b.join(p)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Where the rebuilt call tree starts, with the time spent there outside any recorded
|
||||
/// caller. One start per strongly connected component of the call graph: a function that
|
||||
/// calls back into itself through others (`exec` running an imported module, which runs
|
||||
/// `exec`) has callers, yet they all run inside it. The component's heaviest function
|
||||
/// stands for it, with its total minus what callers outside the component spent in it.
|
||||
fn roots(stats: &[Stat], edges: &[Edge], callees: &[Vec<(usize, f64)>], min: f64) -> Vec<(usize, f64)> {
|
||||
let comp = components(callees);
|
||||
let count = comp.iter().max().map_or(0, |m| m + 1);
|
||||
let mut incoming = vec![0.0; count];
|
||||
for e in edges {
|
||||
if comp[e.caller] != comp[e.callee] {
|
||||
incoming[comp[e.callee]] += e.ct;
|
||||
}
|
||||
}
|
||||
let mut top: Vec<Option<usize>> = vec![None; count];
|
||||
for (f, c) in comp.iter().enumerate() {
|
||||
if top[*c].is_none_or(|t| stats[f].ct > stats[t].ct) {
|
||||
top[*c] = Some(f);
|
||||
}
|
||||
}
|
||||
let mut out: Vec<(usize, f64)> = top
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(c, t)| {
|
||||
let t = (*t)?;
|
||||
let w = stats[t].ct - incoming[c];
|
||||
(w > min).then_some((t, w))
|
||||
})
|
||||
.collect();
|
||||
if out.is_empty()
|
||||
&& let Some(f) = (0..stats.len()).max_by(|a, b| stats[*a].ct.total_cmp(&stats[*b].ct))
|
||||
{
|
||||
out.push((f, stats[f].ct));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The strongly connected component of every function (Tarjan's algorithm, iterative).
|
||||
fn components(callees: &[Vec<(usize, f64)>]) -> Vec<usize> {
|
||||
const UNSEEN: usize = usize::MAX;
|
||||
let n = callees.len();
|
||||
let (mut index, mut low, mut comp, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![UNSEEN; n], vec![false; n]);
|
||||
let (mut stack, mut next, mut count) = (Vec::new(), 0, 0);
|
||||
for start in 0..n {
|
||||
if index[start] != UNSEEN {
|
||||
continue;
|
||||
}
|
||||
let mut work = vec![(start, 0usize)];
|
||||
(index[start], low[start], on_stack[start]) = (next, next, true);
|
||||
stack.push(start);
|
||||
next += 1;
|
||||
while let Some(&(v, i)) = work.last() {
|
||||
if let Some(&(w, _)) = callees[v].get(i) {
|
||||
work.last_mut().unwrap().1 += 1;
|
||||
if index[w] == UNSEEN {
|
||||
(index[w], low[w], on_stack[w]) = (next, next, true);
|
||||
stack.push(w);
|
||||
next += 1;
|
||||
work.push((w, 0));
|
||||
} else if on_stack[w] {
|
||||
low[v] = low[v].min(index[w]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
work.pop();
|
||||
if let Some(&(p, _)) = work.last() {
|
||||
low[p] = low[p].min(low[v]);
|
||||
}
|
||||
if low[v] == index[v] {
|
||||
while let Some(w) = stack.pop() {
|
||||
on_stack[w] = false;
|
||||
comp[w] = count;
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
comp
|
||||
}
|
||||
|
||||
/// Smallest share of the total a rebuilt call-tree node keeps, and the most nodes the
|
||||
/// tree may have: a call graph with many paths would otherwise unfold exponentially.
|
||||
const MIN_SHARE: f64 = 0.0005;
|
||||
const MAX_NODES: usize = 200_000;
|
||||
const MAX_DEPTH_TREE: u32 = 256;
|
||||
|
||||
/// Reads a pstats file. Times become milliseconds. The method list and call edges are
|
||||
/// exact; the call tree is rebuilt from the edges by sharing each function's time among
|
||||
/// its callees in proportion, so it is an estimate below the first level.
|
||||
pub(crate) fn read(bytes: &[u8], bases: &[&Path], profiler: &str) -> Result<Profile, String> {
|
||||
let (funcs, stats, edges) = parse(bytes)?;
|
||||
let mut b = TreeBuilder::new();
|
||||
// Functions share files: look each one up once.
|
||||
let mut sources: HashMap<Rc<str>, Option<PathBuf>> = HashMap::new();
|
||||
let frames: Vec<u32> = funcs
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let file = sources.entry(f.file.clone()).or_insert_with(|| source(&f.file, bases)).clone();
|
||||
let name = if &*f.file == "~" || file.is_some() {
|
||||
f.name.to_string()
|
||||
} else {
|
||||
// Keep functions of files that aren't here apart, and say where they were.
|
||||
format!("{} ({}:{})", f.name, f.file, f.line)
|
||||
};
|
||||
let line = file.as_ref().map(|_| f.line.saturating_sub(1));
|
||||
b.frame(FrameKey { name, file, line, kind: Default::default() })
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut callees: Vec<Vec<(usize, f64)>> = vec![Vec::new(); funcs.len()];
|
||||
for e in &edges {
|
||||
callees[e.caller].push((e.callee, e.ct));
|
||||
}
|
||||
let min = stats.iter().map(|s| s.tt).sum::<f64>() * MIN_SHARE;
|
||||
// `profile` records no time per caller: without it only own times can be drawn.
|
||||
let timed = edges.iter().any(|e| e.ct > 0.0);
|
||||
let roots = if timed { roots(&stats, &edges, &callees, min) } else { Vec::new() };
|
||||
if !timed {
|
||||
for (f, s) in stats.iter().enumerate() {
|
||||
let node = b.child(0, frames[f]);
|
||||
b.add_self(node, s.tt * 1000.0);
|
||||
}
|
||||
}
|
||||
|
||||
enum Step {
|
||||
Enter { parent: u32, func: usize, weight: f64, depth: u32 },
|
||||
Exit(usize),
|
||||
}
|
||||
let mut on_path = vec![false; funcs.len()];
|
||||
let mut stack: Vec<Step> =
|
||||
roots.iter().map(|&(f, weight)| Step::Enter { parent: 0, func: f, weight, depth: 0 }).collect();
|
||||
while let Some(step) = stack.pop() {
|
||||
let (parent, func, weight, depth) = match step {
|
||||
Step::Exit(f) => {
|
||||
on_path[f] = false;
|
||||
continue;
|
||||
}
|
||||
Step::Enter { parent, func, weight, depth } => (parent, func, weight, depth),
|
||||
};
|
||||
let node = b.child(parent, frames[func]);
|
||||
if b.len() >= MAX_NODES || depth >= MAX_DEPTH_TREE {
|
||||
b.add_self(node, weight * 1000.0);
|
||||
continue;
|
||||
}
|
||||
on_path[func] = true;
|
||||
stack.push(Step::Exit(func));
|
||||
let ct = stats[func].ct;
|
||||
let scale = if ct > 0.0 { weight / ct } else { 0.0 };
|
||||
// A recursive call's time is already in the outer call's.
|
||||
let kids: Vec<(usize, f64)> =
|
||||
callees[func].iter().filter(|(c, _)| !on_path[*c]).map(|&(c, ect)| (c, ect * scale)).collect();
|
||||
let sum: f64 = kids.iter().map(|k| k.1).sum();
|
||||
// Mutual recursion can make the callees add up to more than the caller.
|
||||
let fit = if sum > weight && sum > 0.0 { weight / sum } else { 1.0 };
|
||||
let mut kept = 0.0;
|
||||
for (c, w) in kids {
|
||||
let w = w * fit;
|
||||
if w >= min && w > 0.0 {
|
||||
kept += w;
|
||||
stack.push(Step::Enter { parent: node, func: c, weight: w, depth: depth + 1 });
|
||||
}
|
||||
}
|
||||
b.add_self(node, (weight - kept).max(0.0) * 1000.0);
|
||||
}
|
||||
|
||||
let mut profile = b.finish(profiler, "ms", ProfileMode::Cpu);
|
||||
// Two recorded names of one file (`work.py`, `/p/work.py`) are one frame: add them up.
|
||||
let mut methods: HashMap<u32, MethodStat> = HashMap::new();
|
||||
for (f, s) in stats.iter().enumerate().filter(|(_, s)| s.nc > 0.0 || s.ct > 0.0) {
|
||||
let m = methods.entry(frames[f]).or_insert(MethodStat {
|
||||
frame: frames[f],
|
||||
self_weight: 0.0,
|
||||
total: 0.0,
|
||||
calls: Some(0.0),
|
||||
primitive_calls: Some(0.0),
|
||||
});
|
||||
m.self_weight += s.tt * 1000.0;
|
||||
m.total += s.ct * 1000.0;
|
||||
m.calls = m.calls.map(|c| c + s.nc);
|
||||
m.primitive_calls = m.primitive_calls.map(|c| c + s.cc);
|
||||
}
|
||||
profile.methods = methods.into_values().collect();
|
||||
profile.methods.sort_by(|a, b| {
|
||||
b.self_weight.total_cmp(&a.self_weight).then(b.total.total_cmp(&a.total)).then(a.frame.cmp(&b.frame))
|
||||
});
|
||||
let mut calls: HashMap<(u32, u32), CallEdge> = HashMap::new();
|
||||
for e in &edges {
|
||||
let (caller, callee) = (frames[e.caller], frames[e.callee]);
|
||||
let c = calls.entry((caller, callee)).or_insert(CallEdge {
|
||||
caller,
|
||||
callee,
|
||||
self_weight: 0.0,
|
||||
total: 0.0,
|
||||
calls: 0.0,
|
||||
primitive_calls: 0.0,
|
||||
});
|
||||
c.self_weight += e.tt * 1000.0;
|
||||
c.total += e.ct * 1000.0;
|
||||
c.calls += e.nc;
|
||||
c.primitive_calls += e.cc;
|
||||
}
|
||||
profile.calls = calls.into_values().collect();
|
||||
profile.calls.sort_by_key(|c| (c.caller, c.callee));
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A tiny marshal writer for the shapes pstats uses (format 4: refs, short tuples and strings).
|
||||
#[derive(Default)]
|
||||
struct W(Vec<u8>);
|
||||
impl W {
|
||||
fn s(&mut self, v: &str) -> &mut Self {
|
||||
self.0.push(b'z');
|
||||
self.0.push(v.len() as u8);
|
||||
self.0.extend(v.as_bytes());
|
||||
self
|
||||
}
|
||||
fn i(&mut self, v: i32) -> &mut Self {
|
||||
self.0.push(b'i');
|
||||
self.0.extend(v.to_le_bytes());
|
||||
self
|
||||
}
|
||||
fn g(&mut self, v: f64) -> &mut Self {
|
||||
self.0.push(b'g');
|
||||
self.0.extend(v.to_le_bytes());
|
||||
self
|
||||
}
|
||||
fn tuple(&mut self, n: u8) -> &mut Self {
|
||||
self.0.extend([b')', n]);
|
||||
self
|
||||
}
|
||||
fn key(&mut self, (file, line, name): (&str, i32, &str)) -> &mut Self {
|
||||
self.tuple(3).s(file).i(line).s(name)
|
||||
}
|
||||
}
|
||||
|
||||
type Key<'a> = (&'a str, i32, &'a str);
|
||||
/// `(caller, nc, cc, tt, ct)`.
|
||||
type CallerRow<'a> = (Key<'a>, i32, i32, f64, f64);
|
||||
/// `(func, cc, nc, tt, ct, callers)`.
|
||||
type Row<'a> = (Key<'a>, i32, i32, f64, f64, &'a [CallerRow<'a>]);
|
||||
|
||||
/// `rows` as a pstats file.
|
||||
fn pstats(rows: &[Row]) -> Vec<u8> {
|
||||
let mut w = W::default();
|
||||
w.0.push(b'{');
|
||||
for (f, cc, nc, tt, ct, callers) in rows {
|
||||
w.key(*f).tuple(5).i(*cc).i(*nc).g(*tt).g(*ct);
|
||||
w.0.push(b'{');
|
||||
for (c, nc, cc, tt, ct) in *callers {
|
||||
w.key(*c).tuple(4).i(*nc).i(*cc).g(*tt).g(*ct);
|
||||
}
|
||||
w.0.push(b'0');
|
||||
}
|
||||
w.0.push(b'0');
|
||||
w.0
|
||||
}
|
||||
|
||||
fn name(p: &Profile, frame: u32) -> &str {
|
||||
&p.frames[frame as usize].name
|
||||
}
|
||||
|
||||
fn method<'a>(p: &'a Profile, n: &str) -> &'a MethodStat {
|
||||
p.methods.iter().find(|m| name(p, m.frame).starts_with(n)).unwrap()
|
||||
}
|
||||
|
||||
const EXEC: Key = ("~", 0, "<built-in method builtins.exec>");
|
||||
|
||||
#[test]
|
||||
fn reads_a_file_written_by_cprofile() {
|
||||
// `python -m cProfile -o out.prof work.py` (3.14), trimmed: refs, interned strings.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("work.py"), "").unwrap();
|
||||
let bytes = pstats(&[
|
||||
(EXEC, 1, 1, 0.000_01, 0.004, &[]),
|
||||
(("work.py", 1, "<module>"), 1, 1, 0.000_002, 0.0039, &[(EXEC, 1, 1, 0.000_002, 0.0039)]),
|
||||
(("work.py", 6, "main"), 1, 1, 0.000_002, 0.0038, &[(("work.py", 1, "<module>"), 1, 1, 0.000_002, 0.0038)]),
|
||||
(
|
||||
("work.py", 1, "fib"),
|
||||
1,
|
||||
8361,
|
||||
0.002,
|
||||
0.002,
|
||||
&[(("work.py", 1, "fib"), 8360, 2, 0.0019, 0.002), (("work.py", 6, "main"), 1, 1, 0.000_001, 0.002)],
|
||||
),
|
||||
(
|
||||
("/ci/runner/lib.py", 3, "helper"),
|
||||
2,
|
||||
2,
|
||||
0.0018,
|
||||
0.0018,
|
||||
&[(("work.py", 6, "main"), 2, 2, 0.0018, 0.0018)],
|
||||
),
|
||||
]);
|
||||
assert!(looks_like_pstats(&bytes));
|
||||
let p = read(&bytes, &[dir.path()], "cProfile").unwrap();
|
||||
assert_eq!((p.unit.as_str(), p.profiler.as_str()), ("ms", "cProfile"));
|
||||
assert!((p.total - 4.0).abs() < 1e-9, "{}", p.total);
|
||||
|
||||
// Recursion: 8361 calls, 1 primitive; own and total time as recorded.
|
||||
let fib = method(&p, "fib");
|
||||
assert_eq!((fib.calls, fib.primitive_calls), (Some(8361.0), Some(1.0)));
|
||||
assert!((fib.self_weight - 2.0).abs() < 1e-9 && (fib.total - 2.0).abs() < 1e-9);
|
||||
let frame = &p.frames[fib.frame as usize];
|
||||
assert_eq!(frame.file.as_deref(), Some(dir.path().join("work.py").as_path()));
|
||||
assert_eq!(frame.line, Some(0));
|
||||
|
||||
// A file that isn't here keeps its recorded location in the name, without a link.
|
||||
let helper = &p.frames[method(&p, "helper").frame as usize];
|
||||
assert_eq!((helper.name.as_str(), helper.file.as_ref()), ("helper (/ci/runner/lib.py:3)", None));
|
||||
assert_eq!(name(&p, method(&p, "<built-in").frame), "<built-in method builtins.exec>");
|
||||
|
||||
// Exact edges, including the recursive one.
|
||||
let edge = |caller: &str, callee: &str| {
|
||||
p.calls.iter().find(|e| name(&p, e.caller).starts_with(caller) && name(&p, e.callee).starts_with(callee))
|
||||
};
|
||||
assert_eq!(edge("fib", "fib").map(|e| (e.calls, e.primitive_calls)), Some((8360.0, 2.0)));
|
||||
assert_eq!(edge("main", "helper").map(|e| e.calls), Some(2.0));
|
||||
|
||||
// The tree: exec → <module> → main → {fib, helper}; fib's self-call is not unfolded.
|
||||
let path = |names: &[&str]| {
|
||||
let mut node = 0usize;
|
||||
for n in names {
|
||||
node = *p.nodes[node]
|
||||
.children
|
||||
.iter()
|
||||
.find(|c| name(&p, p.nodes[**c as usize].frame).starts_with(n))
|
||||
.unwrap_or_else(|| panic!("no {n}")) as usize;
|
||||
}
|
||||
&p.nodes[node]
|
||||
};
|
||||
let fib_node = path(&["<built-in", "<module>", "main", "fib"]);
|
||||
assert!(fib_node.children.is_empty());
|
||||
assert!((fib_node.total - 2.0).abs() < 1e-9);
|
||||
assert!((path(&["<built-in", "<module>", "main"]).total - 3.8).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_cpythons_own_output() {
|
||||
// `python3.14 -m cProfile -o fib.prof work.py`: interned strings, refs, short tuples.
|
||||
let p = read(include_bytes!("../testdata/fib.prof"), &[], "cProfile").unwrap();
|
||||
let fib = method(&p, "fib");
|
||||
assert_eq!((fib.calls, fib.primitive_calls), (Some(8361.0), Some(1.0)));
|
||||
assert_eq!(name(&p, fib.frame), "fib (work.py:1)");
|
||||
assert!(p.methods.iter().any(|m| name(&p, m.frame) == "<method 'disable' of '_lsprof.Profiler' objects>"));
|
||||
let module = method(&p, "<module>");
|
||||
assert!(p.total >= module.total && module.total > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_callee_splits_its_time_by_caller() {
|
||||
// a and b both call leaf; leaf spends 4 ms for a and 1 ms for b.
|
||||
let bytes = pstats(&[
|
||||
(("m.py", 1, "a"), 1, 1, 0.0, 0.004, &[]),
|
||||
(("m.py", 2, "b"), 1, 1, 0.0, 0.001, &[]),
|
||||
(
|
||||
("m.py", 3, "leaf"),
|
||||
5,
|
||||
5,
|
||||
0.005,
|
||||
0.005,
|
||||
&[(("m.py", 1, "a"), 4, 4, 0.004, 0.004), (("m.py", 2, "b"), 1, 1, 0.001, 0.001)],
|
||||
),
|
||||
]);
|
||||
let p = read(&bytes, &[], "cProfile").unwrap();
|
||||
let under = |n: &str| {
|
||||
let root =
|
||||
p.nodes[0].children.iter().find(|c| name(&p, p.nodes[**c as usize].frame).starts_with(n)).unwrap();
|
||||
p.nodes[p.nodes[*root as usize].children[0] as usize].total
|
||||
};
|
||||
assert!((under("a ") - 4.0).abs() < 1e-9 && (under("b ") - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_that_calls_back_into_itself_through_others_is_still_the_root() {
|
||||
// exec runs the script, whose import runs exec again: exec has a caller, inside itself.
|
||||
let import: Key = ("<frozen importlib._bootstrap>", 1, "_call_with_frames_removed");
|
||||
let bytes = pstats(&[
|
||||
(EXEC, 2, 3, 0.0, 0.010, &[(import, 1, 1, 0.0, 0.003)]),
|
||||
(("main.py", 1, "<module>"), 1, 1, 0.006, 0.010, &[(EXEC, 1, 1, 0.006, 0.010)]),
|
||||
(import, 1, 1, 0.0, 0.004, &[(("main.py", 1, "<module>"), 1, 1, 0.0, 0.004)]),
|
||||
(("~", 0, "<method 'disable' of '_lsprof.Profiler' objects>"), 1, 1, 0.000_001, 0.000_001, &[]),
|
||||
]);
|
||||
let p = read(&bytes, &[], "cProfile").unwrap();
|
||||
let roots: Vec<&str> = p.nodes[0].children.iter().map(|c| name(&p, p.nodes[*c as usize].frame)).collect();
|
||||
assert_eq!(roots, ["<built-in method builtins.exec>"], "disable is below the share kept");
|
||||
assert!((p.total - 10.0).abs() < 1e-9, "{}", p.total);
|
||||
let exec = &p.nodes[p.nodes[0].children[0] as usize];
|
||||
assert_eq!(name(&p, p.nodes[exec.children[0] as usize].frame), "<module> (main.py:1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_times_per_caller_the_tree_is_flat() {
|
||||
let mut w = W::default();
|
||||
w.0.push(b'{');
|
||||
w.key(("m.py", 1, "f")).tuple(5).i(1).i(1).g(0.002).g(0.003);
|
||||
w.0.push(b'{');
|
||||
w.key(("m.py", 9, "g")).i(1);
|
||||
w.0.push(b'0');
|
||||
w.key(("m.py", 9, "g")).tuple(5).i(1).i(1).g(0.001).g(0.003);
|
||||
w.0.extend(b"{00");
|
||||
let p = read(&w.0, &[], "profile").unwrap();
|
||||
assert_eq!(p.nodes[0].children.len(), 2);
|
||||
assert!((p.total - 3.0).abs() < 1e-9, "{}", p.total);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dense_call_graph_stays_bounded() {
|
||||
// f0 → f1 → … with every fi also calling every fj (j > i): exponentially many paths.
|
||||
let n = 60;
|
||||
let keys: Vec<String> = (0..n).map(|i| format!("f{i}")).collect();
|
||||
let mut rows = Vec::new();
|
||||
let callers: Vec<Vec<CallerRow>> =
|
||||
(0..n).map(|j| (0..j).map(|i| (("m.py", i as i32, keys[i].as_str()), 1, 1, 0.0, 1.0)).collect()).collect();
|
||||
for j in 0..n {
|
||||
rows.push((("m.py", j as i32, keys[j].as_str()), 1, 1, 0.001, 1.0, callers[j].as_slice()));
|
||||
}
|
||||
let p = read(&pstats(&rows), &[], "cProfile").unwrap();
|
||||
assert!(p.nodes.len() <= MAX_NODES + 1, "{}", p.nodes.len());
|
||||
assert_eq!(p.methods.len(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_module_caller_counts_and_long_ints() {
|
||||
let mut w = W::default();
|
||||
w.0.push(b'{');
|
||||
w.key(("m.py", 1, "f")).tuple(5).i(1);
|
||||
// 2**31 calls as a marshal long: digits 0, 0, 2 (15 bits each).
|
||||
w.0.extend([b'l', 3, 0, 0, 0, 0, 0, 0, 0, 2, 0]);
|
||||
w.g(0.5).g(0.5);
|
||||
w.0.push(b'{');
|
||||
w.key(("m.py", 9, "g")).i(7);
|
||||
w.0.extend(b"00");
|
||||
let p = read(&w.0, &[], "profile").unwrap();
|
||||
let f = method(&p, "f");
|
||||
assert_eq!(f.calls, Some(2f64.powi(31)));
|
||||
assert_eq!(p.calls.iter().map(|e| e.calls).collect::<Vec<_>>(), [7.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callers_table_referenced_by_many_functions_is_refused() {
|
||||
// 2,000 functions share one stats tuple (by reference) whose callers table has 200
|
||||
// entries: a 60 KB file that would unfold into 400,000 edges.
|
||||
let mut w = W::default();
|
||||
w.0.push(b'{');
|
||||
w.key(("m.py", 0, "f0"));
|
||||
w.0.push(b')' | 0x80);
|
||||
w.0.push(5);
|
||||
w.i(1).i(1).g(0.0).g(0.0);
|
||||
w.0.push(b'{');
|
||||
for i in 0..200 {
|
||||
w.key(("m.py", i, "c")).i(1);
|
||||
}
|
||||
w.0.push(b'0');
|
||||
// The tuple is the first object marked for reference: number 0.
|
||||
for i in 1..2_000 {
|
||||
w.key(("m.py", i, "f"));
|
||||
w.0.push(b'r');
|
||||
w.0.extend(0i32.to_le_bytes());
|
||||
}
|
||||
w.0.push(b'0');
|
||||
let err = read(&w.0, &[], "cProfile").unwrap_err();
|
||||
assert!(err.contains("more calls than the file can hold"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_names_of_one_file_are_one_method() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("work.py");
|
||||
std::fs::write(&file, "").unwrap();
|
||||
let abs = file.to_string_lossy().into_owned();
|
||||
let bytes = pstats(&[
|
||||
(("work.py", 1, "f"), 1, 1, 0.001, 0.001, &[(EXEC, 1, 1, 0.001, 0.001)]),
|
||||
((abs.as_str(), 1, "f"), 2, 2, 0.002, 0.002, &[(EXEC, 2, 2, 0.002, 0.002)]),
|
||||
(EXEC, 1, 1, 0.0, 0.003, &[]),
|
||||
]);
|
||||
let p = read(&bytes, &[dir.path()], "cProfile").unwrap();
|
||||
let f: Vec<_> = p.methods.iter().filter(|m| name(&p, m.frame) == "f").collect();
|
||||
assert_eq!(f.len(), 1);
|
||||
assert_eq!((f[0].calls, f[0].primitive_calls), (Some(3.0), Some(3.0)));
|
||||
assert!((f[0].total - 3.0).abs() < 1e-9);
|
||||
assert_eq!(p.calls.iter().filter(|e| name(&p, e.callee) == "f").map(|e| e.calls).collect::<Vec<_>>(), [3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_an_error_not_a_panic() {
|
||||
for bytes in [&b"{)"[..], b"{)\x03z\xff", b"{\xff", b"{)\x03z\x01~i\x00\x00\x00\x00r\xff\xff\xff\x7f"] {
|
||||
assert!(read(bytes, &[], "cProfile").is_err(), "{bytes:?}");
|
||||
}
|
||||
assert!(!looks_like_pstats(br#"{"nodes":[]}"#));
|
||||
assert!(looks_like_pstats(b"\xfb)\x03"));
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,11 @@ impl TreeBuilder {
|
||||
self.add_self(node, weight);
|
||||
}
|
||||
|
||||
/// Nodes so far, the root included.
|
||||
pub fn len(&self) -> usize {
|
||||
self.nodes.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.len() <= 1 && self.nodes[0].self_weight == 0.0
|
||||
}
|
||||
@@ -121,7 +126,16 @@ impl TreeBuilder {
|
||||
.map(|k| ProfileFrame { name: k.name, file: k.file.map(Into::into), line: k.line, kind: k.kind })
|
||||
.collect();
|
||||
let methods = methods(&nodes, frames.len());
|
||||
Profile { profiler: profiler.to_owned(), unit: unit.to_owned(), mode, total: totals[0], frames, nodes, methods }
|
||||
Profile {
|
||||
profiler: profiler.to_owned(),
|
||||
unit: unit.to_owned(),
|
||||
mode,
|
||||
total: totals[0],
|
||||
frames,
|
||||
nodes,
|
||||
methods,
|
||||
calls: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +164,13 @@ fn methods(nodes: &[ProfileNode], frame_count: usize) -> Vec<MethodStat> {
|
||||
let root_frame = nodes.first().map(|n| n.frame as usize);
|
||||
let mut out: Vec<MethodStat> = (0..frame_count)
|
||||
.filter(|f| Some(*f) != root_frame && total_w[*f] > 0.0)
|
||||
.map(|f| MethodStat { frame: f as u32, self_weight: self_w[f], total: total_w[f] })
|
||||
.map(|f| MethodStat {
|
||||
frame: f as u32,
|
||||
self_weight: self_w[f],
|
||||
total: total_w[f],
|
||||
calls: None,
|
||||
primitive_calls: None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.self_weight.total_cmp(&a.self_weight).then(b.total.total_cmp(&a.total)));
|
||||
out
|
||||
|
||||
BIN
Бінарний файл не відображається.
@@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
// Variables go by name (`-e NAME`) so their values stay out of the command line
|
||||
// echoed in the console; the docker CLI reads them from its own environment.
|
||||
let mut env: BTreeMap<String, String> = run.file_env.clone();
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test")
|
||||
&& !command.env.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
env.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
|
||||
@@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) {
|
||||
return true;
|
||||
}
|
||||
if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) {
|
||||
// A `tests` folder alone means pytest unless its tests are the standard library's unittest.
|
||||
if read(&root.join("pyproject.toml"))
|
||||
.is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"]
|
||||
@@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
.any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest")))
|
||||
}
|
||||
|
||||
/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the
|
||||
/// standard library's unittest and none of them pytest.
|
||||
fn uses_unittest(root: &Path) -> bool {
|
||||
let mut found = false;
|
||||
for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] {
|
||||
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
||||
// ponytail: the first 50 modules of each folder decide; enough to tell a project's style.
|
||||
for entry in entries.flatten().take(50) {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("test") || !name.ends_with(".py") {
|
||||
continue;
|
||||
}
|
||||
let Some(text) = read(&entry.path()) else { continue };
|
||||
if text
|
||||
.lines()
|
||||
.any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found |= text.lines().any(|l| {
|
||||
let l = l.trim_start();
|
||||
l.starts_with("import unittest") || l.starts_with("from unittest")
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Python configurations of the project at `root`, a folder of the opened project `top`.
|
||||
fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
|
||||
@@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest");
|
||||
if uses_pytest(root) || own_pytest {
|
||||
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
|
||||
} else if !root.join("manage.py").is_file() && uses_unittest(root) {
|
||||
out.push(
|
||||
py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"])
|
||||
.test(),
|
||||
);
|
||||
}
|
||||
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
|
||||
if root.join("manage.py").is_file() {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! than one place is taken from the first, in that order.
|
||||
//!
|
||||
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
|
||||
//! Application, JAR Application, Spring Boot, Go Application / Go Test, Flutter and compound configurations become the
|
||||
//! Application, JAR Application, Spring Boot, Go Application / Go Test, Flutter, Dockerfile and compound configurations become the
|
||||
//! matching kinds; other types are skipped with their type.
|
||||
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
|
||||
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
|
||||
@@ -169,6 +169,7 @@ const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
|
||||
const GO_APPLICATION: &str = "GoApplicationRunConfiguration";
|
||||
const GO_TEST: &str = "GoTestRunConfiguration";
|
||||
const FLUTTER: &str = "FlutterRunConfigurationType";
|
||||
const DOCKER: &str = "docker-deploy";
|
||||
|
||||
type Res<T> = Result<T, SkipReason>;
|
||||
|
||||
@@ -341,6 +342,8 @@ impl Cx<'_> {
|
||||
DJANGO_SERVER => self.django_server(name, c, &mut ignored)?,
|
||||
DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if factory == "Doctests" => self.doctest(name, c, &mut ignored)?,
|
||||
NPM => self.npm(name, c, &mut ignored)?,
|
||||
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
|
||||
NODE => self.node(name, c, &mut ignored)?,
|
||||
@@ -351,6 +354,7 @@ impl Cx<'_> {
|
||||
GO_APPLICATION => self.go_config(name, c, false, &mut ignored)?,
|
||||
GO_TEST => self.go_config(name, c, true, &mut ignored)?,
|
||||
FLUTTER => self.flutter(name, c)?,
|
||||
DOCKER => self.dockerfile(name, c, &mut ignored)?,
|
||||
COMPOUND => {
|
||||
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
|
||||
config(name, "compound", String::new(), Vec::new(), None)
|
||||
@@ -361,6 +365,40 @@ impl Cx<'_> {
|
||||
Ok(Found { config, members, ignored })
|
||||
}
|
||||
|
||||
/// Keep Docker's form fields; the frontend resolves the server name to a saved connection
|
||||
/// and uses the native Dockerfile type to generate the platform's run and stop commands.
|
||||
fn dockerfile(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let deployment = c.child("deployment").ok_or(SkipReason::NothingToRun)?;
|
||||
if deployment.attr("type") != Some("dockerfile") {
|
||||
return Err(SkipReason::UnsupportedType {
|
||||
type_: format!("{DOCKER} ({})", deployment.attr("type").unwrap_or_default()),
|
||||
});
|
||||
}
|
||||
let settings = deployment.child("settings").ok_or(SkipReason::NothingToRun)?;
|
||||
let file = self.path(settings.option("sourceFilePath"))?.ok_or(SkipReason::NothingToRun)?;
|
||||
let mut rc = config(name, "docker-dockerfile", String::new(), Vec::new(), None);
|
||||
rc.extras.params.extend([
|
||||
("dockerfile".into(), path_from(self.root, file, self.root)),
|
||||
("runImage".into(), "true".into()),
|
||||
("serverName".into(), c.attr("server-name").unwrap_or_default().trim().to_owned()),
|
||||
]);
|
||||
for (from, to) in [("imageTag", "tag"), ("containerName", "containerName")] {
|
||||
if let Some(value) = self.text(settings.option(from))? {
|
||||
rc.extras.params.insert(to.into(), value);
|
||||
}
|
||||
}
|
||||
for option in settings.children_named("option") {
|
||||
if let Some(key) = option.attr("name")
|
||||
&& !matches!(key, "sourceFilePath" | "imageTag" | "containerName")
|
||||
{
|
||||
ignored.push(key.into());
|
||||
}
|
||||
}
|
||||
// The resolved connection ID belongs to this machine, not to the shared project.
|
||||
self.machine_values.set(true);
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// A Go Application (`GoApplicationRunConfiguration`) or Go Test configuration. Both share
|
||||
/// the kind (package / file / directory), the target node, `go_parameters` (go tool
|
||||
/// arguments) and envs; a test adds a `pattern` and program arguments go after `-args`.
|
||||
@@ -667,6 +705,66 @@ impl Cx<'_> {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a
|
||||
/// file as its path, a folder discovered (`discover -s`, with the configuration's pattern).
|
||||
fn unittest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
|
||||
args.extend(["-m".to_owned(), "unittest".to_owned()]);
|
||||
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
|
||||
if let Some(target) = field("_new_target") {
|
||||
let target = self.expand(&target)?;
|
||||
match field("_new_targetType").as_deref() {
|
||||
Some("PYTHON") => args.push(target),
|
||||
Some("CUSTOM") => {}
|
||||
_ => {
|
||||
let path = path_from(self.root, file_url_path(&target), &dir);
|
||||
if path.ends_with(".py") {
|
||||
args.push(path);
|
||||
} else {
|
||||
args.extend(["discover".to_owned(), "-s".to_owned(), path]);
|
||||
if let Some(pattern) = field("_new_pattern") {
|
||||
args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
|
||||
let mut rc = config(name, "unittest", exe, args, Some("debugpy"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
rc.is_test = true;
|
||||
self.python_env(c, &mut rc, ignored)?;
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// PyCharm's Doctests: a file, or a Python target (`shop.money.round_eur`) as the IDE's
|
||||
/// `file::qualname` (the module found on disk like pytest's targets).
|
||||
fn doctest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
|
||||
args.extend(["-m".to_owned(), "doctest".to_owned()]);
|
||||
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
|
||||
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
|
||||
if let Some(target) = field("_new_target") {
|
||||
let target = self.expand(&target)?;
|
||||
match field("_new_targetType").as_deref() {
|
||||
Some("PYTHON") => match self.python_target(&target, &dir) {
|
||||
Some(node) => args.push(match node.split_once("::") {
|
||||
Some((file, rest)) => format!("{file}::{}", rest.replace("::", ".")),
|
||||
None => node,
|
||||
}),
|
||||
None => ignored.push("_new_target".into()),
|
||||
},
|
||||
Some("CUSTOM") => {}
|
||||
_ => args.push(path_from(self.root, file_url_path(&target), &dir)),
|
||||
}
|
||||
}
|
||||
let mut rc = config(name, "doctest", exe, args, Some("debugpy"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
rc.is_test = true;
|
||||
self.python_env(c, &mut rc, ignored)?;
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm
|
||||
/// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`):
|
||||
/// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working
|
||||
|
||||
@@ -311,15 +311,24 @@ impl Cx<'_> {
|
||||
}
|
||||
|
||||
fn python_attach(&self, name: &str, obj: &Map<String, Value>) -> Res<RunConfig> {
|
||||
if obj.contains_key("processId") || obj.contains_key("listen") {
|
||||
if obj.contains_key("processId") {
|
||||
return Err(SkipReason::UnsupportedAttach);
|
||||
}
|
||||
let connect = obj.get("connect").and_then(Value::as_object).unwrap_or(obj);
|
||||
let host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into());
|
||||
// `listen`: the program connects with `debugpy.connect` (Python Debug Server).
|
||||
let (kind, connect) = match obj.get("listen").and_then(Value::as_object) {
|
||||
Some(listen) => ("python-debug-server", listen),
|
||||
None => ("python-remote", obj.get("connect").and_then(Value::as_object).unwrap_or(obj)),
|
||||
};
|
||||
let mut host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into());
|
||||
// VS Code's `listen.host` is where the adapter binds; the configuration names the address the
|
||||
// program connects to, which a wildcard is not: left at localhost for the user to change.
|
||||
if kind == "python-debug-server" && matches!(host.as_str(), "0.0.0.0" | "::" | "[::]") {
|
||||
host = "localhost".into();
|
||||
}
|
||||
let Some(port) = self.string(connect, "port")? else {
|
||||
return Err(SkipReason::UnsupportedAttach);
|
||||
};
|
||||
let mut c = config(name, "python-remote", String::new(), Vec::new(), Some("debugpy"));
|
||||
let mut c = config(name, kind, String::new(), Vec::new(), Some("debugpy"));
|
||||
c.extras.params = BTreeMap::from([("host".into(), host), ("port".into(), port)]);
|
||||
if let Some(Value::Object(m)) = obj.get("pathMappings").and_then(|m| m.get(0)) {
|
||||
self.roots(m, &mut c)?;
|
||||
|
||||
@@ -426,7 +426,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) {
|
||||
@@ -1087,7 +1087,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
|
||||
Loaded 100 of 612 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача