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

..
588 змінених файлів з 3040 додано та 38199 видалено

No files matched your search

-7
Переглянути файл
@@ -11,10 +11,3 @@ package(=ide-clipboard) & (
)
'''
test-group = "windows-clipboard"
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
# timeout.
[[profile.default.overrides]]
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
slow-timeout = { period = "60s", terminate-after = 5 }
+1 -11
Переглянути файл
@@ -150,18 +150,8 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
# working copy's database); with CI set they fail instead of skipping when these are
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
- name: Subversion (macOS)
if: runner.os == 'macOS'
run: command -v svnadmin >/dev/null || brew install subversion
- name: Subversion version
if: runner.os != 'Windows'
shell: bash
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
+1 -2
Переглянути файл
@@ -34,7 +34,6 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
@@ -110,7 +109,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-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|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|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$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|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
+2 -4
Переглянути файл
@@ -284,8 +284,6 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
@@ -293,10 +291,10 @@ jobs:
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
-1
Переглянути файл
@@ -15,7 +15,6 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+1 -4
Переглянути файл
@@ -152,10 +152,7 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
"no-await-in-loop": "error"
}
}
]
Створено
+1 -30
Переглянути файл
@@ -2766,7 +2766,6 @@ dependencies = [
"gix-ignore",
"gix-index",
"gix-lock",
"gix-mailmap",
"gix-note",
"gix-object",
"gix-odb",
@@ -3133,18 +3132,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "gix-mailmap"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
dependencies = [
"bstr",
"gix-actor",
"gix-date",
"gix-error",
]
[[package]]
name = "gix-note"
version = "0.3.1"
@@ -4186,12 +4173,12 @@ dependencies = [
"serde_json",
"sha1 0.10.7",
"specta",
"sqlx",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"tracing",
"uuid",
"which",
]
[[package]]
@@ -4526,7 +4513,6 @@ dependencies = [
"ide-spell",
"ide-ssh",
"ide-streams",
"ide-svn",
"ide-syntax",
"ide-terminal",
"ide-text",
@@ -4985,21 +4971,6 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "ide-svn"
version = "0.1.56"
dependencies = [
"dunce",
"encoding_rs",
"ide-core",
"ide-vcs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"tempfile",
"which",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-syntax"
version = "0.1.56"
-1
Переглянути файл
@@ -24,7 +24,6 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-svn = { path = "crates/ide-svn" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
-5
Переглянути файл
@@ -6,11 +6,6 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
Copyright 2000-2026 JetBrains s.r.o. and contributors.
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
their names and file contents from IntelliJ's svn4idea TreeConflictData
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
2000-2026 JetBrains s.r.o. and contributors.
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
Corporation, licensed under the MIT License.
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
## Community
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
## Topluluk
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
## 社区
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
+1 -1
Переглянути файл
@@ -18,7 +18,6 @@ ide-tools = { path = "../ide-tools" }
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
tracing.workspace = true
@@ -26,6 +25,7 @@ parking_lot.workspace = true
dunce.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
+1 -3
Переглянути файл
@@ -58,9 +58,7 @@ impl AgentManager {
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
+3 -397
Переглянути файл
@@ -2,10 +2,9 @@
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
//! `<home>/.codex/session_index.jsonl`), and Copilot
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
//! `<home>/.codex/session_index.jsonl`).
use super::native::claude::history;
use serde::Serialize;
@@ -18,7 +17,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
@@ -27,9 +26,6 @@ pub struct ExternalSession {
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
/// apps write the same session, so forking a copy is the safe choice.
pub in_use: bool,
}
/// Modification time of `path` in ms, else 0.
@@ -127,7 +123,6 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -198,7 +193,6 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -252,289 +246,6 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
fn is_yaml_block_header(raw: &str) -> bool {
let mut chars = raw.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
}
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
fn parse_yaml_inline_value(raw: &str) -> String {
if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
}
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
let mut metadata = HashMap::new();
while let Some(line) = lines.next() {
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
continue;
}
let Some((key, raw)) = line.split_once(':') else { continue };
let key = key.trim();
let raw = raw.trim();
if key.is_empty() {
continue;
}
if is_yaml_block_header(raw) {
let folded = raw.starts_with('>');
let mut block = Vec::new();
while let Some(next) = lines.peek() {
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
block.push(lines.next().unwrap_or_default());
} else {
break;
}
}
while block.last().is_some_and(|l| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
.min()
.unwrap_or(0);
let sep = if folded { " " } else { "\n" };
let joined = block
.iter()
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
.collect::<Vec<_>>()
.join(sep);
if !joined.trim().is_empty() {
metadata.insert(key.to_owned(), joined);
}
} else if !raw.is_empty() {
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
}
}
(!metadata.is_empty()).then_some(metadata)
}
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
fn copilot_prompt(path: &Path) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
std::io::BufReader::new(file)
.lines()
.take(400)
.filter_map(|line| line.ok())
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
.find_map(|event| {
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
.flatten()
.filter(|text| !text.is_empty())
.map(short)
})
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
use sqlx::{Connection, Row};
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.create_if_missing(false)
.busy_timeout(std::time::Duration::from_millis(200));
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
Ok(rows) => rows,
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
};
let _ = conn.close().await;
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
let Some(home) = home else { return HashMap::new() };
let dbs = vscode_agent_host_dbs(home);
if dbs.is_empty() {
return HashMap::new();
}
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
// thread works from either without blocking a runtime worker.
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
scope
.spawn(|| {
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
return Vec::new();
};
rt.block_on(async {
let mut all = Vec::new();
for path in &dbs {
all.extend(read_vscode_chat_rows(path).await);
}
all
})
})
.join()
.unwrap_or_default()
});
let mut titles = HashMap::new();
for [pdata, scs_title, scs_source, metadata, payload] in rows {
let Some(pdata) = pdata else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
continue;
};
if let Some(title) =
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
{
titles.insert(sdk_id.to_owned(), title);
}
}
titles
}
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
/// so only a lock whose process still runs counts.
fn copilot_session_in_use(dir: &Path) -> bool {
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("inuse."))
.and_then(|n| n.strip_suffix(".lock"))
.and_then(|n| n.parse::<u32>().ok())
else {
return false;
};
ide_core::process::process_alive(pid)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let dir = entry.path();
let events = dir.join("events.jsonl");
if !events.is_file() {
return None;
}
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
if !in_project(cwd.as_deref(), root) {
return None;
}
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
let title = raw_name
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
let session = ExternalSession {
provider: "copilot".to_owned(),
session_id,
title,
cwd,
updated_ms: mtime(&events),
in_use: copilot_session_in_use(&dir),
};
Some((session, cli_user_named))
})
.collect();
if !pending.is_empty() {
let vscode_titles = vscode_copilot_titles(home);
for (session, cli_user_named) in &mut pending {
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
session.title = short(title);
}
}
}
pending.into_iter().map(|(s, _)| s).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -633,111 +344,6 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
rt.block_on(async {
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
conn.close().await.unwrap();
});
}
#[test]
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
json!({"type": "session.start", "data": {}}),
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
],
);
std::fs::write(
session.join("workspace.yaml"),
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
)
.unwrap();
let block_scalar = copilot_home.join("session-state/copilot-block");
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
block_scalar.join("workspace.yaml"),
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
)
.unwrap();
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
write(
&vscode_renamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
);
std::fs::write(
vscode_renamed.join("workspace.yaml"),
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
)
.unwrap();
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
vscode_placeholder.join("workspace.yaml"),
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
)
.unwrap();
let unnamed = copilot_home.join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
// A live holder marks the session in use; a lock left by a process that exited does not.
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
let empty = copilot_home.join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = copilot_home.join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
exec_sqlite(
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
);
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
assert_eq!(sessions.len(), 5);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert!(named.in_use);
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
let unnamed = by_id.remove("copilot-2").unwrap();
assert_eq!(unnamed.title, "add a regression test");
assert!(!unnamed.in_use);
}
#[test]
+44 -97
Переглянути файл
@@ -1409,23 +1409,19 @@ impl AgentManager {
out.extend(external::claude_sessions(&dir, &root));
}
let home = self.shared.paths.home_dir.clone().or_else(home_dir);
if let Some(home) = home.as_deref() {
if let Some(home) = home {
out.extend(external::codex_sessions(&home.join(".codex"), &root));
}
if let Some(spec) = self.shared.spec("copilot")
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
{
out.extend(external::copilot_sessions(&dir, home.as_deref(), &root));
}
let known = self.imported_session_ids();
out.retain(|s| !known.contains(&s.session_id));
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
out.truncate(50);
out
}
/// Imports an external session as a task, loading it in the background to show its history (#312).
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex" | "copilot") {
if !matches!(provider, "claude" | "codex") {
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
}
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
@@ -1492,21 +1488,9 @@ impl AgentManager {
pending_native_fork: None,
};
let handle = Task::restore(file, self.shared.clone());
let epoch = {
let mut tasks = self.tasks.write();
let epoch = self.shared.shutdown_epoch();
tasks.insert(task.id.clone(), handle.clone());
epoch
};
self.tasks.write().insert(task.id.clone(), handle.clone());
handle.emit_task();
handle.persist();
// Loading the session replays its history into the task, so it shows before a first message.
self.shared.runtime.spawn(async move {
match handle.ensure_session(epoch).await {
Ok(_) => handle.release_when_idle(),
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
}
});
Ok(task)
}
@@ -1514,7 +1498,7 @@ impl AgentManager {
/// recording as the agent's own fork, under an id the host chooses. The session must
/// belong to this project and have been recorded in `cwd`.
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex" | "copilot") {
if !matches!(provider, "claude" | "codex") {
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
}
if !canonical_uuid(session_id) {
@@ -1542,7 +1526,7 @@ impl AgentManager {
let config = self.shared.known_config(&spec.id);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// The host names the fork's session id for claude; codex and Copilot assign their own.
// The host names the fork's session id for claude; codex assigns its own.
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
let task = AgentTask {
project_root: Some(IpcPath(root)),
@@ -2050,63 +2034,46 @@ impl AgentManager {
return Err(IdeError::invalid("wait until the agent is done"));
}
let epoch = self.shared.shutdown_epoch();
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
// It can also fork a recorded thread whose writer is held by another process.
let codex_source = {
let s = source.state.lock();
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
};
let live = if codex_source.is_none() {
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
} else {
None
};
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
let keep = turns.unwrap_or(total).min(total);
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
if !capabilities.fork || (keep < total && !capabilities.rollback) {
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
}
let session = if let Some(live) = &live {
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
Some(
reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned(),
)
} else {
None
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
let session = reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned();
let file = {
let s = source.state.lock();
let mut entries = s.history.conversation.main.entries.clone();
@@ -2132,7 +2099,7 @@ impl AgentManager {
};
TaskFile {
task,
session_id: session,
session_id: Some(session),
entries,
wanted: s.wanted.clone(),
pending_model: None,
@@ -2147,19 +2114,12 @@ impl AgentManager {
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
pending_native_fork: None,
}
};
// Copying may have started the source's agent: it stops again once idle.
if live.is_some() {
source.release_when_idle();
}
source.release_when_idle();
let task = Task::restore(file, self.shared.clone());
if live.is_none() {
// Establish the fork before returning so its snapshot cannot drift while the source continues.
task.ensure_session(epoch).await.map_err(IdeError::internal)?;
task.release_when_idle();
}
self.tasks.write().insert(task.id.clone(), task.clone());
task.persist();
task.emit_task();
@@ -4973,19 +4933,6 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// A writer conflict is temporary: retrying must retain the original session ID.
if spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
{
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
+9 -1
Переглянути файл
@@ -1088,7 +1088,15 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
env.push((k.clone(), v.clone()));
}
}
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
+3 -54
Переглянути файл
@@ -37,15 +37,6 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
/// Pre-session discovery result for `Shared::fetch_settings`.
pub(crate) struct Discovered {
pub commands: Vec<Value>,
@@ -560,7 +551,6 @@ impl CopilotShim {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
@@ -579,7 +569,7 @@ impl CopilotShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
@@ -659,25 +649,6 @@ impl CopilotShim {
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let loaded = self.resume_session(params, &session_id).await?;
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
self.replay_history(&actual_id).await;
Ok(loaded)
}
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
let target = forked
.get("sessionId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
.to_owned();
self.resume_session(params, &target).await
}
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
let cwd = str_param(params, "cwd")?;
let catalog = self.models().await?;
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
@@ -704,8 +675,7 @@ impl CopilotShim {
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
let _ = settings.set(&catalog, MODEL, model_id);
}
@@ -716,6 +686,7 @@ impl CopilotShim {
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
}
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
@@ -726,28 +697,6 @@ impl CopilotShim {
}))
}
async fn replay_history(&self, session_id: &str) {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let updates = {
let mut state = self.state.lock();
let Some(entry) = state.sessions.get_mut(session_id) else { return };
events
.iter()
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
.collect::<Vec<_>>()
};
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
-120
Переглянути файл
@@ -115,18 +115,6 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
}
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
@@ -446,39 +434,6 @@ impl Handler for FakeCopilotServer {
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
"session.getMessages" => Ok(json!({
"events": [
{
"type": "user.message",
"data": { "content": "Fix the parser" }
},
{
"type": "assistant.message",
"data": {
"messageId": "history-message",
"reasoningText": "Inspect the grammar first.",
"content": "I fixed the parser."
}
},
{
"type": "tool.execution_start",
"data": {
"toolCallId": "history-tool",
"toolName": "view",
"arguments": { "path": "/tmp/parser.rs" }
}
},
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "history-tool",
"success": true,
"result": { "content": "fn parse() {}" }
}
}
]
})),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
@@ -719,81 +674,6 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_loads_and_replays_copilot_history() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let loaded: Value = client
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(loaded["sessionId"], "cop-sess-1");
assert!(
server
.calls
.lock()
.iter()
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
);
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
)
);
assert!(
seen.iter()
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
);
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let forked: Value = client
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(forked["sessionId"], "cop-sess-fork");
let calls = server.calls.lock();
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
-49
Переглянути файл
@@ -370,55 +370,6 @@ impl EventTranslator {
}
out
}
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
/// event stream omits historical user messages and emits reasoning deltas, while the
/// persisted form has complete user and assistant messages.
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
if event_type == "user.message" {
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
return Translated { updates: Vec::new(), terminal: None };
};
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
return Translated {
updates: vec![(
target_session,
json!({
"sessionUpdate": "user_message_chunk",
"content": { "type": "text", "text": text },
}),
)],
terminal: None,
};
}
let mut translated = self.translate(main_session, event, fallback_limit);
if event_type == "assistant.message"
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
{
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
translated.updates.insert(
0,
(
target_session,
json!({
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": reasoning },
}),
),
);
}
translated
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
+5 -1
Переглянути файл
@@ -25,7 +25,11 @@ use std::sync::Arc;
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
pub(crate) fn newest_install(command: &str) -> String {
newest_install_in(command, &ide_core::tool_path::search_path())
let path = ide_core::process::host_var_os("PATH")
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
.unwrap_or_default();
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
newest_install_in(command, &ide_core::process::with_user_path(&path))
}
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
+11 -31
Переглянути файл
@@ -114,7 +114,7 @@ impl ProviderSpec {
if !program.is_absolute() {
return self.login_hint.clone();
}
let search = ide_core::tool_path::search_path();
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
let builtin = builtin_spec(&self.id);
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed_with_env(&spec.command, &spec.env),
installed: installed(&spec.command),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
@@ -1057,23 +1057,19 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
pub(crate) fn installed(command: &str) -> bool {
installed_with_env(command, &[])
}
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
let p = Path::new(command);
if p.components().count() > 1 || p.is_absolute() {
if p.components().count() > 1 {
return is_executable(p);
}
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
{
return true;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
}
fn is_executable(p: &Path) -> bool {
@@ -1330,22 +1326,6 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn installed_with_env_resolves_executables_on_provider_path() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
let exe = dir.path().join(name);
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(!installed("fake-agent"));
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
assert!(installed_with_env("fake-agent", &env));
}
#[test]
fn set_builtin_env_writes_and_clears_the_environment() {
let dir = tempfile::tempdir().unwrap();
+3 -5
Переглянути файл
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
}
fn on_path(command: &str) -> bool {
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
which::which(command).is_ok()
}
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
@@ -708,8 +708,7 @@ fn install_npm(
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
@@ -790,8 +789,7 @@ fn install_uv(
_ => format!("{name}=={}", entry.version),
};
check_spec(&spec)?;
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
let bin = dir.join("bin");
let mut cmd = Command::new(uv);
cmd.args(["tool", "install", "--force"])
+16 -1
Переглянути файл
@@ -185,7 +185,22 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
let file = Arc::new(Mutex::new(String::new()));
let connections = Arc::new(Mutex::new(0u32));
Arc::new(move |spec, cwd, client, on_stderr| {
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
let program = {
let path = Path::new(&spec.command);
if path.components().count() > 1 || path.is_absolute() {
path.to_path_buf()
} else {
let search = spec
.env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
}
};
let mut cmd = tokio::process::Command::new(&program);
ide_core::process::prepare(cmd.as_std_mut());
let mut child = cmd
-109
Переглянути файл
@@ -2191,41 +2191,6 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -3276,58 +3241,6 @@ fn plant_codex_session(root: &Path, session_id: &str) {
.unwrap();
}
/// Plants a recorded Copilot session below the test home.
fn plant_copilot_session(root: &Path, session_id: &str) {
let dir = root.join(".copilot").join("session-state").join(session_id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("workspace.yaml"),
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
)
.unwrap();
std::fs::write(
dir.join("events.jsonl"),
format!(
"{}\n",
json!({
"type": "user.message",
"data": {"content": "fix the Copilot parser"}
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn imports_copilot_sessions_and_loads_their_history() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let sessions = mgr.external_sessions();
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
assert_eq!(task.provider, "copilot");
for _ in 0..200 {
if agent.calls.lock().iter().any(|call| call == "session/load")
&& mgr.entries(&task.id, None).unwrap().len() >= 2
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
@@ -3348,28 +3261,6 @@ async fn fork_session_uses_the_id_codex_assigns() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_copilot_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
for _ in 0..200 {
if !agent.forks.lock().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "copilot names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
+3 -3
Переглянути файл
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
@@ -986,7 +986,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
+4 -87
Переглянути файл
@@ -180,30 +180,6 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -257,7 +233,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -294,7 +270,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
return Ok(cached.classpath);
}
continue;
}
@@ -322,7 +298,7 @@ pub fn module_classpaths(
}
}
}
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
Ok(classpaths.into_iter().next().unwrap())
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -370,8 +346,7 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -937,64 +912,6 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
+4 -19
Переглянути файл
@@ -234,7 +234,9 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
Some(out)
}
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
@@ -281,28 +283,11 @@ fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
entries.push(entry);
i += 1;
if wide {
if i == count {
return None;
}
entries.push(Entry::Empty);
i += 1;
}
}
Some(Pool(entries))
}
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
pub fn class_file_name(data: &[u8]) -> Option<String> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
r.u2()?; // access_flags
Some(pool.class(r.u2()?)?.to_owned())
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ mod incremental;
mod javac;
mod model;
pub use classfile::{ClassFile, class_file_name};
pub use classfile::ClassFile;
pub use javac::{JavacPool, Reply, ServerKey};
use incremental::{ClassRecord, SetStamp, SetState};
+2 -29
Переглянути файл
@@ -69,9 +69,6 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -179,7 +176,6 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -252,7 +248,6 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1524,13 +1519,7 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let dependencies = ctx
.deps
.iter()
@@ -1540,26 +1529,11 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: scope(d),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
(!path.contains("${") && Path::new(&path).is_absolute())
.then(|| Path::new(&path).components().collect::<PathBuf>())
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1618,7 +1592,6 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
-4
Переглянути файл
@@ -27,10 +27,6 @@ pub enum McpUiRequest {
subject: String,
project: String,
detail: Option<String>,
/// The project is served without a window: the request shows in another project's window,
/// which names it and keeps the keyboard focus where it is.
#[serde(default)]
background: bool,
},
OpenFile {
path: crate::IpcPath,
+4 -21
Переглянути файл
@@ -63,30 +63,13 @@ mod tests {
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
debounce(&DUE, Duration::from_millis(100), count);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
assert_eq!(RUNS.load(SeqCst), 0);
std::thread::sleep(Duration::from_millis(400));
assert_eq!(RUNS.load(SeqCst), 1);
release_free_pages_soon();
}
}
-93
Переглянути файл
@@ -83,24 +83,6 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
cmd
}
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
/// stopped there as a background job when the app was started from a shell) falls back to
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
/// elsewhere.
pub fn own_session(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
unsafe {
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
}
}
cmd
}
/// Kills the child and everything it started, then reaps it.
///
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
@@ -640,30 +622,6 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
}
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
/// loaded into the process or re-read from the registry (#6806): the extra NUL
/// is treated as an entry separator and leaves a fragment with no `=`.
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
}
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
s.as_encoded_bytes().contains(&byte)
}
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
/// included when this process lacks the variable.
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
@@ -988,28 +946,6 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn own_session_leaves_the_controlling_terminal_behind() {
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
let mut cmd = Command::new("sh");
cmd.args(["-c", "ps -o tty= -p $$"]);
let out = own_session(&mut cmd).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
// Without a terminal (CI) the line above holds anyway: the child must lead a session
// of its own, which only `setsid` makes it.
let mut cmd = Command::new("sleep");
cmd.arg("5");
let mut child = own_session(&mut cmd).spawn().unwrap();
let pid = libc::pid_t::try_from(child.id()).unwrap();
// SAFETY: plain syscall on a child not reaped yet.
let session = unsafe { libc::getsid(pid) };
let _ = child.kill();
let _ = child.wait();
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
@@ -1304,35 +1240,6 @@ mod tests {
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
}
fn os_from_bytes(bytes: &[u8]) -> OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(bytes.to_vec())
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
}
}
#[test]
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
let ok_key = OsString::from("PATH");
let ok_val = OsString::from("/bin");
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
// A REG_MULTI_SZ value's interior NUL would split the environment block,
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
}
#[test]
fn changes_apply_in_order() {
let vars = apply_changes(
+7 -24
Переглянути файл
@@ -5,29 +5,6 @@ use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
pub fn is_skipped_dir(name: &str) -> bool {
name.starts_with('.')
|| matches!(
name,
"node_modules"
| "target"
| "build"
| "dist"
| "vendor"
| "out"
| "bin"
| "obj"
| "venv"
| "SourcePackages"
| "Pods"
| "Carthage"
| "DerivedData"
)
}
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
@@ -36,7 +13,13 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
!is_skipped_dir(&entry.file_name().to_string_lossy())
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
})
.map(|entry| entry.path())
.collect();
+1 -7
Переглянути файл
@@ -203,9 +203,6 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -218,8 +215,7 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
/// Remote folder the project is synchronised to and run from (SSH).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -245,8 +241,6 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
-56
Переглянути файл
@@ -27,35 +27,6 @@ pub struct VcsSettings {
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
/// Settings › Version Control › Subversion.
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnSettings {
/// Path to the svn executable; empty = auto-detect.
pub executable: String,
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
pub interactive: bool,
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
}
impl Default for SvnSettings {
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
fn default() -> Self {
Self {
executable: String::new(),
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
}
}
}
/// Settings › Version Control › GitHub (`vcs.github`).
@@ -109,7 +80,6 @@ impl Default for VcsSettings {
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
svn: SvnSettings::default(),
}
}
}
@@ -560,7 +530,6 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -583,7 +552,6 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -602,14 +570,6 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -656,8 +616,6 @@ pub struct TerminalSettings {
pub close_on_exit: bool,
pub mouse_reporting: bool,
pub copy_on_selection: bool,
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
pub osc52_clipboard: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
@@ -698,7 +656,6 @@ impl Default for TerminalSettings {
close_on_exit: true,
mouse_reporting: true,
copy_on_selection: false,
osc52_clipboard: true,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
@@ -843,17 +800,4 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
-92
Переглянути файл
@@ -35,24 +35,6 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -104,57 +86,6 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,21 +103,6 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -211,14 +127,6 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+10 -95
Переглянути файл
@@ -360,46 +360,9 @@ fn find_binary_in(
}
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
(command == "lldb-dap" && !cfg!(windows))
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
.flatten()
})
}
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
/// The newest LLVM wins.
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
let version = |name: &str| -> Option<u32> {
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
v.parse().ok()
};
let mut found: Vec<(u32, PathBuf)> = Vec::new();
for dir in dirs {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
&& is_executable(&path, false)
{
found.push((v, path));
}
}
}
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
continue;
};
for name in ["lldb-dap", "lldb-vscode"] {
let path = entry.path().join("bin").join(name);
if is_executable(&path, false) {
found.push((v, path));
}
}
}
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
@@ -509,7 +472,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
const GDB_MIN_MAJOR: u32 = 14;
/// `(major, minor)` of the first version number in the output of `gdb --version`
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
@@ -550,29 +513,24 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
/// Probe the already resolved and verified executable with its launch environment.
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
}
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
let mut probe = Command::new(binary);
if let Some(path) = adapter_path(env, cwd) {
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
probe.env("PATH", path);
}
probe.current_dir(cwd);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
let probe = probe
.arg("--version")
.envs(env.iter().cloned())
.envs(spec.env.iter().cloned())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.output();
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
return None;
return Ok(None);
};
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
}
/// Refuse old GDB versions and report whether launch must follow configurationDone.
@@ -585,9 +543,8 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -1069,48 +1026,6 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
fn finds_versioned_lldb_dap() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let exe = |p: &Path| {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
exe(&bin.join("lldb-vscode-14"));
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
exe(&lib.join("llvm-18/bin/lldb-dap"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
exe(&bin.join("lldb-dap-19"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
}
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
#[test]
fn parses_gdb_versions() {
+1 -12
Переглянути файл
@@ -22,7 +22,6 @@ mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
pub mod native;
mod session;
mod stream_trace;
mod swiftpm;
@@ -508,11 +507,6 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
fn is_native(adapter: &str) -> bool {
matches!(adapter, "lldb-dap" | "codelldb")
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
@@ -1643,16 +1637,11 @@ impl DebugManager {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && (!own_terminate || killed) {
// A native attach to a program a run started for the debugger (an Xcode app launched
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
// simulator then holds its launch (and the next one) forever.
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
let _ = s
.conn
.request_timeout(
"disconnect",
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
SHUTDOWN_TIMEOUT,
)
.await;
-206
Переглянути файл
@@ -1,206 +0,0 @@
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
//! CodeLLDB is the debugger OpenIDEA can install itself.
use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
/// debugger command: a configured tool path, else the search path). Other launches pass through.
pub async fn choose(
mut config: LaunchConfig,
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
) -> IdeResult<LaunchConfig> {
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let found = tokio::task::spawn_blocking(move || {
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
if lookup("codelldb").is_some() {
return Found::CodeLldb;
}
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
match found {
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
Found::Nothing => return Err(missing(None)),
}
Ok(config)
}
enum Found {
LldbDap,
CodeLldb,
Gdb(PathBuf),
Nothing,
}
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
let found = match gdb {
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
IdeError::unavailable(format!(
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
))
}
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
None => Map::new(),
Some(Ok(Value::Object(extra))) => extra,
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
};
extra.remove("env");
let source_map = extra.remove("sourceMap");
if to == "codelldb" {
if let Some(Value::Array(pairs)) = source_map {
let map: Map<String, Value> = pairs
.iter()
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
_ => None,
})
.collect();
if !map.is_empty() {
extra.insert("sourceMap".into(), Value::Object(map));
}
}
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
}
config.adapter = to.to_owned();
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
name: "hello".into(),
adapter: "lldb-dap".into(),
request: "launch".into(),
program: Some("/home/dev/hello/build/hello".into()),
args: vec![],
cwd: Some(std::path::PathBuf::from("/").into()),
env: BTreeMap::from([("A".into(), "1".into())]),
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
}
}
fn extra(config: &LaunchConfig) -> Value {
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
}
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
}
#[tokio::test]
async fn keeps_lldb_dap_when_it_is_there() {
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "lldb-dap");
assert_eq!(config.extra_json, cmake_launch().extra_json);
}
#[tokio::test]
async fn falls_back_to_codelldb_with_its_launch_shape() {
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "codelldb");
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
assert_eq!(
extra(&config),
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
);
}
#[tokio::test]
async fn a_swift_package_evaluates_swift_under_codelldb() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
let config = choose(launch, only(&["codelldb"])).await.unwrap();
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
}
#[tokio::test]
async fn other_launches_pass_through() {
let mut attach = cmake_launch();
attach.request = "attach".into();
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
let mut rust = cmake_launch();
rust.adapter = "codelldb".into();
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
}
#[cfg(unix)]
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let gdb = dir.join("gdb");
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
gdb
}
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
#[cfg(unix)]
#[tokio::test]
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
#[tokio::test]
async fn falls_back_to_a_gdb_with_dap() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
}
}
+7 -13
Переглянути файл
@@ -1134,27 +1134,21 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
// See #6806: do not inherit portable-pty's registry-built Windows env block.
cmd.env_clear();
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
cmd.env(k, v);
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
}
for (k, v) in ide_core::process::shell_env_in(cwd) {
if ide_core::process::is_spawnable_env_pair(&k, &v) {
cmd.env(k, v);
}
cmd.env(k, v);
}
cmd.env("TERM", "xterm-256color");
cmd.cwd(cwd);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
match v.as_str() {
Some(v)
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
{
cmd.env(k, v)
}
Some(_) => {}
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
};
}
-22
Переглянути файл
@@ -4019,28 +4019,6 @@ async fn stop_detaches_from_an_attached_program() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
#[tokio::test]
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
let h = harness(Script::default());
let linked = |adapter: &str| LaunchConfig {
adapter: adapter.into(),
request: "attach".into(),
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
..config()
};
let id = h.start(linked("lldb-dap")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
let h = harness(Script::default());
let id = h.start(linked("debugpy")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
+62 -134
Переглянути файл
@@ -447,15 +447,6 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
// saves the separate query `table_comment` would make on the same `pg_class` row.
if let Some(comment) = next() {
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
if !comment.is_empty() {
details.comment = Some(comment);
}
}
}
fn flag(v: &Option<String>) -> bool {
@@ -1393,61 +1384,8 @@ impl DbManager {
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, ..Default::default() });
}
// Everything below describes the same table and none of it feeds the next, so it goes
// out together. Serialised, this is four round trips on the path that opens a table
// (`table_page_on` calls this for the primary key), which is what makes opening a table
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
// so one waits — still one round trip rather than five.
type Rows = Vec<Vec<Option<String>>>;
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let (index_q, fk_q, trigger_q) = (
sql::indexes(driver, schema, table),
sql::table_foreign_keys(driver, schema, table),
sql::triggers(driver, schema, table),
);
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
pool.rows(&index_q, MAX_META_ROWS),
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&fk_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("foreign keys: {}", e.message);
Ok(Vec::new())
}
}
},
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&trigger_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("triggers: {}", e.message);
Ok(Vec::new())
}
}
},
async {
// PostgreSQL reads it with the properties above; the engines without a
// `table_properties` query ask for it here.
match sql::table_comment(driver, schema, table) {
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
_ => Ok::<Rows, IdeError>(Vec::new()),
}
},
async {
match sql::table_properties(driver, schema, table) {
Some(q) => catalog_rows(pool, &q).await,
None => Ok::<Rows, IdeError>(Vec::new()),
}
},
);
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in index_rows? {
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
let mut it = r.into_iter();
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
else {
@@ -1463,7 +1401,11 @@ impl DbManager {
}),
}
}
let fk_rows = fk_rows?;
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
};
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
// SQLite keys that reference the primary key implicitly: look it up.
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
@@ -1476,7 +1418,15 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
let triggers = trigger_rows?
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
};
let triggers = trigger_rows
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
@@ -1489,21 +1439,26 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
let comment = comment_rows.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
);
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
match property_rows {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Ok(details)
}
@@ -1714,16 +1669,16 @@ impl DbManager {
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
}
DbDriver::Postgres => {
// Everything the script needs depends on the relation oid, so read that first and
// then the rest at once — five queries in flight against a pool of four, so one
// waits, but that is still two round trips instead of six.
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
rel.as_deref()
else {
return Err(missing());
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
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()),
};
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
if kind == "v" || kind == "m" {
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
let what = if kind == "m" { "materialized view" } else { "view" };
@@ -1731,70 +1686,43 @@ impl DbManager {
let target = sql::qualified(driver, schema, name);
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
}
let partition = match parent {
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
parent_schema: parent_schema.clone(),
parent_table: parent_table.clone(),
bound: bound.clone(),
}),
_ => None,
};
let is_partition = partition.is_some();
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
sql::postgres_ddl_columns(oid, is_partition),
sql::postgres_ddl_constraints(oid, is_partition),
sql::postgres_ddl_grants(oid),
sql::postgres_ddl_indexes(oid, is_partition),
sql::postgres_ddl_triggers(oid, is_partition),
);
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
catalog_rows(&pool, &cols_q),
pool.rows(&keys_q, MAX_META_ROWS),
pool.rows(&grants_q, MAX_META_ROWS),
pool.rows(&index_q, MAX_META_ROWS),
catalog_rows(&pool, &trigger_q),
);
let columns = col_rows?
let columns = pool
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let data_type = it.next().flatten()?;
let not_null = flag(&it.next().flatten());
let expression = it.next().flatten();
let comment = it.next().flatten().filter(|c| !c.is_empty());
let identity = it.next().flatten();
let generated = it.next().flatten();
let value =
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
Some(sql::DdlColumn {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
let constraints = key_rows?
let constraints = pool
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?))
})
.collect::<Vec<_>>();
let indexes =
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let grants = grant_rows?
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
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::<Vec<_>>();
let triggers =
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let options = sql::DdlTableOptions {
unlogged: persistence.as_deref() == Some("u"),
partition_key: partition_key.clone(),
partition,
};
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
.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))
}
}
}
+24 -224
Переглянути файл
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
pg_get_partkeydef(c.oid), c.relpersistence \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
@@ -697,70 +697,40 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
/// 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, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
"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 \
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
/// On a partition, the not-null flag and expression describe overrides of the parent column.
///
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
/// that view reports `character varying` without the length, `numeric` without the precision,
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
/// recreate the table. It also lists only the columns the current role holds privileges on.
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
let pretty = "(a.attgenerated::text = 's') IS TRUE";
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
let (not_null, expression, identity, parent_join) = if partition {
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
(
"a.attnotnull AND NOT pa.attnotnull",
format!(
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
),
"NULL",
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
)
} else {
("a.attnotnull", expression, "a.attidentity::text", "")
};
/// 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 {not_null} THEN 1 ELSE 0 END, \
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
"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), 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"
)
}
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
pub fn postgres_ddl_constraints(oid: u32) -> String {
format!(
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
)
}
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
let local =
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
pub fn postgres_ddl_indexes(oid: u32) -> String {
format!(
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
ORDER BY 1"
)
}
@@ -779,10 +749,9 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
let local = if partition { " AND tgparentid = 0" } else { "" };
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
@@ -871,12 +840,6 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relispartition", "false")
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
// These flags entered the catalog in different releases. Keep whichever ones exist.
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -1036,42 +999,10 @@ pub struct DdlColumn {
pub name: String,
pub data_type: String,
pub not_null: bool,
pub value: Option<DdlColumnValue>,
pub default: Option<String>,
pub comment: Option<String>,
}
pub enum DdlColumnValue {
Default(String),
IdentityByDefault,
IdentityAlways,
GeneratedStored(String),
}
impl DdlColumnValue {
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
match (identity, generated) {
(Some("d"), _) => Some(Self::IdentityByDefault),
(Some("a"), _) => Some(Self::IdentityAlways),
(_, Some("s")) => expression.map(Self::GeneratedStored),
(_, None | Some("")) => expression.map(Self::Default),
_ => None,
}
}
}
#[derive(Default)]
pub struct DdlTableOptions {
pub unlogged: bool,
pub partition_key: Option<String>,
pub partition: Option<DdlPartition>,
}
pub struct DdlPartition {
pub parent_schema: String,
pub parent_table: String,
pub bound: String,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
@@ -1090,30 +1021,17 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
options: &DdlTableOptions,
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let partition = options.partition.as_ref();
let mut items: Vec<String> = columns
.iter()
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
.map(|c| {
let mut s = format!(" {}", quote_ident(d, &c.name));
if partition.is_none() {
s.push(' ');
s.push_str(&c.data_type);
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
if let Some(v) = &c.default {
s.push_str(&format!(" default {v}"));
}
match &c.value {
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
None => {}
}
if c.not_null
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
{
if c.not_null {
s.push_str(" not null");
}
s
@@ -1121,35 +1039,7 @@ pub fn postgres_table_ddl(
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let target = qualified(d, schema, table);
let persistence = if options.unlogged { "unlogged " } else { "" };
let mut out = format!("create {persistence}table {target}");
if let Some(partition) = partition {
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
out.push_str(&format!(" partition of {parent}"));
}
if partition.is_none() || !items.is_empty() {
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
}
if let Some(partition) = partition {
out.push_str("\n ");
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
// including doubled quotes, while matching the casing of the generated DDL.
for (i, part) in partition.bound.split('\'').enumerate() {
if i != 0 {
out.push('\'');
}
if i % 2 == 0 {
out.push_str(&part.to_ascii_lowercase());
} else {
out.push_str(part);
}
}
}
if let Some(key) = &options.partition_key {
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
}
out.push_str(";\n");
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)));
@@ -1526,31 +1416,15 @@ mod tests {
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
}
#[test]
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
// role holds privileges on. The DDL must therefore read `pg_attribute` with
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
// `text[]` and an enum name come out as written.
let q = postgres_ddl_columns(42, false);
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
assert!(q.contains("FROM pg_attribute a"), "{q}");
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
assert!(q.contains("attrelid = 42"), "{q}");
assert!(!q.contains("information_schema"), "{q}");
}
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: 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,
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
default: Some("'x'::character varying".into()),
comment: None,
},
];
@@ -1561,94 +1435,21 @@ mod tests {
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlTableOptions::default(),
&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_renders_identity_and_stored_columns() {
let columns = [
("id_default", "bigint", true, "d", "", Some("ignored()")),
("id_always", "bigint", true, "a", "", None),
("total", "integer", true, "", "s", Some("qty * price")),
]
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
name: name.into(),
data_type: data_type.into(),
not_null,
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
comment: None,
});
let ddl =
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
assert_eq!(
ddl,
concat!(
"create table \"public\".\"t\"\n(\n",
" \"id_default\" bigint generated by default as identity,\n",
" \"id_always\" bigint generated always as identity,\n",
" \"total\" integer generated always as (qty * price) stored not null\n",
");\n",
)
);
}
#[test]
fn postgres_ddl_renders_unlogged_partitioned_parent() {
let columns =
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
let options =
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
assert_eq!(
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
);
}
#[test]
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
let columns = [DdlColumn {
name: "region".into(),
data_type: "text".into(),
not_null: false,
value: None,
comment: None,
}];
for (bound, rendered) in [
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
("DEFAULT", "default"),
] {
let options = DdlTableOptions {
partition: Some(DdlPartition {
parent_schema: "other".into(),
parent_table: "Parent\"Table".into(),
bound: bound.into(),
}),
..Default::default()
};
assert_eq!(
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
format!(
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\n"
)
);
}
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
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,
value: None,
default: None,
comment: Some("what's this".into()),
},
];
@@ -1667,7 +1468,6 @@ mod tests {
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&DdlTableOptions::default(),
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
+2 -27
Переглянути файл
@@ -391,12 +391,9 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -525,17 +522,6 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -857,17 +843,6 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
-1
Переглянути файл
@@ -28,7 +28,6 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-svn.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
+22 -30
Переглянути файл
@@ -292,21 +292,17 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
@@ -321,21 +317,17 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
+8 -20
Переглянути файл
@@ -1601,21 +1601,15 @@ mod tests {
let text = "a\n b\nc\nd\n e\n";
let formatted = "a\nb\nc\nd\ne\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let started = std::time::Instant::now();
let edits = minimal_edits(text, whole);
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
}
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
assert_eq!(after(text, &edits), formatted);
// Merged or not, the edits stay between the first and the last changed line.
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
// Single-line edits are already minimal and pass through.
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
assert_eq!(minimal_edits(text, small.clone()), small);
@@ -1666,17 +1660,11 @@ mod tests {
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let started = std::time::Instant::now();
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
}
// Merged or not, the edits leave the unchanged first and last lines alone.
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
-22
Переглянути файл
@@ -27,7 +27,6 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
pub mod svn;
mod swiftlint;
pub mod trust;
mod ts_code_style;
@@ -91,10 +90,6 @@ impl HostConfig {
pub struct Host {
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
pub(crate) subversion: Option<bool>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -214,21 +209,6 @@ impl Host {
self
}
/// Adds a version control system besides Git: projects opened afterwards look for its
/// working copies (when trusted) and route the Changes view, status and log to them.
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
self.vcs_providers.push(provider);
self
}
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
pub fn with_subversion(mut self, prompts: bool) -> Self {
self.subversion = Some(prompts);
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
@@ -257,8 +237,6 @@ impl Host {
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
-4
Переглянути файл
@@ -213,7 +213,6 @@ In OpenIDEA the user is asked first, then the IDE's own Debug action starts the
before-launch tasks and Debug tool window as when you press Debug. This needs a project window (it does not work \
for a background project without one). Program output goes to the Debug console, not into this tool's result.",
|call| async move {
call.needs_window()?;
let target =
execution_target(call.opt_str("configurationName")?, call.opt_str("filePath")?, call.opt_i64("line")?)?;
let envs = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
@@ -491,7 +490,6 @@ optional `message` from the last verification. Function and data breakpoints are
`function:` and `data:`. Call this before RESUME to check that an enabled breakpoint will be hit. Breakpoints set \
with `xdebug_set_breakpoint` are the same ones the editor shows and persists.",
|call| async move {
call.needs_window()?;
// The editor mirrors every change to the backend synchronously on request, so
// flushing its pending debounced syncs makes this the same list the editor shows.
call.ask(McpUiRequest::FlushBreakpoints).await?;
@@ -591,7 +589,6 @@ suspends the thread and does not implement one-shot or stack-logging breakpoints
`lineText` so the placement can be checked before RESUME. The breakpoint is shown in the editor's gutter and \
persists with the project; this needs a project window.",
|call| async move {
call.needs_window()?;
let _guard = BREAKPOINT_EDITS.lock().await;
let files = editor_breakpoints(&call);
let (path, line0, relocate_from) = if let Some(id) = call.opt_str("breakpointId")? {
@@ -683,7 +680,6 @@ that file are removed; with neither (the default `owner=agent`), all line breakp
Removal of a missing breakpoint is not an error: `removed` says whether anything was removed. `owner` is accepted \
for compatibility. Function and data breakpoints are managed in the IDE; this needs a project window.",
|call| async move {
call.needs_window()?;
let _guard = BREAKPOINT_EDITS.lock().await;
let owner = call.opt_str("owner")?;
if owner.as_deref().is_some_and(|o| o != "agent" && o != "user") {
-1
Переглянути файл
@@ -429,7 +429,6 @@ Requires a filePath parameter containing the path to the file to open.
The file path can be absolute or relative to the project root.
Optionally puts the caret at a 1-based line and column.",
|call| async move {
call.needs_window()?;
let raw = call.str("filePath")?;
// Opening shows the file to the user: outside the project the user agrees first.
let path = call.resolve_readable(&raw).await?;
+17 -5
Переглянути файл
@@ -1,7 +1,7 @@
use super::page::{OFFSET, Page};
use super::search::{PathScope, paths_param};
use super::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{Diagnostic, IdeResult, Severity};
use ide_core::{Diagnostic, IdeError, IdeResult, Severity};
use serde_json::{Map, Value, json};
/// Problems `get_project_problems` lists by default.
@@ -51,16 +51,28 @@ Lines and UTF-16 columns are 1-based.",
]
}
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
/// Editors and the Problems view are reported by a window: a project served in the
/// background has none, and says so instead of answering as if nothing were open.
fn reported_by_a_window(call: &Call) -> IdeResult<()> {
if !super::BackgroundProjects::is_key(call.window()) {
return Ok(());
}
let (tool, root) = (&call.tool, call.root().display());
Err(IdeError::unavailable(format!(
"{tool} needs the project open in a window: {root} is served in the background."
)))
}
/// [`reported_by_a_window`] for the Problems view, which `check_files` stands in for.
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
call.needs_window().map_err(|mut error| {
reported_by_a_window(call).map_err(|mut error| {
error.message.push_str(" Use check_files for diagnostics.");
error
})
}
async fn open_editors(call: Call) -> IdeResult<Output> {
call.needs_window()?;
reported_by_a_window(&call)?;
let paths = PathScope::of(&call)?;
let windows = call.host.mcp_windows(call.root());
let open = call.host.mcp_reports.editors(&windows);
@@ -72,7 +84,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
}
async fn current_file(call: Call) -> IdeResult<Output> {
call.needs_window()?;
reported_by_a_window(&call)?;
let editor = call.host.mcp_reports.focused(call.window());
Output::json(match editor {
None => json!({}),
+12 -60
Переглянути файл
@@ -18,7 +18,7 @@ pub mod service;
mod symbols;
mod tool;
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
pub(crate) use tool::trusted_attachments;
mod util;
use crate::Host;
@@ -28,7 +28,6 @@ pub use reports::{
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
use serde_json::json;
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -56,8 +55,7 @@ fn tools() -> Vec<tool::Tool> {
tools
}
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
// trust change takes effect immediately.
// Checked both when listing and calling, so a later trust change takes effect immediately.
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
trusted || tool.read_only
}
@@ -65,36 +63,11 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
}
all.into_iter().filter(|t| allowed(t, trusted)).collect()
}
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
if let Some(schema) = tool.input_schema.as_object_mut()
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
{
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
}
tool
}
/// The tool a call runs: a plugin's or a built-in one.
enum Found {
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
Builtin(tool::Tool),
}
impl Found {
fn writes(&self) -> bool {
match self {
Self::Plugin { metadata, .. } => !metadata.read_only,
Self::Builtin(tool) => !tool.metadata.read_only,
}
}
}
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
match host.project(window).ok().filter(|p| !p.light) {
@@ -137,16 +110,6 @@ impl Registry {
}
}
/// The tool `name` for `root`: a plugin's first. Loads nothing.
fn find(&self, root: &Path, name: &str) -> Option<Found> {
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
{
return Some(Found::Plugin { plugins, plugin, tool, metadata });
}
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
}
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
/// a background project that is not loaded is judged as its open will judge it.
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
@@ -187,9 +150,6 @@ impl ToolRegistry for Registry {
let trusted = self.lists_as_trusted(root)?;
Ok(tools_for(&self.0, root, trusted))
}
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
tools_for(&self.0, Path::new(""), true)
}
fn call(
&self,
root: &Path,
@@ -207,27 +167,19 @@ impl ToolRegistry for Registry {
cancel: CancellationToken,
client: &str,
) -> Result<String, ToolCallError> {
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
// Before the project loads, so the refusal neither loads a background project nor
// unloads an idle one at the limit to make room.
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
}
// The guard lives until the call ends, whichever way it leaves: neither the idle
// sweep nor the limit unloads a background project a call runs in.
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
// Found again: a plugin can change while a background project opens, and the call
// runs the tool as it is now.
let found = self.find(root, name).ok_or_else(unknown)?;
if found.writes() {
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) =
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
{
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
}
let tool = match found {
Found::Plugin { plugins, plugin, tool, metadata } => {
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
}
Found::Builtin(tool) => tool,
};
let tool = tools()
.into_iter()
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
let call = tool::Call {
host: self.0.clone(),
+24 -222
Переглянути файл
@@ -1,13 +1,9 @@
//! Window-bound requests; missing windows, cancellation and timeout all fail closed. A
//! confirmation for a project served in the background shows in another project's window
//! and moves to the next one when that window stops answering.
//! Window-bound requests; missing windows, cancellation and timeout all fail closed.
use super::tool::Call;
use crate::Host;
use ide_core::{IdeError, IdeEvent, IdeResult, event::McpUiRequest};
use parking_lot::{Mutex, MutexGuard};
use parking_lot::Mutex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::{Notify, oneshot};
use tokio::sync::oneshot;
#[derive(Default)]
pub struct Requests(Mutex<State>);
@@ -17,24 +13,10 @@ struct State {
pending: HashMap<u32, Pending>,
}
struct Pending {
/// The window key of the call that asked.
owner: String,
/// The window that shows the request and may answer it.
shown_in: String,
/// Signalled when `shown_in` stops answering while `owner` still waits.
moved: Arc<Notify>,
window: String,
answer: oneshot::Sender<Result<bool, String>>,
value: oneshot::Sender<Option<String>>,
}
impl State {
/// `window` answers no more requests: the ones it shows for another window move on.
fn stop_showing(&mut self, window: &str) {
self.ready.remove(window);
for pending in self.pending.values().filter(|p| p.shown_in == window && p.owner != window) {
pending.moved.notify_one();
}
}
}
impl Requests {
pub fn set_ready(&self, window: &str, ready: bool) {
if ready {
@@ -43,18 +25,10 @@ impl Requests {
self.forget_window(window);
}
}
/// `window` closed: its own requests fail, and the ones it shows for a project served in
/// the background move to another window.
pub fn forget_window(&self, window: &str) {
let mut state = self.0.lock();
state.pending.retain(|_, p| p.owner != window);
state.stop_showing(window);
}
/// `window` lost its project's trust: the requests it shows for a project served in the
/// background move to another window; its own stay there and fail the trust check after
/// the answer.
pub(crate) fn withdraw(&self, window: &str) {
self.0.lock().stop_showing(window);
state.ready.remove(window);
state.pending.retain(|_, p| p.window != window);
}
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
self.answer_with(window, id, allow, error, None)
@@ -69,10 +43,10 @@ impl Requests {
value: Option<String>,
) -> IdeResult<()> {
let mut state = self.0.lock();
if !state.pending.get(&id).is_some_and(|p| p.shown_in == window) {
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
}
let pending = state.pending.remove(&id).expect("the request was just found");
let pending = state.pending.remove(&id).unwrap();
let _ = pending.value.send(value);
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
@@ -90,96 +64,30 @@ impl Requests {
self.ask_inner(call, request).await
}
/// The window to show a background project's request in: the most recently focused ready
/// window whose project is trusted. Returns it with the state locked while it is still
/// ready, or `None` when there is none.
fn pick(&self, host: &Host) -> Option<(MutexGuard<'_, State>, String)> {
loop {
// Projects and focus are read without the lock, which is never held with theirs.
let mut windows: Vec<String> = self.0.lock().ready.iter().cloned().collect();
windows.retain(|w| host.project(w).is_ok_and(|p| p.is_trusted()));
host.mcp_reports.most_recently_focused_first(&mut windows);
let target = windows.into_iter().next()?;
let state = self.0.lock();
if state.ready.contains(&target) {
return Some((state, target));
}
}
}
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
let id = super::tool::request_id().0;
let (tx, mut rx) = oneshot::channel();
let (tx, rx) = oneshot::channel();
let (value_tx, value_rx) = oneshot::channel();
let moved = Arc::new(Notify::new());
let background = matches!(request, McpUiRequest::Confirm { background: true, .. });
let shown_in = {
let own = self.0.lock();
let (mut state, shown_in) = if own.ready.contains(call.window()) {
(own, call.window.clone())
} else {
drop(own);
background
.then(|| self.pick(&call.host))
.flatten()
.ok_or_else(|| IdeError::unavailable("MCP request denied: no project window is available"))?
};
let pending = Pending {
owner: call.window.clone(),
shown_in: shown_in.clone(),
moved: moved.clone(),
answer: tx,
value: value_tx,
};
state.pending.insert(id, pending);
shown_in
};
struct Close<'a> {
requests: &'a Requests,
call: &'a Call,
id: u32,
shown_in: String,
{
let mut state = self.0.lock();
if !state.ready.contains(call.window()) {
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
}
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
}
struct Close<'a>(&'a Requests, &'a Call, u32);
impl Drop for Close<'_> {
fn drop(&mut self) {
self.requests.0.lock().pending.remove(&self.id);
self.call.host.window_sink(&self.shown_in).emit(IdeEvent::McpRequestClosed { id: self.id });
self.0.0.lock().pending.remove(&self.2);
self.1.project.sink.emit(IdeEvent::McpRequestClosed { id: self.2 });
}
}
let mut close = Close { requests: self, call, id, shown_in };
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
// One deadline however often the request moves.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(180);
let result = loop {
// An answer that arrives together with a move or a close still counts.
tokio::select! {
biased;
result = &mut rx => break result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
// A project unloading after its window was forgotten must not reach another window.
_ = call.project.closed.cancelled() => return Err(IdeError::unavailable("MCP request denied: project closed")),
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
_ = moved.notified() => {
if self.window_ready(&close.shown_in) {
// The window answers again after a reload, whose new page has not seen the
// request: show it there again (the page drops a repeated id).
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
continue;
}
let target = {
let (mut state, target) = self
.pick(&call.host)
.ok_or_else(|| IdeError::unavailable("MCP request denied: project window closed"))?;
// Answered or dropped meanwhile: `rx` says which.
let Some(pending) = state.pending.get_mut(&id) else { continue };
pending.shown_in = target.clone();
target
};
let left = std::mem::replace(&mut close.shown_in, target);
call.host.window_sink(&left).emit(IdeEvent::McpRequestClosed { id });
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
}
}
let _close = Close(self, call, id);
call.project.sink.emit(IdeEvent::McpRequest { id, request });
let result = tokio::select! {
result = rx => result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
_ = tokio::time::sleep(std::time::Duration::from_secs(180)) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
};
match result {
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
@@ -188,109 +96,3 @@ impl Requests {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{HostConfig, mcp::BackgroundProjects};
use futures::FutureExt;
use ide_core::{CancellationToken, IdeEvent};
use std::path::PathBuf;
type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
/// A trusted project open in the ready window `main`, and the folder `inventory` loaded in the
/// background next to it.
struct Fixture {
host: Arc<Host>,
inventory: PathBuf,
events: Events,
_temp: tempfile::TempDir,
}
impl Fixture {
async fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (root, inventory) = (base.join("project"), base.join("inventory"));
for dir in [&root, &inventory] {
std::fs::create_dir_all(dir).unwrap();
}
let events = Events::default();
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
local_data_dir: base.join("local"),
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().push((window.clone(), e)))
}),
..HostConfig::for_test(&base)
}));
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
host.mcp_requests.set_ready("main", true);
Self { host, inventory, events, _temp: temp }
}
/// A call from the background project at `inventory`.
fn background_call(&self) -> Call {
let window = BackgroundProjects::key(&self.inventory);
Call {
client: "test-client".into(),
tool: "build_project".into(),
host: self.host.clone(),
project: self.host.open_project(&window, &self.inventory).unwrap(),
window,
args: serde_json::Value::Null,
cancel: CancellationToken::new(),
}
}
fn confirm(&self) -> McpUiRequest {
McpUiRequest::Confirm {
client: "test-client".into(),
tool: "build_project".into(),
subject: "build".into(),
project: self.inventory.to_string_lossy().into_owned(),
detail: None,
background: true,
}
}
/// The ids of the requests `main` was asked to show, in order.
fn shown_in_main(&self) -> Vec<u32> {
let events = self.events.lock();
let asked = events.iter().filter(|(window, _)| window == "main");
asked.filter_map(|(_, e)| if let IdeEvent::McpRequest { id, .. } = e { Some(*id) } else { None }).collect()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_request_of_a_project_that_closed_fails_instead_of_moving() {
let f = Fixture::new().await;
let call = f.background_call();
// Unloading forgets the project's key before it cancels `closed`; a request registered in
// between belongs to nobody that will answer it.
call.project.closed.cancel();
let error = f.host.mcp_requests.ask(&call, f.confirm()).now_or_never().expect("fails at once").unwrap_err();
assert_eq!(error.message, "MCP request denied: project closed");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reloaded_window_shows_the_request_again() {
let f = Fixture::new().await;
let call = f.background_call();
let ask = f.host.mcp_requests.ask(&call, f.confirm());
tokio::pin!(ask);
assert!((&mut ask).now_or_never().is_none());
let [id] = f.shown_in_main()[..] else { panic!("{:?}", f.shown_in_main()) };
// A reload: the old page stops answering and drops the request, the new one is ready.
f.host.mcp_requests.set_ready("main", false);
f.host.mcp_requests.set_ready("main", true);
assert!((&mut ask).now_or_never().is_none());
assert_eq!(f.shown_in_main(), [id, id]);
f.host.mcp_requests.answer("main", id, false, None).unwrap();
let error = ask.await.unwrap_err();
assert_eq!(error.message, "MCP request denied by the user");
}
}
-1
Переглянути файл
@@ -137,7 +137,6 @@ crashed, stoppedByAgent, stoppedByUser or startFailed; `exitCode`; `crash` with
process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
),
|call| async move {
call.needs_window()?;
let name = tab_name(&call.str("name")?)?;
let command = call.str("command")?;
if command.trim().is_empty() {
+4 -22
Переглянути файл
@@ -5,14 +5,6 @@ use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The argument that names the project a call is for; the server routes the call by it.
pub(crate) const PROJECT_PATH: &str = "projectPath";
/// The schema of [`PROJECT_PATH`], which every tool takes.
pub(crate) fn project_path() -> Value {
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
}
pub struct Call {
pub client: String,
pub tool: String,
@@ -96,24 +88,12 @@ impl Call {
client: self.client.clone(),
tool: self.tool.clone(),
subject: subject.into(),
project: ide_core::ipc_path::to_ipc(self.root()),
project: self.root().to_string_lossy().into_owned(),
detail,
background: super::BackgroundProjects::is_key(&self.window),
})
.await?;
self.project.require_trust()
}
/// Refuses a tool that works through the project's window (its editors, Problems view, Run
/// tool window or breakpoints) when the project is served in the background without one.
pub fn needs_window(&self) -> IdeResult<()> {
if !super::BackgroundProjects::is_key(&self.window) {
return Ok(());
}
let (tool, root) = (&self.tool, self.root().display());
Err(IdeError::unavailable(format!(
"{tool} needs the project open in a window: {root} is served in the background."
)))
}
pub fn host(&self) -> Arc<Host> {
self.host.clone()
}
@@ -262,7 +242,9 @@ impl Tool {
read_only: true,
destructive: false,
output_schema: None,
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
input_schema: json!({ "type": "object", "properties": {
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
}, "required": [] }),
},
handler: Arc::new(move |call| Box::pin(handler(call))),
}
+5 -21
Переглянути файл
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
"get_repositories",
"Retrieves the list of VCS roots in the project.
This is useful to detect all repositories in a multi-repository project.
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
rebase or cherry-pick in progress (`operationInProgress`).",
|call| async move {
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
let list: Vec<Value> = roots
@@ -117,9 +117,6 @@ In OpenIDEA each root also tells its current `branch` (absent when HEAD is detac
if let Some(op) = r.operation {
v["operationInProgress"] = op.into();
}
if r.unavailable {
v["unavailable"] = true.into();
}
v
})
.collect();
@@ -259,10 +256,10 @@ By default all Git repositories are returned.",
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
let host = call.host();
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
.await?
.into_iter()
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
.map(|r| (r.root.into_path_buf(), r.head))
.collect();
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
let paths = super::search::PathScope::of(&call)?;
@@ -274,25 +271,12 @@ By default all Git repositories are returned.",
};
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
repos
.into_iter()
.filter(|(_, (_, unavailable))| !unavailable)
.map(|(root, (head, _))| (root, head))
.collect()
} else {
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
for path in targets {
// The innermost repository containing the path.
let repo = match innermost_repo(repos.clone(), &path) {
Some((root, (_, true))) => {
if wanted.is_some() {
return Err(IdeError::unavailable(format!(
"Git repository '{}' is currently unavailable",
relative_to_project(&call, &root)
)));
}
continue;
}
Some((root, (head, false))) => (root, head),
Some(repo) => repo,
None => match find_git_root(call.root(), &path) {
Some(root) => {
// JetBrains reads the branch of any repository it reports.
-12
Переглянути файл
@@ -735,18 +735,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.syncSubmodules", "Sync Submodule URLs"),
],
),
// What only a Subversion working copy has; disabled for a Git repository.
sub(
"subversion",
"Subversion",
vec![
act("svn.cleanup", "Cleanup"),
act("svn.lock", "Lock…"),
act("svn.unlock", "Unlock"),
act("svn.relocate", "Relocate…"),
act("svn.properties", "Properties…"),
],
),
SEP,
act("vcs.showLog", "Show Git Log"),
sub(
+1 -5
Переглянути файл
@@ -1314,11 +1314,7 @@ mod build_tool_settings_tests {
let configure = config("configure", &["-S", ".", "-B", "release", "-G", "Ninja"]);
let mut build =
config("target", &["--build", "release", "--target", "hello", "--config", "Release", "-j", "8"]);
build.extras.before_launch.push(ide_run::BeforeLaunchTask {
kind: "build".into(),
target: "configure".into(),
..Default::default()
});
build.extras.before_launch.push(ide_run::BeforeLaunchTask { kind: "build".into(), target: "configure".into() });
let configs = [configure, build];
for kind in [BuildKind::Build, BuildKind::Rebuild] {
let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap();
+2 -30
Переглянути файл
@@ -1,15 +1,13 @@
mod kotlin;
#[cfg(test)]
mod kotlin_tests;
#[cfg(test)]
mod native_tests;
mod output;
use crate::Host;
use ide_command::command;
use ide_core::{DebugSessionId, IdeResult};
use ide_dap::*;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
#[command(trust = trusted)]
@@ -142,17 +140,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
config = add_java_source_paths(config, &roots);
}
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
if config.adapter == "lldb-dap" {
let (root, settings) = (root.clone(), settings.clone());
let project_root = project.root.clone();
config = ide_dap::native::choose(config, move |command| {
native_debugger_command(&project_root, &settings.debugger.cpp, command)
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
})
.await?;
}
let mut ruby_tools = Vec::new();
if config.adapter == "rdbg" && config.request == "launch" {
let project_root = host.project(window).map(|p| p.root.clone()).unwrap_or_else(|_| root.clone());
@@ -165,13 +152,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.await?;
}
let java_analyzer = java_analyzer_command(host, window, &config)?;
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
let custom = |command: &str| {
if let Some(binary) = java_analyzer {
return Some(binary.to_string_lossy().into_owned());
}
let path = native
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
let path = ide_sdk::apply::tool_command(&root, &settings, command)
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
Some(path.to_string_lossy().into_owned())
};
@@ -203,19 +188,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
result
}
fn native_debugger_command(
root: &Path,
settings: &ide_core::settings::CppDebuggerSettings,
adapter: &str,
) -> Option<PathBuf> {
let path = match adapter {
"gdb" => &settings.gdb_executable,
"lldb-dap" => &settings.lldb_dap_executable,
_ => return None,
};
ide_sdk::apply::setting_path(root, path)
}
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
/// (`projectRoot`, else the working directory), so the session debugs with the server that
/// analyzes the code.
-63
Переглянути файл
@@ -1,63 +0,0 @@
use super::*;
use ide_core::IdeError;
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
use ide_workspace::SettingsScope;
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Default)]
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
impl AdapterLauncher for CaptureAdapter {
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
*self.0.lock() = Some(spec);
Box::pin(async { Err(IdeError::cancelled()) })
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cpp_debugger_paths_override_adapter_commands() {
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let root = base.join("project");
let cwd = root.join("build");
std::fs::create_dir_all(&cwd).unwrap();
let capture = Arc::new(CaptureAdapter::default());
let mut host = Host::new(crate::HostConfig::for_test(&base));
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let project = host.project("main").unwrap();
for (adapter, key, configured) in [
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
] {
let config = LaunchConfig {
name: "C++".into(),
adapter: adapter.into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(cwd.clone().into()),
env: Default::default(),
extra_json: Some(r#"{"pid":1}"#.into()),
};
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
project
.settings
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
.unwrap();
let mut config = config;
config.request = "launch".into();
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
config.extra_json = None;
let _ = debug_start(&host, "main", config).await.unwrap_err();
let spec = capture.0.lock().take().unwrap();
assert_eq!(spec.adapter, adapter);
assert_eq!(Path::new(&spec.command), root.join(configured));
assert_eq!(spec.cwd, cwd);
}
}
+6 -47
Переглянути файл
@@ -243,26 +243,12 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
/// Off the main thread: opening a file for edit can ask a server (`svn lock`, `p4 edit`) and
/// wait for a login.
#[command(trust = always)]
pub async fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
let project = host.project(window).ok();
host.blocking(move || match project {
Some(p) => {
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
// its server learns about the change to come. `backend_of` is empty unless trusted.
if writable
&& let Some(backend) = p.backend_of(&path)
&& backend.open_for_edit(std::slice::from_ref(&path))?
{
p.vcs_changed();
}
p.documents.set_writable(&path, writable)
}
None => ide_vfs::set_writable(&path, writable).map(|()| !writable),
})
.await
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
match host.project(window) {
Ok(p) => p.documents.set_writable(&path, writable),
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
}
}
/// Moving to the trash can take a while (large trees): kept off the main thread.
@@ -305,34 +291,7 @@ fn delete_recorded(project: Option<&Project>, path: &Path, undoable: bool) -> Id
#[command(trust = always)]
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
let project = host.project(window)?;
host.blocking(move || {
let wanted = undo.paths();
let skipped = project.history.restore_deletion_undo(undo);
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
// takes that back, keeping the restored content. Git records deletions at commit time.
// One call per working copy: its first folder takes the tree below with it anyway.
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
let Some(backend) = project.backend_of(path) else { continue };
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, paths)) => paths.push(path.clone()),
None => by_backend.push((backend, vec![path.clone()])),
}
}
for (backend, paths) in by_backend {
// The files are back either way; still scheduled for deletion, they would go at commit.
if let Err(e) = backend.unstage(&paths) {
tracing::warn!("undo of delete in {}: {e}", backend.root().display());
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "The restored files are still scheduled for deletion".into(),
body: Some(e.message),
});
}
}
Ok(skipped)
})
.await
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
}
#[command(trust = always)]
-41
Переглянути файл
@@ -246,7 +246,6 @@ pub(crate) async fn resolve_launch(
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_maven_system_classpath(&mut info, root, &model, &module);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
@@ -564,9 +563,6 @@ async fn resolve_launch_without_jdtls(
},
)?;
info.class_paths = class_paths;
if !by_service {
apply_maven_system_classpath(&mut info, root, &model, &module);
}
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
@@ -685,15 +681,6 @@ fn entry_key(path: &str, windows: bool) -> String {
if windows { key.to_lowercase() } else { key }
}
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
for path in compile::maven_system_classpath(root, model, module) {
let path = path.to_string_lossy();
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
info.class_paths.push(path.into_owned());
}
}
}
fn apply_library_classpath(
info: &mut JavaLaunchInfo,
root: &std::path::Path,
@@ -1288,34 +1275,6 @@ mod tests {
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
}
#[test]
fn java_server_launch_classpath_includes_local_maven_system_jars() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let jar = ["src", "main", "resources", "lib", "offline.jar"].iter().fold(root.clone(), |p, c| p.join(c));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
</dependency></dependencies></project>"#,
)
.unwrap();
let model = ide_build::load(&root, &root.join("cache"), None);
let jar = jar.to_string_lossy().into_owned();
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
apply_maven_system_classpath(&mut info, &root, &model, &root);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes", &jar]);
info.class_paths.pop();
info.module_paths.push(jar);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes"]);
}
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
+2 -19
Переглянути файл
@@ -929,14 +929,9 @@ pub async fn lsp_library_sources(
#[command(trust = trusted)]
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
// Opens compiled classes through JDT as decompiled class documents.
let archive = ide_vfs::split_archive_path(&path);
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
}
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
let bytes = tokio::fs::read(path).await?;
ide_build::jbuild::class_file_name(&bytes)
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
host.project(window)?.lsp.java_class_file(&path, archive).await
}
/// References of the symbol at `pos`. `project_wide` also searches project files
@@ -2497,18 +2492,6 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[tokio::test]
async fn disk_class_name_comes_from_bytecode() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("moved.class");
// Class header, UTF-8 and Class constants, then access_flags and this_class.
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
std::fs::write(&path, bytes).unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
std::fs::write(&path, b"invalid").unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
}
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
-2
Переглянути файл
@@ -45,7 +45,6 @@ pub mod settings_sync;
pub mod spell;
pub mod ssh;
pub mod stream_trace;
pub mod svn;
pub mod syntax;
pub mod term;
pub mod thread_dump;
@@ -134,7 +133,6 @@ ide_command::domains!(
search_commands: crate::ops::search::commands,
spell: crate::ops::spell,
ssh: crate::ops::ssh,
svn: crate::ops::svn,
stream_trace: crate::ops::stream_trace,
syntax: crate::ops::syntax,
term: crate::ops::term,
+10 -57
Переглянути файл
@@ -1,34 +1,19 @@
use crate::project::Project;
use ide_core::IdeResult;
use ide_dap::LaunchConfig;
use ide_workspace::roots::{RootKind, SourceFolder};
use std::collections::{BTreeMap, HashSet};
use ide_workspace::roots::RootKind;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// The project's import roots, put on `PYTHONPATH` by runs, debug sessions and consoles.
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
import_roots(&project.root, project.content_roots(), &project.roots().roots)
}
/// `root`, the content roots, then the Source and Test roots. A detected root that is itself a
/// package (it holds `__init__.py`, like an Odoo addon or its `tests` folder) is left out:
/// importing from it would give its modules a second top-level name, and a project with
/// thousands of them made `PYTHONPATH` longer than a process environment can hold (#7083).
/// Folders the user marked always count.
fn import_roots(root: &Path, content_roots: Vec<PathBuf>, roots: &[SourceFolder]) -> Vec<PathBuf> {
let mut paths = vec![root.to_path_buf()];
paths.extend(content_roots);
let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
for folder in roots {
if !matches!(folder.kind, RootKind::Source | RootKind::Test) {
continue;
}
let path = root.join(&folder.path);
if folder.detected_from.is_some() && path.join("__init__.py").is_file() {
continue;
}
if seen.insert(path.clone()) {
paths.push(path);
let mut paths = vec![project.root.clone()];
paths.extend(project.content_roots());
for root in project.roots().roots {
if matches!(root.kind, RootKind::Source | RootKind::Test) {
let path = project.root.join(root.path);
if !paths.contains(&path) {
paths.push(path);
}
}
}
paths
@@ -135,38 +120,6 @@ pub(super) fn prepare_debug(
#[cfg(test)]
mod tests {
#[test]
fn detected_package_folders_are_not_import_roots() {
use ide_workspace::roots::{RootKind, SourceFolder};
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for file in ["src/pkg/__init__.py", "addon/__init__.py", "addon/tests/__init__.py", "marked/__init__.py"] {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
std::fs::create_dir_all(root.join("tests")).unwrap();
let folder = |path: &str, kind, detected: bool| SourceFolder {
path: path.into(),
kind,
detected_from: detected.then(|| "pyproject.toml".into()),
};
let roots = [
folder("src", RootKind::Source, true),
folder("tests", RootKind::Test, true),
folder("addon", RootKind::Source, true),
folder("addon/tests", RootKind::Test, true),
folder("marked", RootKind::Source, false),
folder("build", RootKind::Excluded, true),
folder("src", RootKind::Source, true),
];
assert_eq!(
super::import_roots(root, vec![], &roots),
[root.to_path_buf(), root.join("src"), root.join("tests"), root.join("marked")],
"detected packages are left out, a folder the user marked stays, no duplicates"
);
}
use super::*;
#[test]
+15 -144
Переглянути файл
@@ -448,18 +448,13 @@ async fn start_inner(
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
// The settings of the workspace member it belongs to derived its values.
let mut member = config.clone();
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
let (config, note) = if target.kind == RunTargetKind::Wsl {
(container::prepare_wsl(host, &project.root, target, config).await?, None)
} else {
container::prepare(host, &project.root, target, config).await?
};
// A local run of the docker CLI: the command is resolved in the container, and
// this machine's toolchains and `PYTHONPATH` don't apply.
let mut config = config;
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let (config, note) = container::prepare(host, &project.root, target, config).await?;
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
@@ -467,7 +462,7 @@ async fn start_inner(
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
// A folder on this machine: not in the container or distribution.
// A folder on this machine: not in the container.
ruby_reporter: None,
plots: None,
capture_junit_reports: false,
@@ -552,23 +547,19 @@ async fn start_inner(
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
if config.kind == "xcode" {
let dir = run_dir.clone();
let say = on_output.clone();
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
// Reading build settings can take a minute on a large workspace: say what's going on.
ide_run::xcode::prepare(&dir, &mut config, &|text| {
say(OutputChunk::System { text: format!("{text}\n") })
})?;
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
Ok(config)
})
.await?;
}
if config.kind == ide_run::xcode_clean::KIND {
let dir = run_dir.clone();
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
ide_run::xcode_clean::prepare(&dir, &mut config)?;
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
Ok(config)
})
.await?;
@@ -627,8 +618,6 @@ async fn start_inner(
}
let on_output = match xcode_container {
Some(container) => {
let on_output =
if config.kind == "xcode" { split_build_log(&project, &config, on_output) } else { on_output };
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
sink = problems;
output
@@ -648,53 +637,6 @@ fn xcode_container(config: &RunConfig) -> Option<String> {
const XCODEBUILD_SOURCE: &str = "xcodebuild";
/// Sends an Xcode run's build output to a log file instead of the console, which keeps the app's
/// own output ([`ide_run::xcode::RunOutputSplit`]). Each run of the configuration replaces the
/// file. It is in the temporary folder: the console links a path only without spaces, and the
/// project's cache is under `Application Support`. Problems still sees all of the output: this
/// wraps the console, after [`xcodebuild_problems`] has read it.
fn split_build_log(
project: &crate::project::Project,
config: &RunConfig,
on_output: Emit<OutputChunk>,
) -> Emit<OutputChunk> {
use std::io::Write;
let name: String =
config.id.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect();
let project_key = project.cache_dir.file_name().unwrap_or_default();
let path = std::env::temp_dir().join("openidea-xcode-build").join(project_key).join(format!("{name}.log"));
let file = std::fs::create_dir_all(path.parent().unwrap_or(&path))
.and_then(|()| std::fs::File::create(&path))
.map(std::io::BufWriter::new);
let file = match file {
Ok(file) => Some(file),
Err(e) => {
on_output(OutputChunk::System { text: format!("Cannot write the build log {}: {e}\n", path.display()) });
None
}
};
let wait = config.extras.params.get(ide_run::xcode::WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
let split = ide_run::xcode::RunOutputSplit::new(&path, wait);
let state = parking_lot::Mutex::new((split, file));
Arc::new(move |chunk: OutputChunk| {
let mut guard = state.lock();
let (split, file) = &mut *guard;
let out = split.feed(chunk);
if let Some(f) = file.as_mut()
&& !out.log.is_empty()
{
let _ = f.write_all(out.log.as_bytes());
if !split.building() {
let _ = f.flush();
}
}
drop(guard);
for chunk in out.console {
on_output(chunk);
}
})
}
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
@@ -922,44 +864,6 @@ pub use commands::*;
mod ownership_tests {
use super::*;
#[cfg(unix)]
#[test]
fn a_remote_run_gets_none_of_this_machines_derived_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let venv = root.join(".venv");
std::fs::create_dir_all(venv.join("bin")).unwrap();
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(venv.join("bin/python"), "").unwrap();
let mut settings = ide_core::settings::Settings::default();
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
let mut config = RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: "python".into(),
args: vec!["main.py".into()],
cwd: None,
env: [("FOO".to_owned(), "bar".to_owned())].into(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.target = Some("wsl".into());
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
let derived = Derived { root, fallback: None, settings: &settings };
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
assert_eq!(out.command, "python", "the interpreter is the target's");
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
}
#[cfg(unix)]
#[test]
fn source_roots_go_on_the_container_pythonpath() {
@@ -1158,9 +1062,6 @@ pub async fn run_container_path(
if !path.starts_with('/') {
return Ok(None);
}
if run_target.kind == RunTargetKind::Wsl {
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
}
let library = snapshots
.and_then(|dir| ide_sdk::container_python::current(&dir))
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
@@ -1173,39 +1074,9 @@ pub async fn run_container_path(
.await
}
/// `config` for a container or WSL distribution: without what settings derived from this
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
/// still apply there and are kept.
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
let mut out = config.clone();
out.command = plain.command;
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
if ide_run::is_python_kind(&out.kind) {
container_python_path(&mut out.env, python_roots, root);
}
out
}
/// The settings a configuration's derived values come from (see [`settings_for`]).
#[derive(Clone, Copy)]
struct Derived<'a> {
root: &'a Path,
fallback: Option<&'a Path>,
settings: &'a ide_core::settings::Settings,
}
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
/// as `GOPROXY`'s is not: its first part is `https`).
fn has_local_path(value: &str) -> bool {
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
}
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
/// run gets them: they are mounted with the project, and `container::prepare` /
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
/// they are mounted with the project, and `container::prepare` maps their paths. The
/// container's separator is `:`, whatever this machine's is.
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
let mut paths: Vec<String> =
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
+2 -33
Переглянути файл
@@ -1,5 +1,5 @@
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
//! Docker and Compose run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`).
use crate::Host;
use ide_core::remote_settings::{RunTarget, RunTargetKind};
@@ -73,37 +73,6 @@ pub(super) async fn prepare(
.await
}
/// `config` rewritten to run in `target`'s WSL distribution.
pub(super) async fn prepare_wsl(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<RunConfig> {
if !cfg!(windows) {
return Err(IdeError::invalid(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let root = root.to_path_buf();
host.blocking(move || {
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
let file_env = env_files(&root, &config)?;
let inherited = std::env::var("WSLENV").ok();
ide_remote::wsl::wsl_config(
&config,
&target,
&root,
&linux_root,
ide_core::wsl::EXE,
&file_env,
inherited.as_deref(),
)
})
.await
}
/// The project can only be bind-mounted from a daemon on this machine.
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
if !ide_docker::endpoint_is_local(endpoint)? {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
+12 -126
Переглянути файл
@@ -4,9 +4,6 @@
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
//! the stopped container with `docker cp`. Nothing is installed in the container.
//!
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
//! in place through `\\wsl.localhost\<distro>`.
use crate::Host;
use crate::project::Project;
@@ -26,8 +23,6 @@ use std::time::Duration;
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const QUICK: Duration = Duration::from_secs(30);
/// Starting the distribution may come first.
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// The project interpreter when it is a run target's.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -39,10 +34,8 @@ pub struct ContainerPython {
pub name: String,
/// The Python version of the snapshot in use; `None`: no snapshot yet.
pub version: Option<String>,
/// The image the snapshot was copied from; `None` for WSL.
/// The image the snapshot was copied from.
pub image: Option<String>,
/// The interpreter's path in the container or distribution.
pub executable: Option<String>,
/// The copied library folders on this machine.
pub folders: Vec<IpcPath>,
/// Packages of the snapshot (read-only).
@@ -115,25 +108,22 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
}
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
#[command(trust = trusted)]
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
host.require_trust(window)?;
let project = host.project(window)?;
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
Ok(describe(host, &project.root, &project.settings.effective()))
}
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
let target = settings.languages.python.run_target()?;
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
let dir = dirs.target(root, target);
let dir = Dirs::of(host).target(root, target);
let mut out = ContainerPython {
target: target.to_owned(),
name,
version: None,
image: None,
executable: None,
folders: Vec::new(),
packages: Vec::new(),
updating: updating(&dir),
@@ -142,8 +132,7 @@ fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPy
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
out.packages = snapshots::packages(&dir, &snapshot);
out.version = Some(snapshot.probe.version);
out.executable = Some(snapshot.probe.executable);
out.image = snapshot.distro.is_none().then_some(snapshot.image);
out.image = Some(snapshot.image);
}
Some(out)
}
@@ -155,8 +144,7 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
host.require_trust(window)?;
let project = host.project(window)?;
update(Dirs::of(host), &project, true).await?;
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
Ok(describe(host, &project.root, &project.settings.effective()))
}
/// Takes a snapshot when the project interpreter is a run target's and the current image
@@ -166,22 +154,13 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
return;
}
let (dirs, project) = (Dirs::of(host), project.clone());
let settings = project.settings.effective();
let wsl = settings
.languages
.python
.run_target()
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
let title =
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
host.runtime.spawn(async move {
if let Err(e) = update(dirs, &project, false).await
&& e.kind != ide_core::error::ErrorKind::Cancelled
{
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: title.into(),
title: "Cannot copy the container's Python libraries".into(),
body: Some(e.message),
});
}
@@ -194,7 +173,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind == RunTargetKind::Ssh {
return Err(IdeError::invalid(format!(
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
target.name
)));
}
@@ -203,10 +182,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
return Ok(());
}
let _done = Updating(dir.clone());
let endpoint = match target.kind {
RunTargetKind::Wsl => None,
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
};
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
let task = TaskId::next();
let title = format!("Python libraries of {}", target.name);
let (root, sink) = (project.root.clone(), project.sink.clone());
@@ -222,11 +198,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
};
let report = progress.clone();
let result = tokio::task::spawn_blocking(move || {
let report = |message: &str| report(message, false);
match endpoint {
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
}
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -316,7 +288,6 @@ fn take(
image: image.clone(),
probe,
folders,
distro: None,
};
snapshots::write(&partial, &snapshot)?;
if dir.exists() {
@@ -327,72 +298,6 @@ fn take(
Ok(true)
}
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
fn take_wsl(
root: &Path,
target: &RunTarget,
target_dir: &Path,
cache: &Path,
progress: &dyn Fn(&str),
) -> IdeResult<bool> {
if !cfg!(windows) {
return Err(IdeError::unavailable(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let linux_root = ide_remote::wsl::project_root(target, root)?;
let distro = target.distro.trim();
progress("Starting the WSL Python");
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
let probe = snapshots::parse_probe(&out)?;
let id = format!("wsl-{}-{}", probe.executable, probe.version);
let snapshot = Snapshot {
image: id.clone(),
folders: wsl_folders(&probe, &linux_root),
neutral_python: snapshots::neutral_python(cache, &probe.version),
distro: Some(distro.to_owned()),
probe,
};
// What the language server is given: the probe's other details (its raw `sys.path` order,
// say) are kept in the snapshot but don't restart it.
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
let dir = target_dir.join(snapshots::dir_name(&id));
std::fs::create_dir_all(&dir)?;
snapshots::write(&dir, &snapshot)?;
snapshots::make_current(target_dir, &id)?;
Ok(changed)
}
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
let root = linux_root.trim_end_matches('/');
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
}
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
#[command(trust = trusted)]
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
if !cfg!(windows) {
return Ok(Vec::new());
}
let root = host.project(window)?.root.clone();
host.blocking(move || {
let distro = distro.trim();
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
})
.await
}
/// Distinguishes probe containers.
fn unique() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -401,23 +306,4 @@ fn unique() -> String {
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
}
#[cfg(test)]
mod wsl_tests {
#[test]
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
let probe = super::snapshots::Probe {
version: "3.12.3".into(),
executable: "/mnt/c/p/.venv/bin/python".into(),
stdlib: vec![Some("/usr/lib/python3.12".into())],
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
.map(String::from)
.to_vec(),
};
assert_eq!(
super::wsl_folders(&probe, "/mnt/c/p"),
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
);
}
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
-265
Переглянути файл
@@ -1,265 +0,0 @@
//! What only Subversion has (VCS › Subversion): Cleanup, Lock / Unlock,
//! Relocate, Properties, and Checkout from URL. Everything else a Subversion
//! working copy does goes through the shared `vcs_*` commands and
//! [`ide_vcs::Backend`].
use crate::Host;
use crate::Project;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_svn::WorkingCopy;
use ide_vcs::Backend;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The working copy a Subversion backend is, if it is one.
pub(crate) fn as_svn(backend: &dyn Backend) -> Option<&WorkingCopy> {
(backend as &dyn std::any::Any).downcast_ref::<WorkingCopy>()
}
/// Runs `f` with the Subversion working copy `at` names (its root), or the one holding `path`.
fn with_working_copy<T>(
project: &Project,
at: Option<&Path>,
f: impl FnOnce(&WorkingCopy) -> IdeResult<T>,
) -> IdeResult<T> {
let backend: Option<Arc<dyn Backend>> = match at {
Some(path) => project.backend_of(path),
None => project.backend_at(None),
};
match backend.as_deref().and_then(as_svn) {
Some(wc) => f(wc),
None => Err(IdeError::invalid("not in a Subversion working copy")),
}
}
/// VCS › Subversion › Cleanup: finishes or undoes an interrupted operation and
/// releases the working copy's lock.
#[command(trust = trusted)]
pub async fn svn_cleanup(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| wc.cleanup(&CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// VCS › Subversion › Lock: `svn lock` with a comment; `steal` takes a lock someone else holds.
#[command(trust = trusted)]
pub async fn svn_lock(host: &Host, window: &str, paths: Vec<PathBuf>, comment: String, steal: bool) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to lock"))?;
with_working_copy(&project, Some(&first), |wc| wc.lock(&paths, &comment, steal, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// VCS › Subversion › Unlock; `force` breaks a lock this working copy does not hold.
#[command(trust = trusted)]
pub async fn svn_unlock(host: &Host, window: &str, paths: Vec<PathBuf>, force: bool) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to unlock"))?;
with_working_copy(&project, Some(&first), |wc| wc.unlock(&paths, force, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Where a working copy points: VCS › Subversion › Relocate shows the current URL.
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnRepositoryInfo {
pub url: String,
pub root_url: String,
pub revision: Option<u32>,
}
#[command(trust = trusted)]
pub async fn svn_repository_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<SvnRepositoryInfo> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| {
let r = wc.repository();
Ok(SvnRepositoryInfo {
url: r.url,
root_url: r.root_url,
revision: r.revision.and_then(|r| u32::try_from(r).ok()),
})
})
})
.await
}
/// VCS › Subversion › Relocate: the same repository at a new URL (another host or scheme).
#[command(trust = trusted)]
pub async fn svn_relocate(host: &Host, window: &str, repo: Option<PathBuf>, url: String) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| wc.relocate(&url, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// The conflicts dialog's Accept Deletion on a tree conflict whose incoming change deleted
/// `path`: the conflict is resolved and the local item removed.
#[command(trust = trusted)]
pub async fn svn_accept_incoming_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
project.with_backend_recorded(
project.backend_of(&path).as_deref().map(|b| b.root()),
Some("Accept deletion"),
|b| {
as_svn(b)
.ok_or_else(|| IdeError::invalid("not in a Subversion working copy"))?
.accept_incoming_delete(&path)
},
)?;
project.vcs_changed();
Ok(())
})
.await
}
/// One versioned property (`svn:ignore`, `svn:needs-lock`, or the user's own).
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnProperty {
pub name: String,
pub value: String,
}
/// VCS › Subversion › Properties: the properties of a file or folder.
#[command(trust = trusted)]
pub async fn svn_properties(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<SvnProperty>> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, Some(&path), |wc| {
Ok(wc.properties(&path)?.into_iter().map(|(name, value)| SvnProperty { name, value }).collect())
})
})
.await
}
/// Sets property `name` of `path`, or deletes it when `value` is `None`.
#[command(trust = trusted)]
pub async fn svn_set_property(
host: &Host,
window: &str,
path: PathBuf,
name: String,
value: Option<String>,
) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, Some(&path), |wc| wc.set_property(&path, &name, value.as_deref()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Settings › Version Control › Subversion: the svn found on `PATH` or in a usual
/// install folder, and the version of `executable` (that one when empty).
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnVersion {
pub detected: Option<String>,
pub version: Option<String>,
pub error: Option<String>,
}
/// Settings › Subversion › Test. Auto-detection runs anywhere; a path of the user's or the
/// project's choosing runs only in a trusted project (as Git's Test does).
#[command(trust = always)]
pub async fn svn_version(host: &Host, window: &str, executable: String) -> IdeResult<SvnVersion> {
if !executable.trim().is_empty() {
host.require_trust_if_project(window)?;
}
blocking(move || {
let detected = ide_svn::detected_executable().map(|p| p.display().to_string());
let settings = ide_svn::Settings {
executable: (!executable.trim().is_empty()).then(|| PathBuf::from(executable.trim())),
..ide_svn::Settings::default()
};
let (version, error) = match ide_svn::SvnContext::new(settings).version() {
Ok((major, minor)) if (major, minor) < ide_svn::MIN_VERSION => (
Some(format!("{major}.{minor}")),
Some(format!(
"OpenIDEA needs Subversion {}.{} or later",
ide_svn::MIN_VERSION.0,
ide_svn::MIN_VERSION.1
)),
),
Ok((major, minor)) => (Some(format!("{major}.{minor}")), None),
Err(e) => (None, Some(e.message)),
};
Ok(SvnVersion { detected, version, error })
})
.await
}
/// Get from Version Control › Subversion: `svn checkout` of `url` into `dest`, with the
/// window's project settings when it has a project, the global ones otherwise. svn's progress
/// lines go to `on_output`; `cancel_request(request)` stops it (as Git's clone).
#[command(trust = always)]
pub async fn svn_checkout(
host: &Host,
window: &str,
request: ide_core::RequestId,
url: String,
dest: PathBuf,
on_output: crate::ops::Channel<String>,
) -> IdeResult<()> {
let project = host.project(window).ok();
let ctx = match project.as_ref().and_then(|p| p.svn.clone()) {
Some(ctx) => {
if let Some(p) = &project {
p.apply_svn_settings();
}
ctx
}
None => {
// No project yet: the global settings, and prompts in the window that asked.
let ctx = crate::svn::context(&(host.sink_for)(window), host.subversion == Some(true));
ctx.set_settings(crate::svn::settings(&host.global_settings.read_effective(|s| s.vcs.svn.clone())));
ctx
}
};
let cancel = host.begin_request(request);
let result = blocking(move || {
let report = |line: String| {
let _ = on_output.send(line);
};
WorkingCopy::checkout_reporting(&url, None, &dest, ide_svn::Depth::Infinity, ctx, &cancel, &report).map(|_| ())
})
.await;
host.end_request(request);
result
}
ide_command::domain!(
svn:
svn_accept_incoming_delete,
svn_checkout,
svn_cleanup,
svn_lock,
svn_properties,
svn_relocate,
svn_repository_info,
svn_set_property,
svn_unlock,
svn_version,
);
+24 -75
Переглянути файл
@@ -7,7 +7,19 @@ use ide_vcs::FileStatus;
#[command(trust = always)]
pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
let project = host.project(window)?;
host.blocking(move || merged_status(&project, None)).await
host.blocking(move || {
let settings = project.settings.effective();
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
repos.status()
})
.await
}
#[command(trust = always)]
@@ -30,82 +42,19 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult<Vec<FileS
pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<Vec<FileStatus>> {
// `paths` that belong to no repository are ignored, and an empty list is the full status.
let project = host.project(window)?;
host.blocking(move || merged_status(&project, Some(&paths))).await
}
/// The Git repositories' changes and those of the non-Git working copies, each file reported
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
/// everything). A working copy that cannot answer (an unreachable server) is logged and
/// skipped while another backend answered, so it never hides the Git changes.
/// The last status failure said for each working copy root (see [`merged_status`]).
static STATUS_FAILURES: parking_lot::Mutex<std::collections::BTreeMap<std::path::PathBuf, String>> =
parking_lot::Mutex::new(std::collections::BTreeMap::new());
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
let settings = project.settings.effective();
let repos = project.repos();
let backends = project.backends();
if repos.is_empty() && backends.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
let mut status = if repos.is_empty() {
Vec::new()
} else {
match paths {
Some(paths) => repos.status_paths(paths)?,
None => repos.status()?,
host.blocking(move || {
let settings = project.settings.effective();
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
}
};
if backends.is_empty() {
return Ok(status);
}
// Routed from these snapshots: one lookup per entry, no locks taken again.
let owner = |f: &FileStatus| crate::project::backend_for(&backends, &repos, &f.path).map(|b| b.root());
status.retain(|f| owner(f).is_none());
let mut answered = !repos.is_empty();
let mut failure = None;
for backend in &backends {
let changes = match paths.filter(|p| !p.is_empty()) {
Some(paths) => {
let mine: Vec<_> = paths.iter().filter(|p| p.starts_with(backend.root())).cloned().collect();
if mine.is_empty() {
answered = true;
continue;
}
backend.status_paths(&mine)
}
None => backend.status(),
};
match changes {
Ok(changes) => {
answered = true;
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
STATUS_FAILURES.lock().remove(backend.root());
}
Err(e) => {
tracing::warn!("status of {}: {e}", backend.root().display());
// Said once per root and message, not on every refresh: the Changes view would
// otherwise show that root as unchanged without a word.
let root = backend.root().to_path_buf();
if STATUS_FAILURES.lock().insert(root.clone(), e.message.clone()).as_ref() != Some(&e.message) {
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: format!("Changes of {} could not be read", root.display()),
body: Some(e.message.clone()),
});
}
failure = Some(e);
}
for r in repos.all() {
r.set_ignored_names(settings.ignored_names());
r.set_cli_status(settings.vcs.git.cli_status);
}
}
match failure {
Some(e) if !answered => Err(e),
_ => Ok(status),
}
repos.status_paths(&paths)
})
.await
}
pub mod commands;
+27 -302
Переглянути файл
@@ -94,14 +94,13 @@ async fn revision_text(
project: &Option<std::sync::Arc<Project>>,
external: &Option<std::sync::Arc<ide_vcs::Repo>>,
path: &Path,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
f: impl FnOnce(&ide_vcs::Repo) -> IdeResult<T>,
) -> IdeResult<T> {
match project {
Some(project) => project.with_log_backend_of(path, f),
Some(project) => project.with_log_repo_of(path, f),
None => f(external
.as_ref()
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
.as_ref()),
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?),
}
}
let (text_encoding, charset) = match &encoding {
@@ -149,46 +148,20 @@ impl LogAccess {
.with_log_repo_at(at, f)
}
/// The non-Git working copy `at` names (see [`Project::backend_at`]).
fn backend(&self, at: Option<&Path>) -> Option<std::sync::Arc<dyn Backend>> {
if self.external.is_some() {
return None;
}
self.project.as_ref().and_then(|p| p.backend_at(at))
}
/// `with_log_repo_at` through the backend-agnostic Changes-view surface.
fn with_log_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend(at) {
return f(backend.as_ref());
}
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
}
/// `with_log_repo_at` for a Git-only read: a non-Git working copy answers `T::default()`
/// (no refs, users, branches) so its log and branch widget still work.
fn with_git_log_or_default<T: Default>(
&self,
at: Option<&Path>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
if self.backend(at).is_some() {
return Ok(T::default());
}
self.with_log_repo_at(at, f)
}
}
/// A repository of the project (IDEA's VCS root).
#[derive(Default, Serialize, Deserialize, Type)]
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct VcsRoot {
/// Worktree root.
pub root: ide_core::IpcPath,
/// Root representing all mapped worktrees of the same Git repository in branch lists.
pub branch_root: ide_core::IpcPath,
/// The version control system holding it.
pub kind: VcsKind,
/// Merge / rebase / cherry-pick / revert in progress.
pub operation: Option<String>,
/// The current rebase uses Git's interactive mode.
@@ -217,10 +190,6 @@ pub struct VcsRoot {
/// Conflicts staged during the current operation that can be reopened.
#[serde(default)]
pub resolved_conflicts: Vec<ide_core::IpcPath>,
/// The repository's worktree or git directory is missing or on an unmounted volume.
#[serde(default)]
#[specta(optional)]
pub unavailable: bool,
}
#[derive(Clone, Serialize, Deserialize, Type)]
@@ -453,32 +422,14 @@ fn per_repo(
Ok(())
}
/// `per_repo` through the backend-agnostic Changes-view surface: the paths of a non-Git
/// working copy go to it, the rest to the Git repositories as before.
/// `per_repo` through the backend-agnostic Changes-view surface.
fn per_backend(
project: &Project,
paths: &[PathBuf],
recorded: Option<&str>,
f: impl Fn(&dyn Backend, &[PathBuf]) -> IdeResult<()>,
) -> IdeResult<()> {
let mut git: Vec<PathBuf> = Vec::new();
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
for path in paths {
match project.backend_of(path) {
Some(backend) => match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, mine)) => mine.push(path.clone()),
None => groups.push((backend, vec![path.clone()])),
},
None => git.push(path.clone()),
}
}
for (backend, mine) in &groups {
project.backend_recorded(backend.as_ref(), recorded, |b| f(b, mine))?;
}
if git.is_empty() && !groups.is_empty() {
return Ok(());
}
per_repo(project, &git, recorded, |r, paths| f(r as &dyn Backend, paths))
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
}
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
@@ -580,59 +531,29 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<Path
blocking(move || project.detected_repository_roots()).await
}
fn unavailable_vcs_root(root: &Path) -> VcsRoot {
VcsRoot {
root: root.into(),
branch_root: root.into(),
// Only Git repositories are mapped (Directory Mappings).
kind: VcsKind::Git,
operation: None,
interactive_rebase: false,
head: None,
head_commit: None,
shallow: false,
lfs: false,
uninitialized_submodules: Vec::new(),
has_remotes: None,
resolved_conflicts: Vec::new(),
unavailable: true,
}
}
/// The project's repositories, the primary one first.
#[command(trust = always)]
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
let project = host.project(window)?;
let repos = project.repos();
let backends = project.backends();
let trusted = project.is_trusted();
blocking(move || {
let primary = repos.primary().map(|r| r.root().to_path_buf());
let mut all: Vec<_> = repos.all().iter().collect();
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
let roots: Vec<_> = all
.into_iter()
.map(|repo| {
let dirs = repo.check_valid().ok().and_then(|()| repo.metadata_dirs().ok());
let available = dirs.is_some() && !repo.is_stale();
(repo, available, dirs)
})
.collect();
let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect();
let mut branch_roots = std::collections::HashMap::new();
for (repo, available, dirs) in &roots {
if *available && let Some([git_dir, common_dir]) = dirs {
for (repo, dirs) in &roots {
if let Some([git_dir, common_dir]) = dirs {
let first = branch_roots.entry(common_dir).or_insert(repo.root());
if git_dir == common_dir {
*first = repo.root();
}
}
}
let mut roots: Vec<VcsRoot> = roots
Ok(roots
.iter()
.map(|(r, available, dirs)| {
if !available {
return unavailable_vcs_root(r.root());
}
.map(|(r, dirs)| {
let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir));
let (head, head_commit) = r.head().unwrap_or_default();
let operation = r.operation().ok().flatten();
@@ -644,20 +565,14 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
.into_iter()
.map(Into::into)
.collect();
let has_remotes = trusted.then(|| r.has_remotes().ok()).flatten();
let shallow = r.is_shallow().unwrap_or(false);
if r.is_stale() {
return unavailable_vcs_root(r.root());
}
VcsRoot {
root: r.root().into(),
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
kind: VcsKind::Git,
operation,
interactive_rebase,
head,
head_commit,
shallow,
shallow: r.is_shallow().unwrap_or(false),
lfs: r.uses_lfs(),
uninitialized_submodules: r
.uninitialized_submodules()
@@ -665,21 +580,11 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
.iter()
.map(|path| ide_core::ipc_path::to_ipc(path))
.collect(),
has_remotes,
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
resolved_conflicts,
unavailable: false,
}
})
.collect();
// A non-Git working copy shows its own head (a stream, `trunk`) where Git shows the branch.
roots.extend(backends.iter().map(|b| VcsRoot {
root: b.root().into(),
branch_root: b.root().into(),
kind: b.kind(),
head: b.head_label(),
..VcsRoot::default()
}));
Ok(roots)
.collect())
})
.await
}
@@ -687,13 +592,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
#[command(trust = always)]
pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<BranchInfo> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return Ok(BranchInfo { head: backend.head_label(), ..BranchInfo::default() });
}
project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())
})
.await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
}
#[command(trust = trusted)]
@@ -964,9 +863,6 @@ pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: Lo
let cancel =
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
let result = blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return backend.log(&query, &cancel);
}
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
(r as &dyn Backend).log(&query, &cancel)
@@ -1004,13 +900,13 @@ pub async fn vcs_log_refs(
repo: Option<PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_refs())).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
}
#[command(trust = always)]
pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_users())).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_users())).await
}
#[command(trust = always)]
@@ -1040,7 +936,7 @@ pub async fn vcs_log_details(
revision: String,
) -> IdeResult<LogDetails> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_backend_at(repo.as_deref(), |b| b.log_details(&revision))).await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
}
#[command(trust = always)]
@@ -1054,9 +950,6 @@ pub async fn vcs_log_details_batch(
let project = LogAccess::new(host, window, repo.as_deref());
let cancel = host.begin_project_read_request(window, request);
let result = blocking(move || {
if let Some(backend) = project.backend(repo.as_deref()) {
return revisions.iter().map(|revision| backend.log_details(revision)).collect();
}
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
r.log_details_batch_cancellable(&revisions, &cancel)
@@ -1190,12 +1083,9 @@ pub async fn vcs_commit_selection_changes(
) -> IdeResult<Vec<RevisionChange>> {
let project = LogAccess::new(host, window, repo.as_deref());
let cancel = host.begin_project_read_request(window, request);
let result = blocking(move || match project.backend(repo.as_deref()) {
// Post-commit checks read what a commit changed, in a working copy of another system too.
Some(backend) => backend.commits_changes(&commits),
None => project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)),
})
.await;
let result =
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)))
.await;
host.end_request(request);
result
}
@@ -1203,23 +1093,13 @@ pub async fn vcs_commit_selection_changes(
#[command(trust = always)]
pub async fn vcs_branches(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || match project.backend(repo.as_deref()) {
Some(backend) => backend.branches(),
None => project.with_log_repo_at(repo.as_deref(), |r| r.branches()),
})
.await
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
}
#[command(trust = always)]
pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
let project = host.project(window)?;
blocking(move || {
if project.backend_at(repo.as_deref()).is_some() {
return Ok(Vec::new());
}
project.with_repo_at(repo.as_deref(), |r| r.stashes())
})
.await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
}
#[command(trust = trusted)]
@@ -1423,26 +1303,6 @@ pub async fn vcs_checkout(
let options = options.unwrap_or_default();
blocking(move || {
with_shelf_batch(&project, shelf_batch, || {
// A non-Git working copy switches to another line of development (`svn switch`).
if project.backend_at(repo.as_deref()).is_some() {
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
if create {
// New Branch in a Subversion working copy: Create Branch or Tag (`svn copy` on
// the server) to `branches/<name>`, or `tags/<name>` as typed, then switch to it.
let wc = crate::ops::svn::as_svn(b).ok_or_else(|| {
ide_core::IdeError::unavailable("creating a branch is not supported here")
})?;
let line = if branch.starts_with("branches/") || branch.starts_with("tags/") {
branch.clone()
} else {
format!("branches/{branch}")
};
wc.create_line(&line, &format!("Create {line}"), &ide_core::CancellationToken::new())?;
return b.switch_to(&line).map(|()| CheckoutOutcome::Done);
}
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
});
}
project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| {
r.checkout_with(&branch, create, &options)
})
@@ -1942,15 +1802,6 @@ pub async fn vcs_remote(
RemoteOp::PullLfs => Some("Git LFS pull"),
_ => None,
};
// Update Project on a non-Git working copy is its own update (`svn update`, `p4 sync`).
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
&& project.backend_at(repo.as_deref()).is_some()
{
return with_shelf_batch(&project, shelf_batch, || {
project
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
});
}
with_shelf_batch(&project, shelf_batch, || {
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
RemoteOp::Fetch { background: true, report, skip_remotes } => {
@@ -2081,14 +1932,8 @@ pub async fn vcs_update_branches(
#[command(trust = always)]
pub async fn vcs_conflict_versions(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_vcs::MergeVersions> {
let project = host.project(window)?;
blocking(move || {
project.with_backend_of(&path, |b| {
// Git reads the user's side from the index; a working copy without one, from the file.
let rev = if b.as_git().is_some() { ":2" } else { "WT" };
b.conflict_versions(&path, project.vcs_encoding(&path, Some(rev))?)
})
})
.await
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path, project.vcs_encoding(&path, Some(":2"))?)))
.await
}
#[command(trust = trusted)]
@@ -2104,7 +1949,8 @@ pub async fn vcs_accept_conflict_side(
ide_vcs::ConflictSide::Ours => "Accept yours",
ide_vcs::ConflictSide::Theirs => "Accept theirs",
};
blocking(move || per_backend(&project, &paths, Some(label), |b, paths| b.accept_conflict_side(paths, side))).await
blocking(move || per_repo(&project, &paths, Some(label), |repo, paths| repo.accept_conflict_side(paths, side)))
.await
}
#[command(trust = trusted)]
@@ -2115,23 +1961,6 @@ pub async fn vcs_revert_resolved(host: &Host, window: &str, paths: Vec<PathBuf>)
.await
}
/// Marks the conflicts of `paths` resolved with the files as they are (the merge editor
/// saved its result): `git add`, `svn resolve --accept working`.
#[command(trust = trusted)]
pub async fn vcs_mark_resolved(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || per_backend(&project, &paths, Some("Mark resolved"), |b, paths| b.mark_resolved(paths))).await
}
/// The conflicts of `path` the merge editor does not show (property and tree conflicts of
/// a Subversion working copy); none for a Git repository.
#[command(trust = always)]
pub async fn vcs_conflict_details(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<ide_vcs::ConflictDetail>> {
let project = host.project(window)?;
blocking(move || project.with_backend_of(&path, |b| b.conflict_details(&path))).await
}
#[command(trust = always)]
pub async fn vcs_diff_text(host: &Host, window: &str, path: PathBuf, staged: bool) -> IdeResult<String> {
let project = host.project(window)?;
@@ -3407,103 +3236,6 @@ pub async fn vcs_shelf_import(
.await
}
/// The changelists the non-Git working copy at `repo` keeps itself; `None` when the root
/// (Git) leaves them to the IDE's lists ([`vcs_changelists_load`]).
#[command(trust = trusted)]
pub async fn vcs_backend_changelists(
host: &Host,
window: &str,
repo: Option<PathBuf>,
) -> IdeResult<Option<Vec<BackendChangelist>>> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || match project.backend_at(repo.as_deref()) {
Some(backend) => backend.changelists(),
None => Ok(None),
})
.await
}
/// Creates a changelist of the working copy at `repo`; returns its id.
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_create(
host: &Host,
window: &str,
repo: Option<PathBuf>,
name: String,
comment: String,
) -> IdeResult<String> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
let id = project.with_backend_at(repo.as_deref(), |b| b.create_changelist(&name, &comment))?;
project.vcs_changed();
Ok(id)
})
.await
}
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_edit(
host: &Host,
window: &str,
repo: Option<PathBuf>,
id: String,
name: String,
comment: String,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_backend_at(repo.as_deref(), |b| b.edit_changelist(&id, &name, &comment))?;
project.vcs_changed();
Ok(())
})
.await
}
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_delete(
host: &Host,
window: &str,
repo: Option<PathBuf>,
id: String,
) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
project.with_backend_at(repo.as_deref(), |b| b.delete_changelist(&id))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Moves `paths` to changelist `id` of the working copy each belongs to.
#[command(trust = trusted)]
pub async fn vcs_backend_changelist_move(host: &Host, window: &str, paths: Vec<PathBuf>, id: String) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
for path in paths {
let backend = project.backend_of(&path).ok_or_else(|| {
ide_core::IdeError::invalid(format!("{} is not in a working copy with changelists", path.display()))
})?;
match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, mine)) => mine.push(path),
None => groups.push((backend, vec![path])),
}
}
for (backend, mine) in &groups {
backend.move_to_changelist(mine, &id)?;
}
project.vcs_changed();
Ok(())
})
.await
}
#[command(trust = always)]
pub async fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
let project = host.project(window)?;
@@ -3587,11 +3319,6 @@ ide_command::domain!(
vcs_branch_info,
vcs_check_incoming,
vcs_branches,
vcs_backend_changelists,
vcs_backend_changelist_create,
vcs_backend_changelist_edit,
vcs_backend_changelist_delete,
vcs_backend_changelist_move,
vcs_changelists_load,
vcs_changelists_save,
vcs_checkout,
@@ -3619,8 +3346,6 @@ ide_command::domain!(
vcs_conflict_versions,
vcs_accept_conflict_side,
vcs_revert_resolved,
vcs_mark_resolved,
vcs_conflict_details,
vcs_create_branch,
vcs_undo_branch_creation,
vcs_create_patch,
+10 -156
Переглянути файл
@@ -1,9 +1,8 @@
//! Code insight for Xcode projects: sourcekit-lsp doesn't read `.xcodeproj` / `.xcworkspace`
//! files, it gets their build settings from a Build Server Protocol server named in
//! `.bsp/*.json` or the legacy `buildServer.json`. The IDE neither bundles nor installs a BSP
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
//! `.git/info/exclude`, then restarts sourcekit-lsp.
//! server: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
//! the config, then restarts sourcekit-lsp.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
@@ -15,68 +14,14 @@ use std::process::{Command, Stdio};
/// The generators, in order of preference, and their arguments for `container`.
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<String> {
fn tool_args(tool: &str, container: &str) -> Vec<String> {
if tool == "sourcekit-xcode-bsp" {
// Detects the workspace or project in the working directory itself.
return vec!["init".into()];
}
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
// Without `-scheme` it binds the scheme built last.
let mut args: Vec<String> = vec!["config".into(), flag.into(), container.into()];
if let Some(dir) = build_root {
args.extend(["--build_root".into(), dir.to_string_lossy().into_owned()]);
}
args
}
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let mut cmd = Command::new("xcodebuild");
ide_core::process::prepare(&mut cmd)
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
.current_dir(root)
.stdin(Stdio::null())
.stderr(Stdio::null());
let out = cmd.output().ok().filter(|o| o.status.success())?;
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
}
/// The config `tool` writes at the project root.
fn config_name(tool: &str) -> &'static str {
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
}
fn git(root: &Path, args: &[&str]) -> Option<std::process::Output> {
let mut cmd = Command::new("git");
ide_core::process::prepare(&mut cmd).arg("-C").arg(root).args(args).stdin(Stdio::null());
cmd.output().ok()
}
/// Adds `name` (a file or folder at `root`) to the repository's `info/exclude`, so a generated
/// machine-specific config doesn't show up as a change. Nothing when `root` isn't in a Git
/// repository or `name` is already tracked or ignored. Returns whether it added the line.
fn exclude_from_git(root: &Path, name: &str) -> std::io::Result<bool> {
let ok = |args: &[&str]| git(root, args).filter(|o| o.status.success());
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_owned();
let Some(exclude) = ok(&["rev-parse", "--git-path", "info/exclude"]).map(text) else { return Ok(false) };
let prefix = ok(&["rev-parse", "--show-prefix"]).map(text).unwrap_or_default();
if ok(&["ls-files", "--error-unmatch", "--", name]).is_some() || ok(&["check-ignore", "-q", "--", name]).is_some() {
return Ok(false);
}
let exclude = root.join(exclude);
if let Some(dir) = exclude.parent() {
std::fs::create_dir_all(dir)?;
}
let before = std::fs::read_to_string(&exclude).unwrap_or_default();
let sep = if before.is_empty() || before.ends_with('\n') { "" } else { "\n" };
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&exclude)?;
std::io::Write::write_all(&mut file, format!("{sep}/{prefix}{name}\n").as_bytes())?;
Ok(true)
vec!["config".into(), flag.into(), container.into()]
}
/// An Xcode project without a BSP config, at the project root.
@@ -124,8 +69,8 @@ pub fn xcode_bsp_setup(host: &Host, window: &str) -> IdeResult<Option<XcodeBspSe
Ok(Some(XcodeBspSetup { container, tool }))
}
/// Writes the BSP config at the project root with `tool`, adds it to `.git/info/exclude`
/// ([`exclude_from_git`]), then restarts the project's sourcekit-lsp so it reads it.
/// Writes the BSP config at the project root with `tool`, then restarts the project's
/// sourcekit-lsp so it reads it.
#[command(trust = trusted)]
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
if !TOOLS.contains(&tool.as_str()) {
@@ -142,17 +87,12 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
.ok_or_else(|| IdeError::unavailable(format!("{tool} is not installed")))?;
let mut cmd = Command::new(exe);
ide_core::process::prepare(&mut cmd)
// An absolute path: with `--build_root` it is written to the config as given.
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
.args(tool_args(&tool, &container))
.current_dir(&root)
.env("PATH", &search)
.stdin(Stdio::null());
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
if out.status.success() {
// Best effort: a config that shows up in `git status` is a nuisance, not a failure.
if let Err(e) = exclude_from_git(&root, config_name(&tool)) {
tracing::warn!("could not add {} to .git/info/exclude: {e}", config_name(&tool));
}
return Ok(());
}
let stderr = String::from_utf8_lossy(&out.stderr);
@@ -191,95 +131,9 @@ mod tests {
#[test]
fn passes_the_container_to_xcode_build_server() {
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace", None), ["config", "-workspace", "A.xcworkspace"]);
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj", None), ["config", "-project", "A.xcodeproj"]);
let dd = Path::new("/Users/me/Library/Developer/Xcode/DerivedData/A-abc");
assert_eq!(
tool_args("xcode-build-server", "A.xcworkspace", Some(dd)),
[
"config",
"-workspace",
"A.xcworkspace",
"--build_root",
"/Users/me/Library/Developer/Xcode/DerivedData/A-abc"
]
);
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj", Some(dd)), ["init"]);
}
fn git_in(dir: &Path, args: &[&str]) {
let out = Command::new("git").arg("-C").arg(dir).args(args).output().unwrap();
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
}
fn exclude_file(repo: &Path) -> String {
std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap_or_default()
}
#[test]
fn excludes_the_generated_config_from_git_once() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
git_in(repo, &["init", "-q"]);
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
assert!(exclude_from_git(repo, "buildServer.json").unwrap());
assert!(exclude_file(repo).ends_with("\n/buildServer.json\n"), "{}", exclude_file(repo));
// Now ignored: not added twice.
assert!(!exclude_from_git(repo, "buildServer.json").unwrap());
assert_eq!(exclude_file(repo).matches("buildServer.json").count(), 1);
// sourcekit-xcode-bsp's folder.
std::fs::create_dir(repo.join(".bsp")).unwrap();
std::fs::write(repo.join(".bsp/x.json"), "{}").unwrap();
assert!(exclude_from_git(repo, config_name("sourcekit-xcode-bsp")).unwrap());
assert!(exclude_file(repo).ends_with("/buildServer.json\n/.bsp\n"));
}
#[test]
fn leaves_tracked_and_ignored_configs_and_non_repos_alone() {
let tmp = tempfile::tempdir().unwrap();
// Not a Git repository: nothing to do, no `.git` created.
let plain = tmp.path().join("plain");
std::fs::create_dir(&plain).unwrap();
assert!(!exclude_from_git(&plain, "buildServer.json").unwrap());
assert!(!plain.join(".git").exists());
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git_in(&repo, &["init", "-q"]);
let before = exclude_file(&repo);
// Tracked: the team shares it.
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
git_in(&repo, &["add", "buildServer.json"]);
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
// Already in .gitignore.
git_in(&repo, &["rm", "-q", "--cached", "buildServer.json"]);
std::fs::write(repo.join(".gitignore"), "buildServer.json\n").unwrap();
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
assert_eq!(exclude_file(&repo), before);
}
#[test]
fn excludes_the_config_of_a_project_in_a_subfolder_of_the_repository() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
git_in(repo, &["init", "-q"]);
let ios = repo.join("apps/ios");
std::fs::create_dir_all(&ios).unwrap();
assert!(exclude_from_git(&ios, "buildServer.json").unwrap());
assert!(exclude_file(repo).ends_with("/apps/ios/buildServer.json\n"));
std::fs::write(ios.join("buildServer.json"), "{}").unwrap();
// The line matches the file in the subfolder only.
git_in(&ios, &["check-ignore", "-q", "buildServer.json"]);
assert!(
Command::new("git")
.arg("-C")
.arg(repo)
.args(["check-ignore", "-q", "buildServer.json"])
.status()
.unwrap()
.code()
== Some(1)
);
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace"), ["config", "-workspace", "A.xcworkspace"]);
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj"), ["config", "-project", "A.xcodeproj"]);
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
}
#[test]
+6 -35
Переглянути файл
@@ -118,50 +118,21 @@ impl PluginHost {
.find(|(p, n, _)| p == plugin && n == tool)
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
let arguments = arguments_for(&declared.input_schema, args)?;
let tool = tool.to_owned();
let validator =
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
rt.mcp_call(&tool, &arguments, inv)
})
}
}
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
/// server routes a call by; a schema that refuses it gets the call without it.
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args)
&& let Some(args) = args.as_object_mut()
{
args.remove(crate::mcp::PROJECT_PATH);
}
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
Ok(args.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
let strict = serde_json::json!({
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
});
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
// Declared through a local `$ref` and required: the plugin keeps it.
let declared = serde_json::json!({
"$ref": "#/$defs/call",
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
});
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
assert_eq!(kept["projectPath"], "/work/inventory");
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
}
#[test]
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
let tmp = tempfile::tempdir().unwrap();
+5 -15
Переглянути файл
@@ -760,11 +760,6 @@ impl PluginHost {
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
.map(|(id, _)| id.clone())
.collect();
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
// plugins again, and listing restricts an untrusted project again, which looped while idle.
if ids.is_empty() {
return;
}
for id in ids {
self.unload(&id);
}
@@ -3008,16 +3003,11 @@ impl PluginHost {
{
let mut plugins = self.plugins.write();
if let Some(existing) = plugins.get(&id) {
// Every rescan meets the same duplicate again: say it once per directory, not on each scan.
static WARNED: std::sync::LazyLock<Mutex<std::collections::HashSet<(String, PathBuf)>>> =
std::sync::LazyLock::new(Default::default);
if WARNED.lock().insert((id.clone(), dir.to_path_buf())) {
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
}
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
return (id, None);
}
plugins.insert(id.clone(), plugin.clone());
+22 -350
Переглянути файл
@@ -9,7 +9,7 @@ use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
use ide_lsp::LspManager;
use ide_syntax::StructureService;
use ide_text::{AppliedChange, ByteEdit};
use ide_vcs::{Backend, BackendProvider, FileStatus, Repo, Repos};
use ide_vcs::{Backend, Repo, Repos};
use ide_vfs::Watcher;
use ide_workspace::documents::DocumentObserver;
use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder};
@@ -41,21 +41,6 @@ pub struct Project {
pub lsp: Arc<LspManager>,
/// Git repositories: the one containing the project root and those nested below it.
pub repos: Arc<RwLock<Repos>>,
/// Working copies of the other version control systems ([`Host::with_vcs_provider`]) holding
/// the project root or a content root. Found in a trusted project only: answering may run
/// the system's client, and a `P4CONFIG` can name a program as its server.
pub backends: Arc<RwLock<Vec<Arc<dyn Backend>>>>,
pub(crate) vcs_providers: Arc<[Arc<dyn BackendProvider>]>,
/// Held for a whole scan of `backends`, so overlapping scans (project open, trust change)
/// finish in turn and the last one reads the current trust.
backend_scan: Arc<Mutex<()>>,
/// Folders with a working-copy marker that a scan did not make roots (svn missing, a format
/// it cannot read), with the marker's time then: saving files there does not scan again
/// until the marker or the svn settings change.
unresolved_markers: Arc<Mutex<HashMap<PathBuf, Option<std::time::SystemTime>>>>,
/// How svn runs for this project (Settings › Version Control › Subversion, its prompts);
/// `None` without Subversion support.
pub svn: Option<Arc<ide_svn::SvnContext>>,
/// Explicitly opened external logs remain read-only and outside project indexing.
pub(crate) external_log_repos: RwLock<Vec<Arc<Repo>>>,
/// Incrementally maintained syntax trees of the open documents.
@@ -401,12 +386,8 @@ impl Host {
}));
}
{
// Weak: `documents` keeps `lsp` alive through its observers, so a strong handle here would be
// a cycle that leaks every closed project's documents, registry and language manager.
let documents = Arc::downgrade(&documents);
lsp.set_apply_edit_hook(Box::new(move |edit| {
documents.upgrade().is_some_and(|documents| documents.apply_workspace_edit(&edit).is_ok())
}));
let documents = documents.clone();
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
}
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
@@ -444,19 +425,6 @@ impl Host {
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
let backends: Arc<RwLock<Vec<Arc<dyn Backend>>>> = Arc::default();
// Subversion's settings and prompts belong to this project (and its window).
let svn = self.subversion.map(|prompts| crate::svn::context(&sink, prompts));
if let Some(ctx) = &svn {
ctx.set_settings(crate::svn::settings(&settings.read_effective(|s| s.vcs.svn.clone())));
}
let mut providers = self.vcs_providers.clone();
if let Some(ctx) = &svn {
providers.push(Arc::new(ide_svn::Provider::new(ctx.clone())));
}
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = providers.into();
let backend_scan: Arc<Mutex<()>> = Arc::default();
let unresolved_markers: Arc<Mutex<HashMap<PathBuf, Option<std::time::SystemTime>>>> = Arc::default();
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
@@ -495,9 +463,6 @@ impl Host {
let build_cache = build_cache.clone();
let notify_watch_exhausted = notify_watch_exhausted.clone();
let watcher_weak = watcher_weak.clone();
let (backends, vcs_providers, backend_scan, unresolved_markers) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), unresolved_markers.clone());
let markers: Vec<String> = vcs_providers.iter().filter_map(|p| p.marker().map(str::to_owned)).collect();
Watcher::start(
&root.clone(),
excludes.clone(),
@@ -600,21 +565,6 @@ impl Host {
.collect();
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
});
// `git worktree add` writes the worktree's gitfile before its gitdir's
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
// rescans too while its worktree is unknown and one a rescan would find.
git_dirs |= batch.vcs.iter().any(|p| {
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
return false;
}
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
})
});
// A repository folder moved or restored into the project: no `.git` event is
// written inside it before the watcher sees the new directory, its creation is
// the signal. A `git clone` / `git init` inside the project already arrives
@@ -635,53 +585,6 @@ impl Host {
if git_dirs || vcs_moved {
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
// A working copy appeared below the project (a checkout made inside it, a
// folder moved in) or one went: its marker is the signal, as `.git` is above.
// The marker itself may be an ignored name, so the folders of created paths
// are checked for it. The scan asks providers, so it runs off this thread.
if !markers.is_empty() && trusted.load(Ordering::Acquire) {
let known: Vec<PathBuf> = backends.read().iter().map(|b| b.root().to_path_buf()).collect();
let mut folders: HashSet<&Path> = HashSet::new();
for p in &batch.created {
let is_marker = p.file_name().is_some_and(|n| markers.iter().any(|m| n == m.as_str()));
folders.extend(if !is_marker && p.is_dir() { Some(p.as_path()) } else { p.parent() });
}
let fresh: Vec<PathBuf> = folders
.iter()
.filter(|d| !known.iter().any(|r| r == *d) && markers.iter().any(|m| d.join(m).exists()))
.filter(|d| unresolved_markers.lock().get(**d) != Some(&marker_time(d, &markers)))
.map(|d| d.to_path_buf())
.collect();
let gone = batch.removed.iter().any(|p| known.iter().any(|r| r.starts_with(p)));
if !fresh.is_empty() || gone {
let (backends, providers, lock, trust) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), trusted.clone());
let (unresolved, markers) = (unresolved_markers.clone(), markers.clone());
let (root, settings, sink, cache) =
(root.clone(), settings.clone(), sink.clone(), build_cache.clone());
let rescan = move || {
let scan = BackendScan {
backends: &backends,
providers: &providers,
lock: &lock,
trusted: &trust,
};
scan.run(&root, &settings, &sink, &cache);
// Still no root there: not asked again until its marker changes.
let known: Vec<PathBuf> =
backends.read().iter().map(|b| b.root().to_path_buf()).collect();
let mut unresolved = unresolved.lock();
for d in fresh.into_iter().filter(|d| !known.contains(d)) {
let time = marker_time(&d, &markers);
unresolved.insert(d, time);
}
};
if let Err(e) = std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(rescan)
{
tracing::warn!("looking for working copies again: {e}");
}
}
}
// A watch limit hit after startup (per-directory mode, Linux):
// folders past the limit never sync — surface it once, like
// the polling fallback below (#1915). The check itself is
@@ -763,14 +666,9 @@ impl Host {
{
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
let (backends, providers, trust) = (backends.clone(), vcs_providers.clone(), trusted.clone());
let scan = backend_scan.clone();
let trusted = trusted.load(Ordering::Acquire);
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted);
let backend_scan =
BackendScan { backends: &backends, providers: &providers, lock: &scan, trusted: &trust };
backend_scan.run(&root, &settings, &sink, &build_cache);
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
})?;
}
mark("git");
@@ -811,11 +709,6 @@ impl Host {
index,
lsp,
repos,
backends,
vcs_providers,
backend_scan,
unresolved_markers,
svn,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
@@ -1117,11 +1010,6 @@ impl Host {
index,
lsp,
repos: Arc::default(),
backends: Arc::default(),
vcs_providers: Arc::new([]),
backend_scan: Arc::default(),
unresolved_markers: Arc::default(),
svn: None,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
@@ -1160,16 +1048,17 @@ impl Host {
}
}
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
impl Project {
pub fn is_trusted(&self) -> bool {
self.trusted.load(Ordering::Acquire)
}
pub fn require_trust(&self) -> IdeResult<()> {
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
if self.is_trusted() {
Ok(())
} else {
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
}
}
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
@@ -1297,127 +1186,18 @@ fn detect_repositories(
build_cache: &Path,
trusted: bool,
) -> IdeResult<Repos> {
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &repository_scan_skips(settings))
}
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
let ignored = settings.ignored_names();
move |p: &Path| {
let skip = |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
ignored.is_ignored_name(&name)
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
&& p.parent().is_some_and(ide_workspace::unity::is_project))
})
}
}
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
settings.vcs.git.enabled
&& !settings
.vcs
.mappings
.excluded
.iter()
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
/// When `dir`'s working-copy marker last changed.
fn marker_time(dir: &Path, markers: &[String]) -> Option<std::time::SystemTime> {
markers.iter().find_map(|m| dir.join(m).metadata().and_then(|m| m.modified()).ok())
}
/// Asks `providers` in order about `folder`; the first to answer adds its working copy to
/// `found`, unless one with the same root is there already.
fn ask_providers<'a>(
folder: &Path,
providers: impl IntoIterator<Item = &'a Arc<dyn BackendProvider>>,
found: &mut Vec<Arc<dyn Backend>>,
) {
for provider in providers {
match provider.discover(folder) {
Ok(Some(backend)) => {
if !found.iter().any(|b| b.root() == backend.root()) {
found.push(backend);
}
return;
}
Ok(None) => {}
Err(e) => tracing::warn!("looking for a working copy in {}: {e}", folder.display()),
}
}
}
/// The working copy among `backends` that `path` belongs to ([`Project::backend_of`]): the
/// deepest one holding it, unless a Git repository at or below its root holds the path.
pub(crate) fn backend_for<'a>(
backends: &'a [Arc<dyn Backend>],
repos: &Repos,
path: &Path,
) -> Option<&'a Arc<dyn Backend>> {
let backend =
backends.iter().filter(|b| path.starts_with(b.root())).max_by_key(|b| b.root().components().count())?;
let nested_git = repos.for_path(path).is_some_and(|r| r.root().starts_with(backend.root()));
(!nested_git).then_some(backend)
}
/// What a scan of the non-Git working copies works on: the list it replaces, the providers
/// asked, the lock that serialises scans and the project's trust, read under that lock.
struct BackendScan<'a> {
backends: &'a RwLock<Vec<Arc<dyn Backend>>>,
providers: &'a [Arc<dyn BackendProvider>],
lock: &'a Mutex<()>,
trusted: &'a AtomicBool,
}
impl BackendScan<'_> {
/// Asks the providers for the working copies holding the project root and its content
/// roots; emits `VcsChanged` when the set changed. An untrusted project gets none and runs
/// nothing. Scans run one at a time, each reading the trust when it starts, so a scan
/// started before a trust change can't overwrite the one after it. Providers are asked in
/// registration order and the first to answer for a folder wins it.
fn run(&self, root: &Path, settings: &SettingsStore, sink: &SharedSink, build_cache: &Path) {
let _scan = self.lock.lock();
let trusted = self.trusted.load(Ordering::Acquire);
let mut found: Vec<Arc<dyn Backend>> = Vec::new();
if trusted && !self.providers.is_empty() {
let settings = settings.effective();
let mut folders = vec![root.to_path_buf()];
folders.extend(content_roots(&settings, root, build_cache, trusted));
let markers: Vec<&str> = self.providers.iter().filter_map(|p| p.marker()).collect();
let skip = repository_scan_skips(&settings);
for folder in &folders {
// The folder itself (its working copy may start above it): every provider.
if !found.iter().any(|b| folder.starts_with(b.root())) {
ask_providers(folder, self.providers, &mut found);
}
// Working copies nested below it, like nested Git repositories: a separate
// checkout or a directory external inside a working copy, or one inside a Git
// repository. Only the providers whose marker the folder holds are asked.
if markers.is_empty() {
continue;
}
for nested in ide_vcs::marked_folders(folder, &markers, &skip) {
if found.iter().any(|b| b.root() == nested) {
continue;
}
let marked = self.providers.iter().filter(|p| p.marker().is_some_and(|m| nested.join(m).exists()));
ask_providers(&nested, marked, &mut found);
}
}
}
let roots =
|list: &[Arc<dyn Backend>]| list.iter().map(|b| (b.kind(), b.root().to_path_buf())).collect::<Vec<_>>();
if roots(&found) != roots(&self.backends.read()) {
*self.backends.write() = found;
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
}
}
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &skip)
}
impl Project {
@@ -1437,74 +1217,6 @@ impl Project {
&self.build_cache_dir(),
self.is_trusted(),
);
self.refresh_backends();
}
/// Looks for the non-Git working copies again: they are found in a trusted project only,
/// so trusting it (or restricting it) changes the answer.
pub fn refresh_backends(&self) {
self.apply_svn_settings();
self.unresolved_markers.lock().clear();
let scan = BackendScan {
backends: &self.backends,
providers: &self.vcs_providers,
lock: &self.backend_scan,
trusted: &self.trusted,
};
scan.run(&self.root, &self.settings, &self.sink, &self.build_cache_dir());
}
/// Settings › Version Control › Subversion as this project has them, for its next svn
/// command. An untrusted project's own svn settings never run (as with its Git executable):
/// the global ones apply. Written only when they changed.
pub fn apply_svn_settings(&self) {
let Some(ctx) = &self.svn else { return };
let svn = if self.is_trusted() {
self.settings.read_effective(|s| s.vcs.svn.clone())
} else {
self.settings.layer(ide_workspace::settings::SettingsScope::Global).vcs.svn
};
let next = crate::svn::settings(&svn);
if ctx.settings() != next {
ctx.set_settings(next);
// Another svn may read the folders this one could not.
self.unresolved_markers.lock().clear();
}
}
/// Tells the UI that what version control reports changed without a file event (a file
/// was opened for edit).
pub fn vcs_changed(&self) {
self.sink.emit(IdeEvent::VcsChanged { root: self.root.clone().into() });
}
/// The project's non-Git working copies; none while it is in Restricted Mode. A working
/// copy rooted where a Git repository is (a folder with both `.git` and `.svn`) is left to
/// Git, so each root is reported once.
pub fn backends(&self) -> Vec<Arc<dyn Backend>> {
if !self.is_trusted() {
return Vec::new();
}
self.apply_svn_settings();
let repos = self.repos.read();
self.backends.read().iter().filter(|b| repos.at_root(b.root()).is_none()).cloned().collect()
}
/// The non-Git working copy `path` belongs to: the deepest one holding it, unless a Git
/// repository at or below that working copy's root holds the path (a Git checkout inside
/// a Perforce workspace stays Git's).
pub fn backend_of(&self, path: &Path) -> Option<Arc<dyn Backend>> {
backend_for(&self.backends(), &self.repos.read(), path).cloned()
}
/// The non-Git working copy rooted at `at`; without `at`, the first one of a project that
/// has no Git repository, where Git would use its primary repository.
pub fn backend_at(&self, at: Option<&Path>) -> Option<Arc<dyn Backend>> {
match at {
Some(root) => self.backends().into_iter().find(|b| b.root() == root),
None if self.repos.read().is_empty() => self.backends().into_iter().next(),
None => None,
}
}
/// Settings › Version Control › Git › Enable Git integration (effective value).
@@ -1606,12 +1318,8 @@ impl Project {
}
}
/// Runs `f` with the backend `path` belongs to: its non-Git working copy, else its Git
/// repository.
/// `with_repo_of` through the backend-agnostic Changes-view surface.
pub fn with_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_of(path) {
return f(backend.as_ref());
}
self.with_repo_of(path, |r| f(r as &dyn Backend))
}
@@ -1627,12 +1335,8 @@ impl Project {
f(repo)
}
/// `with_repo_at` through the backend-agnostic Changes-view surface; `at` may name a
/// non-Git working copy ([`Self::backend_at`]).
/// `with_repo_at` through the backend-agnostic Changes-view surface.
pub fn with_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_at(at) {
return f(backend.as_ref());
}
self.with_repo_at(at, |r| f(r as &dyn Backend))
}
@@ -1642,43 +1346,22 @@ impl Project {
at: Option<&Path>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
if let Some(backend) = self.backend_at(at) {
return f(backend.as_ref());
}
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
}
/// `with_log_repo_of` through the backend-agnostic Changes-view surface.
pub fn with_log_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
if let Some(backend) = self.backend_of(path) {
return f(backend.as_ref());
}
self.with_log_repo_of(path, |r| f(r as &dyn Backend))
}
/// `with_repo_recorded` through the backend-agnostic Changes-view surface: a non-Git
/// working copy's operation (update, revert…) gets the same Local History labels and
/// snapshots.
/// `with_repo_recorded` through the backend-agnostic Changes-view surface.
pub fn with_backend_recorded<T>(
&self,
at: Option<&Path>,
operation: Option<&str>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
match self.backend_at(at) {
Some(backend) => self.backend_recorded(backend.as_ref(), operation, f),
None => self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend)),
}
}
/// [`Self::with_backend_recorded`] for a working copy already looked up.
pub fn backend_recorded<T>(
&self,
backend: &dyn Backend,
operation: Option<&str>,
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
) -> IdeResult<T> {
self.recorded(operation, || backend.status(), || f(backend))
self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend))
}
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
@@ -1703,27 +1386,16 @@ impl Project {
operation: Option<&str>,
f: impl FnOnce(&Repo) -> IdeResult<T>,
) -> IdeResult<T> {
self.recorded(operation, || self.with_repo_at(at, Backend::status), || self.with_repo_at(at, f))
}
/// Runs `run` with the Local History labels and snapshots of [`Self::with_repo_recorded`]:
/// `changed` lists the files to snapshot.
fn recorded<T>(
&self,
operation: Option<&str>,
changed: impl FnOnce() -> IdeResult<Vec<FileStatus>>,
run: impl FnOnce() -> IdeResult<T>,
) -> IdeResult<T> {
let Some(name) = operation else { return self.with_disk_sync(run) };
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
self.history_label(&format!("Before {name}"));
if let Ok(changed) = changed() {
if let Ok(changed) = self.with_backend_at(at, |r| r.status()) {
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
if let Err(e) = self.history.record_file(&file.path, &format!("Before {name}"), false) {
tracing::debug!("local history: {e}");
}
}
}
let result = self.with_disk_sync(run);
let result = self.with_disk_sync(|| self.with_repo_at(at, f));
self.history_label(&format!("After {name}"));
result
}
@@ -1955,7 +1627,7 @@ impl Project {
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
}
let bytes = self.with_log_backend_of(path, |b| b.file_bytes_at(path, rev))?.unwrap_or_default();
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
Ok(self.documents.detect_encoding(path, &bytes))
}
-1
Переглянути файл
@@ -500,7 +500,6 @@ mod tests {
subject: "rm -rf".into(),
project: "/srv/app".into(),
detail: None,
background: false,
};
let update = ide_core::updates::UpdateInfo {
version: "9.9.9".into(),
-147
Переглянути файл
@@ -1,147 +0,0 @@
//! Subversion in a project: its [`SvnContext`] (Settings › Version Control ›
//! Subversion as the project has them) and svn's prompts shown in the
//! project's window through the askpass dialog (`IdeEvent::Askpass`, answered
//! with `ssh_askpass_answer`).
use ide_core::IdeEvent;
use ide_core::event::{AskpassKind, SharedSink};
use ide_svn::{Prompt, PromptHandler, Settings, SvnContext};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::time::Duration;
/// Prompt ids of svn, apart from those the askpass server hands out (counting from 1).
static NEXT_ID: AtomicU64 = AtomicU64::new(1 << 48);
static PENDING: Mutex<Option<HashMap<u64, mpsc::Sender<Option<String>>>>> = Mutex::new(None);
/// How long a prompt waits for the user before the command is cancelled.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// Delivers the answer to svn prompt `id`; false when no svn command waits for it.
pub fn answer_prompt(id: u64, answer: Option<String>) -> bool {
match PENDING.lock().as_mut().and_then(|p| p.remove(&id)) {
Some(tx) => tx.send(answer).is_ok(),
None => false,
}
}
/// The context of a new project: prompts open in its window when `prompts`.
pub(crate) fn context(sink: &SharedSink, prompts: bool) -> Arc<SvnContext> {
let ctx = Arc::new(SvnContext::new(Settings::default()));
if prompts {
ctx.set_prompt_handler(Some(Arc::new(WindowPrompts { sink: sink.clone() })));
}
ctx
}
/// The svn run settings from a project's `vcs.svn`; `svn+ssh://` passphrases go to
/// the app's askpass like git's.
pub(crate) fn settings(svn: &ide_core::workflow_settings::SvnSettings) -> Settings {
let path = |s: &str| (!s.trim().is_empty()).then(|| PathBuf::from(s.trim()));
Settings {
executable: path(&svn.executable),
interactive: svn.interactive,
config_dir: if svn.use_custom_config_dir { path(&svn.config_dir) } else { None },
env: ide_vcs::askpass_env(),
}
}
struct WindowPrompts {
sink: SharedSink,
}
impl PromptHandler for WindowPrompts {
fn answer(&self, prompt: &Prompt) -> Option<String> {
let (text, kind) = describe(prompt);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::channel();
PENDING.lock().get_or_insert_default().insert(id, tx);
self.sink.emit(IdeEvent::Askpass { id, prompt: text, kind, remember: false });
let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten();
if let Some(pending) = PENDING.lock().as_mut() {
pending.remove(&id);
}
self.sink.emit(IdeEvent::AskpassDone { id });
reply(prompt, answer?)
}
}
/// The dialog's text and input for a prompt.
pub(crate) fn describe(prompt: &Prompt) -> (String, AskpassKind) {
let realm = |realm: &str| if realm.is_empty() { String::new() } else { format!(" ({realm})") };
match prompt {
Prompt::Username { realm: r } => (format!("Subversion username{}:", realm(r)), AskpassKind::Text),
Prompt::Password { realm: r, username } => {
(format!("Subversion password for '{username}'{}:", realm(r)), AskpassKind::Secret)
}
Prompt::ClientCertificate { realm: r } => (format!("Client certificate file{}:", realm(r)), AskpassKind::Text),
Prompt::ClientCertificatePassphrase { file, .. } => {
(format!("Passphrase for client certificate '{file}':"), AskpassKind::Secret)
}
Prompt::ServerCertificate { details, permanent, .. } => {
let keep = if *permanent { "Trust it and remember the choice?" } else { "Trust it for this command?" };
(format!("{details}\n\n{keep}"), AskpassKind::Confirm)
}
Prompt::StorePlaintext { details } => {
(format!("{details}\n\nStore the password unencrypted?"), AskpassKind::Confirm)
}
}
}
/// What svn reads for the dialog's answer: a confirmation is `yes` / `no`.
pub(crate) fn reply(prompt: &Prompt, answer: String) -> Option<String> {
let yes = answer == "yes";
Some(match prompt {
Prompt::ServerCertificate { permanent: true, .. } if yes => "p".into(),
Prompt::ServerCertificate { .. } if yes => "t".into(),
Prompt::ServerCertificate { .. } => "R".into(),
Prompt::StorePlaintext { .. } => if yes { "yes" } else { "no" }.into(),
_ => answer,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_prompts_to_the_askpass_dialog() {
let cert =
Prompt::ServerCertificate { url: "https://h".into(), details: "Fingerprint: AB".into(), permanent: true };
assert_eq!(describe(&cert).1, AskpassKind::Confirm);
assert_eq!(reply(&cert, "yes".into()).as_deref(), Some("p"));
assert_eq!(reply(&cert, "no".into()).as_deref(), Some("R"));
let temporary = Prompt::ServerCertificate { url: String::new(), details: String::new(), permanent: false };
assert_eq!(reply(&temporary, "yes".into()).as_deref(), Some("t"));
let password = Prompt::Password { realm: "<svn://h:3690> Test".into(), username: "ann".into() };
assert_eq!(
describe(&password),
("Subversion password for 'ann' (<svn://h:3690> Test):".into(), AskpassKind::Secret)
);
assert_eq!(reply(&password, "secret".into()).as_deref(), Some("secret"));
}
#[test]
fn answers_reach_only_waiting_prompts() {
assert!(!answer_prompt(7, None));
let events: Arc<Mutex<Vec<u64>>> = Arc::default();
let seen = events.clone();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
if let IdeEvent::Askpass { id, .. } = e {
seen.lock().push(id);
}
});
let handler = WindowPrompts { sink };
let asked = std::thread::spawn(move || handler.answer(&Prompt::Username { realm: String::new() }));
let id = loop {
if let Some(id) = events.lock().first().copied() {
break id;
}
std::thread::sleep(Duration::from_millis(5));
};
assert!(answer_prompt(id, Some("ann".into())));
assert_eq!(asked.join().unwrap().as_deref(), Some("ann"));
}
}
-5
Переглянути файл
@@ -260,10 +260,6 @@ impl crate::Host {
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
} else if !project.vcs_providers.is_empty() {
// Non-Git working copies are found in a trusted project only: they show up (or go) now.
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_backends());
}
if let Some(bridge) = &project.kotlin_bridge {
bridge.schedule();
@@ -318,7 +314,6 @@ impl crate::Host {
.map(|(window, _)| window.clone())
.collect();
for window in windows {
self.mcp_requests.withdraw(&window);
let requests = self.project_requests.write().remove(&window).unwrap_or_default();
for request in requests {
self.cancel_request(request);
-43
Переглянути файл
@@ -87,46 +87,3 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
host.shutdown_notebooks_on_exit();
assert!(started.elapsed() < Duration::from_secs(5), "exit joined the finished close instead of timing out");
}
/// `Documents` keeps the language manager alive through its observers and the manager once held the
/// documents back, so a closed project's documents (and everything they reference) were never freed.
/// Checked for the synchronous close and for the detached close that a window uses.
#[test]
fn closing_a_project_frees_its_documents() {
for detached in [false, true] {
assert_close_frees_documents(detached);
}
}
fn assert_close_frees_documents(detached: bool) {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let (documents, languages) = {
let project = host.project("main").unwrap();
(Arc::downgrade(&project.documents), Arc::downgrade(&project.languages))
};
assert!(documents.upgrade().is_some(), "the open project owns its documents");
if detached {
host.close_project_detached("main");
} else {
host.close_project("main");
}
// The detached close drops the project on its own thread.
let deadline = Instant::now() + Duration::from_secs(5);
while documents.upgrade().is_some() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(documents.upgrade().is_none(), "detached={detached}: the documents of a closed project are still alive");
assert!(
languages.upgrade().is_none(),
"detached={detached}: the language registry of a closed project is still alive"
);
}
+1 -1
Переглянути файл
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
eprintln!("run target interpreter: {after:?}");
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
assert_eq!(info.name, "Compose web");
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
-298
Переглянути файл
@@ -1,298 +0,0 @@
//! Subversion roots a project finds inside a working copy (externals, inner checkouts) and one
//! IDE commit across them, through the shared `vcs_*` commands. Follows IntelliJ's svn4idea
//! SvnExternalTest, SvnExternalCommitNoticedTest and SvnCommitTest (scenarios only); the
//! working copies themselves are checked in crates/ide-svn/tests/ij_files.rs.
//! Skipped when `svn` or `svnadmin` is not installed (a failure in CI).
mod common;
use ide_host::Host;
use ide_host::ops::vcs;
use ide_vcs::{ChangeKind, CommitOptions, FileStatus, VcsKind};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
fn which(name: &str) -> Option<PathBuf> {
let names = [name.to_owned(), format!("{name}.exe")];
std::env::split_paths(&std::env::var_os("PATH")?)
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.find(|p| p.is_file())
}
/// Whether svn is installed: skipped locally without it, a failure in CI (`CI` set).
fn have_svn() -> bool {
let missing: Vec<&str> = ["svn", "svnadmin"].into_iter().filter(|t| which(t).is_none()).collect();
if missing.is_empty() {
return true;
}
// Windows CI runners have no Subversion from a trusted source: the tests skip there.
if !cfg!(windows) && std::env::var_os("CI").is_some_and(|v| !v.is_empty() && v != "false") {
panic!("CI must install {missing:?} for the Subversion tests");
}
false
}
/// `path` as a `file://` URL, `file:///C:/…` on Windows.
fn file_url(path: &Path) -> String {
let text = path.to_string_lossy().replace('\\', "/");
if text.starts_with('/') { format!("file://{text}") } else { format!("file:///{text}") }
}
/// A repository with `trunk`, `branches/shared/part.txt` (an external's target) and a second
/// repository holding `lib/inside.txt`.
struct Fixture {
_temp: tempfile::TempDir,
base: PathBuf,
url: String,
another: String,
}
/// A configuration folder of svn's for the test (no password stores, nothing remembered), and
/// global settings of the test's host (`<base>/config`) that point svn at it.
fn private_svn_config(base: &Path) {
let svn = base.join("svn-config");
std::fs::create_dir_all(&svn).unwrap();
std::fs::write(svn.join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(svn.join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n").unwrap();
std::fs::create_dir_all(base.join("config")).unwrap();
std::fs::write(
base.join("config/settings.toml"),
format!("[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
}
fn fixture() -> Option<Fixture> {
if !have_svn() {
return None;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
// The hosts below read svn's configuration and logins from here, never ~/.subversion.
private_svn_config(&base);
for name in ["repo", "another"] {
assert!(Command::new("svnadmin").arg("create").arg(base.join(name)).status().unwrap().success());
}
let fx = Fixture { url: file_url(&base.join("repo")), another: file_url(&base.join("another")), base, _temp: temp };
fx.svn(&fx.base, &["mkdir", "-q", "-m", "layout", &format!("{}/trunk", fx.url), &format!("{}/branches", fx.url)]);
fx.import("part.txt", "shared part\n", &format!("{}/branches/shared", fx.url));
fx.import("inside.txt", "from another repository\n", &format!("{}/lib", fx.another));
Some(fx)
}
impl Fixture {
fn svn(&self, cwd: &Path, args: &[&str]) -> String {
let out = Command::new("svn")
.args(args)
.args(["--non-interactive", "--config-dir"])
.arg(self.base.join("svn-config"))
.current_dir(cwd)
.env_remove("LC_ALL")
.env("LC_MESSAGES", "C")
.output()
.unwrap();
assert!(out.status.success(), "svn {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn import(&self, name: &str, text: &str, url: &str) {
let dir = self.base.join(format!("import-{name}"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(name), text).unwrap();
self.svn(&self.base, &["import", "-q", "-m", "import", dir.to_str().unwrap(), url]);
}
/// `trunk` checked out at `name` with `main.txt` committed.
fn checkout(&self, name: &str) -> PathBuf {
let dest = self.base.join(name);
self.svn(&self.base, &["checkout", "-q", &format!("{}/trunk", self.url), dest.to_str().unwrap()]);
std::fs::write(dest.join("main.txt"), "main\n").unwrap();
self.svn(&dest, &["add", "-q", "main.txt"]);
self.svn(&dest, &["commit", "-q", "-m", "main"]);
self.svn(&dest, &["update", "-q"]);
dest
}
/// The externals definition of both kinds: this repository's and the other one's.
fn externals(&self) -> String {
format!("^/branches/shared ext-same\n{}/lib ext-other\n", self.another)
}
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..1000 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
/// A trusted project at `root`, with its working copy found.
async fn open(base: &Path, root: &Path) -> (Host, Arc<ide_host::Project>) {
let host = Host::new(common::host_config(base)).with_subversion(false);
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
(host, project)
}
/// The project's version-control roots, relative to `root` (`.` for itself), sorted.
async fn roots(host: &Host, project: &ide_host::Project, root: &Path) -> Vec<(VcsKind, String)> {
project.refresh_repositories();
let mut out: Vec<(VcsKind, String)> = vcs::vcs_roots(host, "main")
.await
.unwrap()
.into_iter()
.map(|r| {
let rel = r.root.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
(r.kind, if rel.is_empty() { ".".to_owned() } else { rel })
})
.collect();
out.sort_by(|a, b| a.1.cmp(&b.1));
out
}
fn svn_roots(names: &[&str]) -> Vec<(VcsKind, String)> {
names.iter().map(|n| (VcsKind::Subversion, (*n).to_owned())).collect()
}
fn rows(status: &[FileStatus], root: &Path) -> Vec<String> {
let mut out: Vec<String> = status
.iter()
.map(|f| {
let rel = f.path.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
format!("{rel}:{:?}", f.unstaged.unwrap_or(ChangeKind::Modified))
})
.collect();
out.sort();
out
}
/// Externals from this repository and from another one, their definition committed, are
/// version-control roots of their own next to the working copy holding them.
/// IntelliJ SvnExternalTest.testExternalCopyIsDetected, testExternalCopyIsDetectedAnotherRepo.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn externals_are_roots_of_their_own() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
fx.svn(&root, &["commit", "-q", "-m", "externals"]);
fx.svn(&root, &["update", "-q"]);
assert!(root.join("ext-same/part.txt").exists() && root.join("ext-other/inside.txt").exists());
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// A definition set and not committed, fetched by the IDE's Update Project: the externals the
/// update brings become roots. IntelliJ SvnExternalTest.testUncommittedExternalCopyIsDetected,
/// testUncommittedExternalCopyIsDetectedAnother.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn externals_an_update_brings_become_roots() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&["."]));
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert!(root.join("ext-same/part.txt").exists() && root.join("ext-other/inside.txt").exists());
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// A checkout made deep inside a working copy (`inner1/inner2/inner`), from this repository or
/// from another one, is a root of its own. IntelliJ SvnExternalTest.testInnerCopyDetected.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn inner_checkouts_are_roots_of_their_own() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
let inner = root.join("inner1/inner2/inner");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/branches/shared", fx.url), inner.to_str().unwrap()]);
let other = root.join("other-repo");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/lib", fx.another), other.to_str().unwrap()]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "inner1/inner2/inner", "other-repo"]));
}
/// Edits in a working copy, in checkouts inside it (same and another repository) and in its
/// externals show in the Changes view; one IDE commit (one `vcs_commit` per root, as the
/// Commit window sends it) commits them all. IntelliJ SvnCommitTest.testSameRepoPlusInnerCopyCommit,
/// testAnotherRepoPlusInnerCopyCommit, testPlusExternalCopyCommit; SvnExternalTest
/// testSimpleExternalsStatus at the host; SvnExternalCommitNoticedTest.testExternalCommitInExternals.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn one_commit_across_a_working_copy_and_the_ones_inside_it() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
fx.svn(&root, &["commit", "-q", "-m", "externals"]);
fx.svn(&root, &["update", "-q"]);
// Checkouts of folders of their own: two working copies of one file would make the
// second commit out of date, as svn rightly says.
fx.import("part.txt", "inner part\n", &format!("{}/branches/inner", fx.url));
fx.import("inside.txt", "other inside\n", &format!("{}/lib2", fx.another));
let inner = root.join("inner1/inner2/inner");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/branches/inner", fx.url), inner.to_str().unwrap()]);
let other = root.join("other-repo");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/lib2", fx.another), other.to_str().unwrap()]);
let (host, _project) = open(&fx.base, &root).await;
let files = [
root.join("main.txt"),
root.join("ext-same/part.txt"),
root.join("ext-other/inside.txt"),
inner.join("part.txt"),
other.join("inside.txt"),
];
for file in &files {
std::fs::write(file, "edited\n").unwrap();
}
let expected = [
"ext-other/inside.txt:Modified",
"ext-same/part.txt:Modified",
"inner1/inner2/inner/part.txt:Modified",
"main.txt:Modified",
"other-repo/inside.txt:Modified",
];
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(rows(&status, &root), expected);
// The Commit window: each path goes to the deepest root holding it.
let all: Vec<PathBuf> = vcs::vcs_roots(&host, "main").await.unwrap().into_iter().map(|r| r.root.0).collect();
let root_of = |p: &Path| all.iter().filter(|r| p.starts_with(r)).max_by_key(|r| r.components().count()).cloned();
for repo in &all {
let stage: Vec<PathBuf> = files.iter().filter(|f| root_of(f).as_ref() == Some(repo)).cloned().collect();
let options = CommitOptions { stage: stage.into_iter().map(Into::into).collect(), ..Default::default() };
vcs::vcs_commit(&host, "main", Some(repo.clone()), "everywhere".into(), options).await.unwrap();
}
assert!(vcs::vcs_status(&host, "main").await.unwrap().is_empty());
for url in [
format!("{}/branches/shared/part.txt", fx.url),
format!("{}/branches/inner/part.txt", fx.url),
format!("{}/lib/inside.txt", fx.another),
format!("{}/lib2/inside.txt", fx.another),
] {
assert_eq!(fx.svn(&fx.base, &["cat", &url]), "edited\n", "{url}");
}
}
/// The project's working copy switched to a branch from a terminal: the branch widget shows
/// the branch once the roots are looked at again. IntelliJ SvnExternalCommitNoticedTest
/// .testExternalRootSwitch.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_root_switched_in_a_terminal_shows_its_new_line() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
fx.svn(&fx.base, &["copy", "-q", "-m", "branch", &format!("{}/trunk", fx.url), &format!("{}/branches/b", fx.url)]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("trunk"));
fx.svn(&root, &["switch", "-q", &format!("{}/branches/b", fx.url)]);
project.refresh_repositories();
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/b"));
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots[0].head.as_deref(), Some("branches/b"));
}
+10 -15
Переглянути файл
@@ -742,43 +742,38 @@ async fn typescript_import_style() {
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let lsp = smoke.host.project(WINDOW).unwrap().lsp.clone();
// Returns once vtsls has the change. A completion that runs before it fills tsserver's
// module specifier cache for that file under the old preferences, and that cache is keyed
// without `autoImportSpecifierExcludeRegexes`, so the file keeps the old answer.
let set = async |key: &str, value: &str| {
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();
lsp.reconfigure().await;
};
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""#).await;
set("importModuleSpecifier", r#""relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
set("importModuleSpecifier", r#""non-relative""#).await;
set("importModuleSpecifier", r#""non-relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
set("importModuleSpecifier", r#""relative""#).await;
set("importModuleSpecifierEnding", r#""index""#).await;
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifierEnding", r#""index""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
set("importModuleSpecifierEnding", r#""minimal""#).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"]"#).await;
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$"]"#).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", "[]").await;
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", "[]").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;
}
+45 -363
Переглянути файл
@@ -1,8 +1,6 @@
mod common;
use ide_core::{
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
};
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
use ide_host::{Host, HostConfig};
use ide_mcp::ToolRegistry;
@@ -14,8 +12,7 @@ struct Harness {
host: Arc<Host>,
root: PathBuf,
tmp: tempfile::TempDir,
/// Every event, with the window whose sink it was emitted on.
events: Arc<std::sync::Mutex<Vec<(String, IdeEvent)>>>,
events: Arc<std::sync::Mutex<Vec<IdeEvent>>>,
}
impl Harness {
fn new() -> Self {
@@ -30,9 +27,9 @@ impl Harness {
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
sink_for: Box::new(move |_| {
let events = sink.clone();
Arc::new(move |e| events.lock().unwrap().push(e))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
@@ -58,7 +55,7 @@ impl Harness {
async fn request(&self) -> u32 {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|(_, e)| match e {
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::McpRequest { id, .. } => Some(*id),
_ => None,
}) {
@@ -70,54 +67,6 @@ impl Harness {
.await
.unwrap()
}
/// The requests `window` shows: asked there and not closed since.
fn shown(&self, window: &str) -> Vec<(u32, McpUiRequest)> {
let mut shown = Vec::new();
for (_, event) in self.events.lock().unwrap().iter().filter(|(w, _)| w == window) {
match event {
IdeEvent::McpRequest { id, request } => shown.push((*id, request.clone())),
IdeEvent::McpRequestClosed { id } => shown.retain(|(open, _)| open != id),
_ => {}
}
}
shown
}
/// Waits until `window` shows `count` requests, and returns them.
async fn shown_in(&self, window: &str, count: usize) -> Vec<(u32, McpUiRequest)> {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
let shown = self.shown(window);
if shown.len() >= count {
return shown;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.unwrap_or_else(|_| panic!("{window} shows no {count} requests"))
}
/// The request `window` shows, once it shows one.
async fn request_in(&self, window: &str) -> (u32, McpUiRequest) {
self.shown_in(window, 1).await.pop().unwrap()
}
/// Whether `window` was told that request `id` closed.
fn closed_in(&self, window: &str, id: u32) -> bool {
let events = self.events.lock().unwrap();
events
.iter()
.any(|(w, e)| w == window && matches!(e, IdeEvent::McpRequestClosed { id: closed } if *closed == id))
}
/// Reports `window` focused, as its frontend does when the user brings it to the front.
fn focus(&self, window: &str) {
self.host.mcp_reports.set_focused_editor(window, None, true);
}
/// Opens the window `second` on the folder `second` next to the open project.
fn open_second(&self) -> PathBuf {
let second = self.root.parent().unwrap().join("second");
std::fs::create_dir_all(&second).unwrap();
self.host.open_project("second", &second).unwrap();
second
}
async fn call(&self, name: &str, args: Value) -> String {
let (host, root, name) = (self.host.clone(), self.root.clone(), name.to_owned());
tokio::task::spawn_blocking(move || {
@@ -303,10 +252,6 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
assert!(!h.host.project("main").unwrap().is_trusted());
let registry = Registry::new(h.host.clone());
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
// A tool that writes, called all the same, says why it can't run.
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
assert!(!h.root.join("x.txt").exists());
assert!(!h.host.global_settings.effective().mcp_server.enabled);
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
assert_eq!(
@@ -446,11 +391,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
assert!(p.documents.is_dirty(doc.id).unwrap());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old text\nneedle needle\n");
assert!(
h.events
.lock()
.unwrap()
.iter()
.any(|(_, e)| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
);
let edit_id = h
.events
@@ -458,7 +399,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
.unwrap()
.iter()
.rev()
.find_map(|(_, event)| match event {
.find_map(|event| match event {
// Undoable like a refactoring, but marked as the agent's, so it isn't announced as one.
IdeEvent::WorkspaceEditApplied { id, by_agent, .. } => {
assert!(*by_agent, "an MCP edit is the agent's");
@@ -497,16 +438,14 @@ async fn execution_requires_a_window_and_denial_never_runs_a_build() {
h.host.mcp_requests.set_ready("main", true);
let denied = h.error("build_project", json!({}));
let answer = async {
let (id, request) = h.request_in("main").await;
// A window's own project is not a background one.
assert!(matches!(request, McpUiRequest::Confirm { background: false, .. }), "{request:?}");
let id = h.request().await;
assert!(h.host.mcp_requests.answer("other", id, true, None).is_err());
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, answer);
assert!(error.contains("denied by the user"), "{error}");
assert!(h.host.processes.list().is_empty());
assert!(h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequestClosed { .. })));
assert!(h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequestClosed { .. })));
h.events.lock().unwrap().clear();
let closed = h.error("build_project", json!({}));
let close = async {
@@ -835,7 +774,7 @@ fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
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) =>
{
@@ -908,9 +847,11 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert_eq!(tabs[0].name, "MCP test");
}
/// A shell configuration named `MCP test` that prints `windowless` and exits with 3.
fn windowless_config() -> ide_run::RunConfig {
ide_run::RunConfig {
#[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(),
@@ -923,14 +864,8 @@ fn windowless_config() -> ide_run::RunConfig {
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[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;
ide_run::save_user_configs(&h.root, &[windowless_config()]).unwrap();
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
@@ -938,7 +873,7 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
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");
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -1085,7 +1020,7 @@ async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
.expect("ran without waiting for an answer")
.unwrap();
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -1117,7 +1052,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest {
id,
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
@@ -1611,91 +1546,22 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
}
#[tokio::test(flavor = "multi_thread")]
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
let h = Harness::new();
let inventory = h.root.parent().unwrap().join("inventory");
std::fs::create_dir_all(&inventory).unwrap();
let (_server, discovery) = h.server();
let list = rpc(1, "tools/list", json!({}));
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
let replies = bridged(&discovery, &inventory, &[list, read]).await;
let tools = replies[0]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
let message = replies[1]["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
for reply in bridged(&discovery, &inventory, &[list, read]).await {
assert_eq!(reply["error"]["code"], -32001, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
}
assert!(h.background().is_empty());
assert_eq!(h.host.projects().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
let h = Harness::new();
// A folder that only holds repositories: one trusted, one not.
let work = h.root.parent().unwrap().join("work");
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
for project in [&inventory, &ledger] {
std::fs::create_dir_all(project.join("src")).unwrap();
}
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
h.set("enabled", json!(true));
h.set("backgroundProjects", json!("listed"));
h.set("backgroundProjectPaths", json!([inventory, ledger]));
h.host.set_project_trust(&inventory, true, false).await.unwrap();
let (_server, discovery) = h.server();
let requests =
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &work, &requests).await;
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
let tools = replies[1]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
// A tool that writes is refused for the untrusted project before it loads; a call that
// names no project is refused too.
let create = rpc(
4,
"tools/call",
json!({"name":"create_new_file","arguments":{
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
);
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
assert!(refused.contains("Restricted Mode"), "{refused}");
assert!(!ledger.join("notes.txt").exists());
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
assert!(h.background().is_empty(), "refusals open nothing");
// Inside a served project, servesFolder names it, and loads nothing either.
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
assert!(h.background().is_empty());
let read = rpc(
6,
"tools/call",
json!({"name":"read_file","arguments":{
"projectPath":inventory,"file_path":"src/stock.txt"}}),
);
let replies = bridged(&discovery, &work, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
assert_eq!(h.background(), std::slice::from_ref(&inventory));
// A remote window's root is that host's to serve.
let remote = work.join("remote");
std::fs::create_dir_all(&remote).unwrap();
h.host.mcp_reports.set_remote("remote", remote.clone());
let replies = bridged(&discovery, &remote, &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
h.host.close_project_detached("remote");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
let h = Harness::new();
@@ -1854,215 +1720,31 @@ async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
}
#[tokio::test(flavor = "multi_thread")]
async fn tools_that_need_a_window_refuse_in_a_background_project_before_asking() {
async fn tools_that_ask_the_user_fail_closed_in_a_background_project() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let root = inventory.display();
// Running without confirmation does not give them a window either.
for brave in [false, true] {
h.set("runWithoutConfirmation", json!(brave));
for (tool, args) in [
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
("xdebug_start_debugger_session", json!({"filePath":"src/stock.txt","line":1})),
("xdebug_set_breakpoint", json!({"filePath":"src/stock.txt","line":1})),
("xdebug_remove_breakpoint", json!({})),
("xdebug_list_breakpoints", json!({})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert_eq!(
error,
format!("{tool} needs the project open in a window: {root} is served in the background.")
);
}
for (tool, args) in [
("build_project", json!({})),
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert!(error.contains("no project window"), "{tool}: {error}");
}
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
assert!(h.host.processes.list().is_empty());
// Running without confirmation does not give `run_command` or the editor a window.
h.set("runWithoutConfirmation", json!(true));
for (tool, args) in [
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert!(error.contains("no project window"), "{tool}: {error}");
}
assert_eq!(h.background(), [inventory]);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_background_project_asks_in_the_most_recently_focused_project_window() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
h.host.set_project_trust(&second, true, false).await.unwrap();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let error = h.call_at(&inventory, "build_project", json!({})).await.unwrap_err();
assert!(error.contains("no project window is available"), "{error}");
for window in ["main", "second"] {
h.host.mcp_requests.set_ready(window, true);
}
h.focus("second");
h.focus("main");
let denied = h.call_at(&inventory, "build_project", json!({}));
let deny = async {
let (id, request) = h.request_in("main").await;
let McpUiRequest::Confirm { background, project, .. } = request else { panic!("{request:?}") };
assert!(background);
assert_eq!(project, ide_core::ipc_path::to_ipc(&inventory));
assert!(h.shown("second").is_empty());
assert!(h.host.mcp_requests.answer("second", id, true, None).is_err());
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.unwrap_err().contains("denied by the user"));
assert!(h.host.processes.list().is_empty());
// Allowed there, a configuration runs on its own, as without a window under brave mode.
ide_run::save_user_configs(&inventory, &[windowless_config()]).unwrap();
let run =
h.call_at(&inventory, "execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
let allow = async {
let (id, request) = h.request_in("main").await;
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(run, allow);
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
std::fs::write(inventory.join("api.http"), "### Health\nGET http://127.0.0.1:9/health\n").unwrap();
let denied = h.call_at(&inventory, "http_run_request", json!({"path":"api.http","index":0}));
let deny = async {
let (id, request) = h.request_in("main").await;
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.unwrap_err().contains("denied by the user"));
assert!(h.shown("second").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn requests_for_two_background_projects_queue_in_one_window() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
let ledger = h.root.parent().unwrap().join("ledger");
std::fs::create_dir_all(&ledger).unwrap();
h.set("backgroundProjectPaths", json!([inventory, ledger]));
for root in [&inventory, &ledger] {
h.host.trust.decide(root, true, false).unwrap();
}
let first = h.call_at(&inventory, "build_project", json!({}));
let second = h.call_at(&ledger, "build_project", json!({}));
let deny = async {
let shown = h.shown_in("main", 2).await;
let mut projects: Vec<_> = shown
.iter()
.map(|(_, request)| match request {
McpUiRequest::Confirm { project, background: true, .. } => PathBuf::from(project),
other => panic!("{other:?}"),
})
.collect();
projects.sort();
assert_eq!(projects, [inventory.clone(), ledger.clone()]);
for (id, _) in shown {
h.host.mcp_requests.answer("main", id, false, None).unwrap();
}
};
let (first, second, ()) = tokio::join!(first, second, deny);
for error in [first.unwrap_err(), second.unwrap_err()] {
assert!(error.contains("denied by the user"), "{error}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_request_moves_when_its_window_closes_and_fails_when_none_is_left() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
h.host.set_project_trust(&second, true, false).await.unwrap();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
for window in ["second", "main"] {
h.host.mcp_requests.set_ready(window, true);
h.focus(window);
}
let denied = h.call_at(&inventory, "build_project", json!({}));
let moves = async {
let (id, _) = h.request_in("main").await;
h.host.close_project_detached("main");
let (moved, _) = h.request_in("second").await;
assert_eq!(moved, id);
assert!(h.closed_in("main", id));
h.host.mcp_requests.answer("second", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, moves);
assert!(error.unwrap_err().contains("denied by the user"));
let closed = h.call_at(&inventory, "build_project", json!({}));
let close = async {
let (id, _) = h.request_in("second").await;
h.host.close_project_detached("second");
id
};
let (error, id) = tokio::join!(closed, close);
assert!(error.unwrap_err().contains("project window closed"));
assert!(h.closed_in("second", id));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_request_leaves_the_window_when_its_project_unloads_or_the_call_is_cancelled() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let unloaded = h.call_at(&inventory, "build_project", json!({}));
let unload = async {
let (id, _) = h.request_in("main").await;
assert!(h.host.mcp_background.detach(&h.host, &inventory, None));
id
};
let (error, id) = tokio::join!(unloaded, unload);
assert!(error.unwrap_err().contains("project window closed"));
assert!(h.closed_in("main", id));
let (host, root, cancel) = (h.host.clone(), inventory.clone(), CancellationToken::new());
let token = cancel.clone();
let cancelled = tokio::task::spawn_blocking(move || Registry::new(host).call(&root, "build_project", "{}", token));
let (id, _) = h.request_in("main").await;
cancel.cancel();
assert!(cancelled.await.unwrap().is_err());
assert!(h.closed_in("main", id));
assert!(h.shown("main").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_untrusted_window_never_shows_a_background_request() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
// `second` is untrusted and focused last; its ready mark is a stale one.
for window in ["main", "second"] {
h.host.mcp_requests.set_ready(window, true);
h.focus(window);
}
let call = h.call_at(&inventory, "build_project", json!({}));
let moves = async {
let (id, _) = h.request_in("main").await;
assert!(h.shown("second").is_empty());
h.host.set_project_trust(&second, true, false).await.unwrap();
h.host.set_project_trust(&h.root, false, false).await.unwrap();
let (moved, _) = h.request_in("second").await;
assert_eq!(moved, id);
assert!(h.closed_in("main", id));
h.host.set_project_trust(&second, false, false).await.unwrap();
};
let (error, ()) = tokio::join!(call, moves);
assert!(error.unwrap_err().contains("project window closed"));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_cancelled_or_failed_call_leaves_nothing_holding_the_project() {
let h = Harness::new();
@@ -2168,7 +1850,7 @@ fn debugger_window(h: &Harness) {
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request }
if !handled.contains(id)
&& matches!(
+10 -69
Переглянути файл
@@ -70,20 +70,6 @@ impl Harness {
fn run(&self, id: &str, arg: Option<&str>) -> ide_core::IdeResult<Option<String>> {
self.plugins.run_command(ID, id, arg, self.invocation())
}
/// The folder `inventory` next to the project, listed to be served without a window.
fn serve_inventory(&self) -> PathBuf {
let inventory = self.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
self.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
inventory
}
fn source(&self) -> String {
serde_json::json!({"id":"local","name":"Example","driver":"sqlite","database":self.root.join("db.sqlite").to_string_lossy(),"options":[]}).to_string()
}
@@ -203,66 +189,21 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_destructive_plugin_tool_of_a_background_project_asks_in_a_project_window() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
f.host.trust.decide(&inventory, true, false).unwrap();
f.host.mcp_requests.set_ready("main", true);
let (registry, root) = (Registry::new(f.host.clone()), inventory.clone());
let call = tokio::task::spawn_blocking(move || {
registry.call(&root, "test_data_tools__erase", "{}", CancellationToken::new())
});
let (window, id, background) = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(found) = f.events.lock().unwrap().iter().find_map(|(w, e)| match e {
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { background, .. } } => {
Some((w.clone(), *id, *background))
}
_ => None,
}) {
break found;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!((window.as_str(), background), ("main", true));
f.host.mcp_requests.answer("main", id, false, None).unwrap();
let denied = call.await.unwrap().unwrap_err();
assert!(format!("{denied:?}").contains("denied by the user"), "{denied:?}");
f.host.close_project(&ide_host::mcp::BackgroundProjects::key(&inventory));
}
#[tokio::test(flavor = "multi_thread")]
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
let registry = Registry::new(f.host.clone());
// A connection without a project of its own lists the tool with `projectPath`, which its
// calls have to pass, and the plugin's strict schema still takes the call.
let listed = registry.tools_without_project();
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
assert!(result.contains("hello"), "{result}");
// A tool that writes refuses the untrusted folder, and nothing loads.
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
// The fixture's `spin` runs until it is cancelled or its budget ends.
let f = Harness::with_timeout(Duration::from_secs(10));
let inventory = f.serve_inventory();
let inventory = f.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
let held_by = || {
let loaded = f.host.mcp_background.snapshot(&f.host, std::time::Instant::now());
loaded.into_iter().next().map(|project| project.kept_open_by)
-17
Переглянути файл
@@ -8170,20 +8170,3 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
assert_eq!(dirs.len(), 1);
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
}
#[test]
fn restricting_a_project_without_its_plugins_announces_nothing() {
let tmp = tempfile::tempdir().unwrap();
let events: Events = Arc::default();
let sink = {
let events = events.clone();
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
};
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
host.load_all();
events.lock().clear();
// A restricted window lists the plugins, which restricts its project again each time.
host.restrict_project(tmp.path());
host.restrict_project(tmp.path());
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
}
-793
Переглянути файл
@@ -1,793 +0,0 @@
//! Subversion working copies through the shared `vcs_*` commands and the
//! `svn_*` ones, against throwaway `svnadmin` repositories (`file://` URLs).
//! Skipped when `svn` or `svnadmin` is not installed.
mod common;
use ide_core::CancellationToken;
use ide_host::Host;
use ide_host::ops::{svn, vcs};
use ide_vcs::{ChangeKind, CommitOptions, FileStatus, LogQuery, VcsKind};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
fn which(name: &str) -> Option<PathBuf> {
let names = [name.to_owned(), format!("{name}.exe")];
std::env::split_paths(&std::env::var_os("PATH")?)
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.find(|p| p.is_file())
}
/// Whether svn is installed: skipped locally without it, a failure in CI (`CI` set).
fn have_svn() -> bool {
have(&["svn", "svnadmin"])
}
/// Whether `tools` are installed, likewise.
fn have(tools: &[&str]) -> bool {
let missing: Vec<&str> = tools.iter().copied().filter(|t| which(t).is_none()).collect();
if missing.is_empty() {
return true;
}
// Windows CI runners have no Subversion from a trusted source: the tests skip there.
if !cfg!(windows) && std::env::var_os("CI").is_some_and(|v| !v.is_empty() && v != "false") {
panic!("CI must install {missing:?} for the Subversion tests");
}
false
}
/// `path` as a `file://` URL, `file:///C:/…` on Windows.
fn file_url(path: &Path) -> String {
let text = path.to_string_lossy().replace('\\', "/");
if text.starts_with('/') { format!("file://{text}") } else { format!("file:///{text}") }
}
struct Fixture {
_temp: tempfile::TempDir,
base: PathBuf,
url: String,
}
/// A configuration folder of svn's for the test (no password stores, nothing remembered), and
/// global settings of the test's host (`<base>/config`) that point svn at it.
fn private_svn_config(base: &Path) {
let svn = base.join("svn-config");
std::fs::create_dir_all(&svn).unwrap();
std::fs::write(svn.join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(svn.join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n").unwrap();
std::fs::create_dir_all(base.join("config")).unwrap();
std::fs::write(
base.join("config/settings.toml"),
format!("[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
}
/// A repository with `trunk` and `branches`, and an `svn` that never reads the user's own
/// configuration or stores a login.
fn fixture() -> Option<Fixture> {
if !have_svn() {
return None;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
// The hosts below read svn's configuration and logins from here, never ~/.subversion.
private_svn_config(&base);
assert!(Command::new("svnadmin").arg("create").arg(base.join("repo")).status().unwrap().success());
let fixture = Fixture { url: file_url(&base.join("repo")), base, _temp: temp };
let (trunk, branches) = (format!("{}/trunk", fixture.url), format!("{}/branches", fixture.url));
fixture.svn(&fixture.base, &["mkdir", "-q", "-m", "layout", &trunk, &branches]);
Some(fixture)
}
impl Fixture {
fn svn(&self, cwd: &Path, args: &[&str]) -> String {
let out = Command::new("svn")
.args(args)
.args(["--non-interactive", "--config-dir"])
.arg(self.base.join("svn-config"))
.current_dir(cwd)
.env_remove("LC_ALL")
.env("LC_MESSAGES", "C")
.output()
.unwrap();
assert!(out.status.success(), "svn {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn checkout(&self, name: &str) -> PathBuf {
let dest = self.base.join(name);
self.svn(&self.base, &["checkout", "-q", &format!("{}/trunk", self.url), dest.to_str().unwrap()]);
dest
}
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..1000 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
/// A trusted project at `root`, with its working copy found.
async fn open(base: &Path, root: &Path) -> (Host, Arc<ide_host::Project>) {
let host = Host::new(common::host_config(base)).with_subversion(false);
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
(host, project)
}
fn kinds(status: &[FileStatus]) -> Vec<(String, ChangeKind)> {
let mut out: Vec<_> = status.iter().map(|f| (f.rel_path.clone(), f.unstaged.unwrap())).collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// Get from Version Control › Subversion, its progress lines dropped.
async fn checkout(host: &Host, url: String, dest: PathBuf) -> ide_core::IdeResult<()> {
let channel = ide_host::ops::Channel::new(|_: String| {});
svn::svn_checkout(host, "main", ide_core::RequestId::next(), url, dest, channel).await
}
fn commit_options(paths: &[PathBuf]) -> CommitOptions {
CommitOptions { stage: paths.iter().cloned().map(Into::into).collect(), ..Default::default() }
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_through_the_shared_commands() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let (host, _project) = open(&fx.base, &root).await;
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!((roots.len(), roots[0].kind, roots[0].head.as_deref()), (1, VcsKind::Subversion, Some("trunk")));
// svn reads the test's own configuration, never the user's ~/.subversion.
let svn_settings = _project.svn.as_ref().unwrap().settings();
assert_eq!(svn_settings.config_dir, Some(fx.base.join("svn-config")));
// Add, commit, log.
let a = root.join("a.txt");
std::fs::write(&a, "one\n").unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Untracked)]);
vcs::vcs_stage(&host, "main", vec![a.clone()]).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Added)]);
let rev = vcs::vcs_commit(&host, "main", None, "add a 中文".into(), commit_options(std::slice::from_ref(&a)))
.await
.unwrap();
assert_eq!(rev, "2");
let log = vcs::vcs_log(&host, "main", None, LogQuery { limit: 10, ..Default::default() }).await.unwrap();
assert_eq!(log.iter().map(|c| c.summary.as_str()).collect::<Vec<_>>(), ["add a 中文", "layout"]);
assert_eq!(vcs::vcs_log_details(&host, "main", None, "2".into()).await.unwrap().message, "add a 中文");
// What the post-commit checks read of the new revision (they name the root).
let changes = vcs::vcs_commit_selection_changes(
&host,
"main",
Some(root.clone()),
vec![rev.clone()],
ide_core::RequestId::next(),
)
.await
.unwrap();
assert_eq!(
changes.iter().map(|c| (c.path.as_str(), c.after.as_deref())).collect::<Vec<_>>(),
[("a.txt", Some("2"))]
);
// New Branch is Create Branch or Tag, then a switch; the widget lists trunk and branches.
let outcome = vcs::vcs_checkout(&host, "main", None, "feature".into(), true, None, None).await.unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/feature"));
let branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
let names: Vec<(&str, bool)> = branches.iter().map(|b| (b.name.as_str(), b.current)).collect();
assert_eq!(names, [("trunk", false), ("branches/feature", true)]);
vcs::vcs_checkout(&host, "main", None, "trunk".into(), false, None, None).await.unwrap();
// Update Project with a conflict, resolved in the merge editor (which stages the result).
let other = fx.checkout("other");
std::fs::write(other.join("a.txt"), "theirs\n").unwrap();
fx.svn(&other, &["commit", "-q", "-m", "theirs"]);
std::fs::write(&a, "mine\n").unwrap();
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Conflicted)]);
let versions = vcs::vcs_conflict_versions(&host, "main", a.clone()).await.unwrap();
assert_eq!((versions.ours.as_deref(), versions.theirs.as_deref()), (Some("mine\n"), Some("theirs\n")));
assert_eq!(versions.base.as_deref(), Some("one\n"));
assert!(versions.merged.unwrap().contains("<<<<<<< .mine"));
std::fs::write(&a, "merged\n").unwrap();
vcs::vcs_stage(&host, "main", vec![a.clone()]).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Modified)]);
vcs::vcs_commit(&host, "main", None, "merged".into(), commit_options(std::slice::from_ref(&a))).await.unwrap();
// VCS › Subversion: properties, locks, repository info, cleanup.
svn::svn_set_property(&host, "main", a.clone(), "review".into(), Some("yes".into())).await.unwrap();
let props = svn::svn_properties(&host, "main", a.clone()).await.unwrap();
assert_eq!(props.iter().map(|p| (p.name.as_str(), p.value.as_str())).collect::<Vec<_>>(), [("review", "yes")]);
svn::svn_lock(&host, "main", vec![a.clone()], "editing".into(), false).await.unwrap();
svn::svn_unlock(&host, "main", vec![a.clone()], false).await.unwrap();
let info = svn::svn_repository_info(&host, "main", None).await.unwrap();
assert!(info.url.ends_with("/repo/trunk"), "{}", info.url);
svn::svn_cleanup(&host, "main", None).await.unwrap();
assert!(svn::svn_version(&host, "main", String::new()).await.unwrap().version.is_some());
let fresh = fx.base.join("fresh");
checkout(&host, format!("{}/trunk", fx.url), fresh.clone()).await.unwrap();
assert_eq!(std::fs::read_to_string(fresh.join("a.txt")).unwrap(), "merged\n");
let _ = CancellationToken::new();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn svn_changelists_through_the_backend_changelist_commands() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
for name in ["a.txt", "b.txt"] {
std::fs::write(root.join(name), "base\n").unwrap();
}
fx.svn(&root, &["add", "-q", "a.txt", "b.txt"]);
fx.svn(&root, &["commit", "-q", "-m", "base"]);
// A nested Git repository keeps the IDE's own lists.
let git = root.join("tool");
std::fs::create_dir(&git).unwrap();
assert!(Command::new("git").arg("init").arg("-q").arg(&git).status().unwrap().success());
std::fs::write(git.join("g.txt"), "g\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
until("the nested Git repository", || !project.repos().is_empty()).await;
let (a, b) = (root.join("a.txt"), root.join("b.txt"));
let lists = || async {
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
lists.into_iter().map(|l| (l.name, l.files.into_iter().map(|f| f.0).collect::<Vec<_>>())).collect::<Vec<_>>()
};
// A list made with the svn CLI shows up.
std::fs::write(&a, "a\n").unwrap();
std::fs::write(&b, "b\n").unwrap();
fx.svn(&root, &["changelist", "-q", "from cli", "a.txt"]);
assert_eq!(lists().await, [("from cli".to_owned(), vec![a.clone()])]);
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(git.clone())).await.unwrap(), None);
// A move in the Commit window is `svn changelist`; so are renames and deletions.
let id = vcs::vcs_backend_changelist_create(&host, "main", Some(root.clone()), "ui".into(), String::new())
.await
.unwrap();
vcs::vcs_backend_changelist_move(&host, "main", vec![b.clone()], id.clone()).await.unwrap();
let status = fx.svn(&root, &["status"]);
assert!(status.contains("--- Changelist 'ui':") && status.contains("b.txt"), "{status}");
vcs::vcs_backend_changelist_edit(&host, "main", Some(root.clone()), id, "UI".into(), String::new()).await.unwrap();
assert!(fx.svn(&root, &["status"]).contains("--- Changelist 'UI':"));
let default = ide_vcs::changelists::DEFAULT_ID.to_owned();
vcs::vcs_backend_changelist_move(&host, "main", vec![b.clone()], default).await.unwrap();
assert!(!fx.svn(&root, &["status", "b.txt"]).contains("Changelist"));
vcs::vcs_backend_changelist_delete(&host, "main", Some(root.clone()), "list:from cli".into()).await.unwrap();
assert!(lists().await.is_empty());
// A Git file is not the working copy's to list.
assert!(vcs::vcs_backend_changelist_move(&host, "main", vec![git.join("g.txt")], "list:ui".into()).await.is_err());
// A commit drops the committed file's list.
fx.svn(&root, &["changelist", "-q", "ui", "a.txt"]);
vcs::vcs_commit(&host, "main", Some(root.clone()), "a".into(), commit_options(std::slice::from_ref(&a)))
.await
.unwrap();
assert!(lists().await.is_empty());
}
/// An executable script `name` in `dir` (unix).
#[cfg(unix)]
fn script(dir: &Path, name: &str, text: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(name);
std::fs::write(&path, text).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
/// A project nobody trusted runs no svn at all, not even the one its own
/// `.openidea/settings.toml` names; trusting it looks for working copies again, with that svn.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_untrusted_project_runs_no_svn() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let log = fx.base.join("runs.log");
let real = which("svn").unwrap();
let svn = script(
&fx.base,
"project-svn",
&format!("#!/bin/sh\necho \"$*\" >> '{}'\nexec '{}' \"$@\"\n", log.display(), real.display()),
);
std::fs::create_dir(root.join(".openidea")).unwrap();
std::fs::write(
root.join(".openidea/settings.toml"),
format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
let project = host.open_project("main", &root).unwrap();
tokio::time::sleep(Duration::from_millis(1500)).await;
assert!(project.backends().is_empty());
assert!(vcs::vcs_roots(&host, "main").await.unwrap().is_empty());
assert!(!log.exists(), "svn ran: {}", std::fs::read_to_string(&log).unwrap_or_default());
// Get from Version Control in its window checks out with the global settings' svn.
let fresh = fx.base.join("fresh");
checkout(&host, format!("{}/trunk", fx.url), fresh.clone()).await.unwrap();
assert!(fresh.join(".svn").is_dir());
assert!(
!log.exists(),
"the project's svn ran for a checkout: {}",
std::fs::read_to_string(&log).unwrap_or_default()
);
// Settings › Subversion › Test with the project's svn is refused; auto-detection works.
assert!(svn::svn_version(&host, "main", svn.to_string_lossy().into_owned()).await.is_err());
assert!(svn::svn_version(&host, "main", String::new()).await.unwrap().version.is_some());
assert!(!log.exists());
host.set_project_trust(&root, true, false).await.unwrap();
until("the working copy", || !project.backends().is_empty()).await;
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots.iter().map(|r| r.kind).collect::<Vec<_>>(), [VcsKind::Subversion]);
assert!(std::fs::read_to_string(&log).unwrap().contains("info"), "the project's own svn runs once trusted");
// Restricted again: nothing of it is reported.
host.set_project_trust(&root, false, false).await.unwrap();
until("no working copy", || project.backends().is_empty()).await;
}
/// A running `svnserve`, ended when dropped (also when a test fails).
#[cfg(unix)]
struct Svnserve(std::process::Child);
#[cfg(unix)]
impl Drop for Svnserve {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// `svnserve` on a free port that asks every client for alice / secret.
#[cfg(unix)]
fn serve_with_login(fx: &Fixture) -> (Svnserve, String) {
let repo = fx.base.join("repo");
std::fs::write(
repo.join("conf/svnserve.conf"),
"[general]\nanon-access = none\nauth-access = write\npassword-db = passwd\nrealm = Test\n",
)
.unwrap();
std::fs::write(repo.join("conf/passwd"), "[users]\nalice = secret\n").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let child = Command::new("svnserve")
.args([
"-d",
"--foreground",
"--threads",
"--listen-host",
"127.0.0.1",
"--listen-port",
&port.to_string(),
"-r",
])
.arg(&repo)
.spawn()
.unwrap();
let started = std::time::Instant::now();
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(started.elapsed() < Duration::from_secs(10), "svnserve did not start");
std::thread::sleep(Duration::from_millis(50));
}
(Svnserve(child), format!("svn://127.0.0.1:{port}"))
}
/// Two projects with their own Settings › Subversion: each runs its own svn, and svn's
/// prompts open in the window of the project whose command asked, answered there.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn two_projects_keep_their_settings_and_prompts() {
let Some(fx) = fixture() else { return };
if !have(&["svnserve"]) {
return;
}
let (_server, url) = serve_with_login(&fx);
let checkout = |name: &str| {
let dest = fx.base.join(name);
fx.svn(
&fx.base,
&[
"checkout",
"-q",
"--username",
"alice",
"--password",
"secret",
"--no-auth-cache",
&format!("{url}/trunk"),
dest.to_str().unwrap(),
],
);
dest
};
let (one, two) = (checkout("one"), checkout("two"));
// Project one runs its svn through a wrapper of its own.
let log = fx.base.join("one.log");
let real = which("svn").unwrap();
let wrapper = script(
&fx.base,
"one-svn",
&format!("#!/bin/sh\necho \"$*\" >> '{}'\nexec '{}' \"$@\"\n", log.display(), real.display()),
);
for (root, settings) in [
(
&one,
format!(
"[vcs.svn]\nexecutable = {:?}\nuseCustomConfigDir = true\nconfigDir = {:?}\n",
wrapper.to_string_lossy(),
fx.base.join("cfg-one").to_string_lossy()
),
),
(
&two,
format!(
"[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n",
fx.base.join("cfg-two").to_string_lossy()
),
),
] {
std::fs::create_dir(root.join(".openidea")).unwrap();
fx.svn(root, &["propset", "-q", "svn:ignore", ".openidea", "."]);
std::fs::write(root.join(".openidea/settings.toml"), settings).unwrap();
}
for name in ["cfg-one", "cfg-two"] {
std::fs::create_dir(fx.base.join(name)).unwrap();
std::fs::write(fx.base.join(name).join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(fx.base.join(name).join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n")
.unwrap();
}
// Each window's prompts, answered as a user there would.
type Asked = Arc<parking_lot::Mutex<Vec<(String, String)>>>;
let asked: Asked = Arc::default();
let mut config = common::host_config(&fx.base);
let seen = asked.clone();
config.sink_for = Box::new(move |window: &str| {
let (seen, window) = (seen.clone(), window.to_owned());
Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::Askpass { id, prompt, .. } = event {
seen.lock().push((window.clone(), prompt.clone()));
let answer = if prompt.contains("username") { "alice" } else { "secret" };
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
ide_host::svn::answer_prompt(id, Some(answer.into()));
});
}
})
});
let host = Host::new(config).with_subversion(true);
for (window, root) in [("w1", &one), ("w2", &two)] {
host.trust.decide(root, true, false).unwrap();
let project = host.open_project(window, root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
}
let ran_before = std::fs::read_to_string(&log).unwrap_or_default().lines().count();
assert!(ran_before > 0, "project one's svn found its working copy");
let update = |window: &'static str| {
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, window, None, ide_core::RequestId::next(), op, channel, None)
};
update("w2").await.unwrap();
let prompts = asked.lock().clone();
assert!(!prompts.is_empty() && prompts.iter().all(|(w, _)| w == "w2"), "{prompts:?}");
assert_eq!(
std::fs::read_to_string(&log).unwrap_or_default().lines().count(),
ran_before,
"project two used its own svn"
);
asked.lock().clear();
update("w1").await.unwrap();
let prompts = asked.lock().clone();
assert!(!prompts.is_empty() && prompts.iter().all(|(w, _)| w == "w1"), "{prompts:?}");
assert!(
std::fs::read_to_string(&log).unwrap().lines().any(|l| l.starts_with("update")),
"project one used its wrapper"
);
}
fn git_init(dir: &Path) {
assert!(Command::new("git").arg("init").arg("-q").arg(dir).status().unwrap().success());
}
/// A folder that is both a Git repository and an svn working copy is reported once, as Git;
/// a Git repository inside a working copy keeps its own files.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_and_svn_in_one_folder_or_nested() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
git_init(&root.join("tool"));
std::fs::write(root.join("tool/g.txt"), "g\n").unwrap();
std::fs::write(root.join("s.txt"), "s\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
until("the nested Git repository", || !project.repos().is_empty()).await;
let mut roots: Vec<(VcsKind, String)> = vcs::vcs_roots(&host, "main")
.await
.unwrap()
.into_iter()
.map(|r| (r.kind, r.root.0.file_name().unwrap().to_string_lossy().into_owned()))
.collect();
roots.sort_by(|a, b| a.1.cmp(&b.1));
assert_eq!(roots, [(VcsKind::Git, "tool".to_owned()), (VcsKind::Subversion, "wc".to_owned())]);
let status = vcs::vcs_status(&host, "main").await.unwrap();
let mut rows: Vec<String> =
status.iter().map(|f| f.path.0.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/")).collect();
rows.sort();
let rows: Vec<&str> = rows.iter().map(String::as_str).collect();
assert!(rows.contains(&"s.txt") && rows.contains(&"tool/g.txt"), "{rows:?}");
assert!(!rows.contains(&"tool"), "the Git repository is no unversioned folder of the working copy: {rows:?}");
// Both in one folder.
let both = fx.checkout("both");
git_init(&both);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&both, true, false).unwrap();
let project = host.open_project("both", &both).unwrap();
until("the Git repository", || !project.repos().is_empty()).await;
tokio::time::sleep(Duration::from_millis(500)).await;
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "both").await.unwrap().into_iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Git]);
}
/// A working copy inside a Git project's folder is found, as a nested Git repository is.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_inside_a_git_project() {
let Some(fx) = fixture() else { return };
let root = fx.base.join("gitproject");
std::fs::create_dir(&root).unwrap();
git_init(&root);
// Not `vendor/`: dependency folders are skipped, for nested Git repositories too.
fx.svn(&root, &["checkout", "-q", &format!("{}/trunk", fx.url), "parts"]);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
assert_eq!(project.backends()[0].root(), root.join("parts"));
}
/// The project tree's Delete schedules a file for deletion; its Undo brings the file back and
/// takes the deletion back, keeping the restored content. (Review A4.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn undo_of_a_delete_takes_the_deletion_back() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let file = root.join("notes.txt");
std::fs::write(&file, "base\n").unwrap();
std::fs::create_dir(root.join("docs")).unwrap();
std::fs::write(root.join("docs/a.txt"), "a\n").unwrap();
std::fs::write(root.join("docs/b.txt"), "b\n").unwrap();
fx.svn(&root, &["add", "-q", "notes.txt", "docs"]);
fx.svn(&root, &["commit", "-q", "-m", "notes"]);
std::fs::write(&file, "edited before the delete\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
// What Delete does (`delete_recorded`: the same paths, history, removal and backend hook),
// without the system Trash `fs_delete_with_undo` moves things to.
let delete = |path: &Path| {
let paths = ide_workspace::file_ops::deletion_paths(path).unwrap();
let undo = project.history.capture_deletion_undo(&paths, 1 << 20);
if path.is_dir() {
std::fs::remove_dir_all(path).unwrap()
} else {
std::fs::remove_file(path).unwrap()
}
project.with_backend_of(path, |b| b.files_deleted(&paths)).unwrap();
undo
};
let undo = delete(&file);
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("notes.txt".into(), ChangeKind::Deleted)]);
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "edited before the delete\n");
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("notes.txt".into(), ChangeKind::Modified)]);
assert!(fx.svn(&root, &["status", "notes.txt"]).starts_with('M'), "no longer scheduled for deletion");
// A folder: every file in it comes back, none scheduled for deletion.
let undo = delete(&root.join("docs"));
assert!(fx.svn(&root, &["status", "docs"]).lines().all(|l| l.starts_with('D')));
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("docs/b.txt")).unwrap(), "b\n");
assert_eq!(fx.svn(&root, &["status", "docs"]), "", "the folder is as committed");
}
/// In a project with a Git repository and a working copy, a working copy that cannot report
/// its changes does not hide the Git ones, and the window is told once. (Review A13.)
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_that_cannot_report_is_told() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
git_init(&root.join("tool"));
std::fs::write(root.join("tool/g.txt"), "g\n").unwrap();
// svn as the project has it: fails `status` once told to.
let broken = fx.base.join("broken");
let real = which("svn").unwrap();
let svn = script(
&fx.base,
"flaky-svn",
&format!(
"#!/bin/sh\nif [ -e '{}' ] && [ \"$1\" = status ]; then echo 'svn: E155036: format too old' >&2; exit 1; fi\nexec '{}' \"$@\"\n",
broken.display(),
real.display()
),
);
std::fs::create_dir(root.join(".openidea")).unwrap();
fx.svn(&root, &["propset", "-q", "svn:ignore", ".openidea\ntool", "."]);
std::fs::write(
root.join(".openidea/settings.toml"),
format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
let told: Arc<parking_lot::Mutex<Vec<String>>> = Arc::default();
let mut config = common::host_config(&fx.base);
let seen = told.clone();
config.sink_for = Box::new(move |_: &str| {
let seen = seen.clone();
Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::Notify { title, .. } = event {
seen.lock().push(title);
}
})
});
let host = Host::new(config).with_subversion(false);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
until("the Git repository", || !project.repos().is_empty()).await;
std::fs::write(&broken, "").unwrap();
for _ in 0..3 {
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert!(status.iter().any(|f| f.path.0.ends_with("tool/g.txt")), "{status:?}");
}
let told = told.lock().clone();
assert_eq!(told.iter().filter(|t| t.starts_with("Changes of ")).count(), 1, "{told:?}");
}
/// Get from Version Control › Subversion reports svn's progress line by line, and its Cancel
/// stops a checkout the server holds up. (Review A7, F3.)
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_checkout_reports_progress_and_can_be_cancelled() {
let Some(fx) = fixture() else { return };
if !have(&["svnserve"]) {
return;
}
let seed = fx.checkout("seed");
for name in ["a.txt", "b.txt"] {
std::fs::write(seed.join(name), "x\n").unwrap();
}
fx.svn(&seed, &["add", "-q", "a.txt", "b.txt"]);
fx.svn(&seed, &["commit", "-q", "-m", "files"]);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
let lines: Arc<parking_lot::Mutex<Vec<String>>> = Arc::default();
let seen = lines.clone();
let channel = ide_host::ops::Channel::new(move |line: String| seen.lock().push(line));
let dest = fx.base.join("fresh");
svn::svn_checkout(&host, "main", ide_core::RequestId::next(), format!("{}/trunk", fx.url), dest.clone(), channel)
.await
.unwrap();
let lines = lines.lock().clone();
assert!(lines.iter().any(|l| l.ends_with("a.txt")) && lines.iter().any(|l| l.ends_with("b.txt")), "{lines:?}");
// A server that stops answering: Cancel returns at once.
std::fs::write(fx.base.join("repo/conf/svnserve.conf"), "[general]\nanon-access = read\n").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let server = Svnserve(
Command::new("svnserve")
.args([
"-d",
"--foreground",
"--threads",
"--listen-host",
"127.0.0.1",
"--listen-port",
&port.to_string(),
"-r",
])
.arg(fx.base.join("repo"))
.spawn()
.unwrap(),
);
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
std::thread::sleep(Duration::from_millis(50));
}
let pid = server.0.id().to_string();
assert!(Command::new("kill").args(["-STOP", &pid]).status().unwrap().success());
let request = ide_core::RequestId::next();
let host = Arc::new(host);
let running = {
let host = host.clone();
let channel = ide_host::ops::Channel::new(|_: String| {});
let url = format!("svn://127.0.0.1:{port}/trunk");
let dest = fx.base.join("stuck");
tokio::spawn(async move { svn::svn_checkout(&host, "main", request, url, dest, channel).await })
};
tokio::time::sleep(Duration::from_millis(1500)).await;
let started = std::time::Instant::now();
host.cancel_request(request);
let result = tokio::time::timeout(Duration::from_secs(20), running).await;
let _ = Command::new("kill").args(["-CONT", &pid]).status();
drop(server);
let err = result.expect("cancel stops the checkout").unwrap().unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled, "{err:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
/// What `smoke/svn.test.ts` checks, through `openidea-server`'s protocol (in-memory, as
/// `tests/rpc.rs` does) so that CI's Rust job runs it: the server finds the working copy of a
/// trusted project and lists, commits and logs it with svn non-interactive. (Review T2.)
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_working_copy_through_the_server_protocol() {
use ide_host::rpc::{self, Dispatcher, Invoke};
use serde_json::{Value, json};
struct Client;
impl ide_jsonrpc::Handler for Client {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let slot = Arc::new(std::sync::OnceLock::new());
let sink_peer = slot.clone();
// As openidea-server builds its host: svn without prompts.
let host = Arc::new(
Host::new(ide_host::HostConfig {
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))),
..common::host_config(&fx.base)
})
.with_subversion(false),
);
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host.clone(), Dispatcher::standard(), slot, sr, sw));
let (cr, cw) = tokio::io::split(client_io);
let peer = ide_jsonrpc::Peer::connect(cr, cw, Arc::new(Client));
let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
let invoke = |cmd: &str, args: Value| {
let call = Invoke { window: "main".into(), cmd: cmd.into(), args };
let peer = &peer;
async move { peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply) }
};
invoke("open_project", json!({ "path": root })).await.unwrap();
invoke("project_trust_set", json!({ "path": root, "trusted": true, "folder": false })).await.unwrap();
let mut kinds = Value::Null;
for _ in 0..500 {
kinds = invoke("vcs_roots", json!({})).await.unwrap();
if kinds.as_array().is_some_and(|r| !r.is_empty()) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(kinds[0]["kind"], "subversion", "{kinds}");
assert_eq!(invoke("vcs_branch_info", json!({ "repo": null })).await.unwrap()["head"], "trunk");
let notes = root.join("notes.txt");
std::fs::write(&notes, "first\n").unwrap();
let status = invoke("vcs_status", json!({})).await.unwrap();
assert_eq!(status[0]["relPath"], "notes.txt");
assert_eq!(status[0]["unstaged"], "untracked");
let options = json!({ "amend": false, "signOff": false, "author": null, "runHooks": true, "stage": [notes] });
let revision =
invoke("vcs_commit", json!({ "repo": null, "message": "Add notes", "options": options })).await.unwrap();
assert_eq!(revision, "2");
assert_eq!(invoke("vcs_status", json!({})).await.unwrap(), json!([]));
let query = json!({ "branch": null, "path": null, "author": null, "text": null, "skip": 0, "limit": 10 });
let log = invoke("vcs_log", json!({ "repo": null, "query": query })).await.unwrap();
let summaries: Vec<&str> = log.as_array().unwrap().iter().filter_map(|c| c["summary"].as_str()).collect();
assert_eq!(summaries, ["Add notes", "layout"]);
}
-1
Переглянути файл
@@ -250,7 +250,6 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_branches", "", vcs::vcs_branches(host, w, root())),
call!("vcs_stashes", "", vcs::vcs_stashes(host, w, root())),
call!("vcs_conflict_versions", "", vcs::vcs_conflict_versions(host, w, file.clone())),
call!("vcs_conflict_details", "", vcs::vcs_conflict_details(host, w, file.clone())),
call!("vcs_diff_text", "", vcs::vcs_diff_text(host, w, file.clone(), false)),
call!("vcs_config_get", "", vcs::vcs_config_get(host, w, root(), "user.name".into())),
call!("vcs_config_get_bool", "", vcs::vcs_config_get_bool(host, w, root(), "log.showSignature".into())),
-640
Переглянути файл
@@ -1,640 +0,0 @@
//! A version control system besides Git plugs in through `BackendProvider`, the way
//! Perforce and Subversion do: an in-memory fake here, so nothing but `git` has to be
//! installed.
mod common;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_host::{
Host,
ops::{fs, vcs},
};
use ide_vcs::{
Backend, BackendChangelist, BackendProvider, BlameLine, BlockHistory, Branch, ChangeKind, ChangedFile, Commit,
CommitOptions, FileStatus, LineHunk, LogDetails, LogQuery, PendingChange, RevisionChange, TextEncoding, VcsKind,
};
use parking_lot::Mutex;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
/// A working copy whose root holds a `.fake-vcs` file. Its changes are whatever the test
/// says; it remembers what it was asked to stage and open for edit.
struct Fake {
root: PathBuf,
changed: Mutex<Vec<PathBuf>>,
unreachable: AtomicBool,
staged: Mutex<Vec<PathBuf>>,
opened: Mutex<Vec<PathBuf>>,
/// The line of development checked out (`trunk` until switched).
head: Mutex<String>,
/// Its own changelists, named lists like Subversion's.
lists: Mutex<Vec<BackendChangelist>>,
}
impl Backend for Fake {
fn root(&self) -> &Path {
&self.root
}
fn kind(&self) -> VcsKind {
VcsKind::Perforce
}
fn head_label(&self) -> Option<String> {
Some(self.head.lock().clone())
}
fn update(&self, _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> {
std::fs::write(self.root.join("a.txt"), "updated\n")?;
output("Updated to revision 8.".into());
Ok(())
}
fn branches(&self) -> IdeResult<Vec<Branch>> {
let head = self.head.lock().clone();
Ok(["trunk", "branches/x"]
.map(|name| Branch {
name: name.into(),
remote: false,
current: name == head,
upstream: None,
tracked_tip: None,
ahead: 0,
behind: 0,
outgoing: None,
last_commit_ms: 0.0,
commit: String::new(),
})
.into())
}
fn switch_to(&self, branch: &str) -> IdeResult<()> {
*self.head.lock() = branch.into();
Ok(())
}
fn changelists(&self) -> IdeResult<Option<Vec<BackendChangelist>>> {
Ok(Some(self.lists.lock().clone()))
}
fn create_changelist(&self, name: &str, comment: &str) -> IdeResult<String> {
let list = BackendChangelist { id: name.into(), name: name.into(), comment: comment.into(), files: Vec::new() };
self.lists.lock().push(list);
Ok(name.into())
}
fn edit_changelist(&self, id: &str, name: &str, comment: &str) -> IdeResult<()> {
let mut lists = self.lists.lock();
let list = lists.iter_mut().find(|l| l.id == id).ok_or_else(|| IdeError::not_found(id))?;
(list.name, list.comment) = (name.into(), comment.into());
Ok(())
}
fn delete_changelist(&self, id: &str) -> IdeResult<()> {
self.lists.lock().retain(|l| l.id != id);
Ok(())
}
fn move_to_changelist(&self, paths: &[PathBuf], id: &str) -> IdeResult<()> {
let mut lists = self.lists.lock();
for list in lists.iter_mut() {
list.files.retain(|f| !paths.contains(&f.0));
}
if let Some(list) = lists.iter_mut().find(|l| l.id == id) {
list.files.extend(paths.iter().map(|p| p.clone().into()));
}
Ok(())
}
fn status(&self) -> IdeResult<Vec<FileStatus>> {
if self.unreachable.load(Ordering::Acquire) {
return Err(IdeError::unavailable("server unreachable"));
}
Ok(self
.changed
.lock()
.iter()
.map(|p| FileStatus {
path: p.clone().into(),
rel_path: p.strip_prefix(&self.root).unwrap().to_string_lossy().into_owned(),
staged: None,
unstaged: Some(ChangeKind::Modified),
renamed_from: None,
})
.collect())
}
fn file_bytes_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
Ok(None)
}
fn file_at(&self, _: &Path, _: Option<&str>, _: TextEncoding) -> IdeResult<Option<String>> {
Ok(None)
}
fn file_mode_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<String>> {
Ok(None)
}
fn diff_text(&self, _: &Path, _: bool, _: TextEncoding) -> IdeResult<String> {
Ok(String::new())
}
fn working_tree_patch(
&self,
_: Option<&Path>,
_: Option<&str>,
_: usize,
_: &CancellationToken,
) -> IdeResult<String> {
Ok(String::new())
}
fn line_hunks(&self, _: &Path, _: &str, _: bool, _: TextEncoding) -> IdeResult<Vec<LineHunk>> {
Ok(Vec::new())
}
fn blame(&self, _: &Path, _: Option<&str>, _: Option<&str>, _: TextEncoding) -> IdeResult<Vec<BlameLine>> {
Ok(Vec::new())
}
fn block_history(
&self,
_: &Path,
_: Option<&str>,
_: (u32, u32),
_: TextEncoding,
_: &CancellationToken,
) -> IdeResult<BlockHistory> {
Err(IdeError::unavailable("no block history"))
}
fn log(&self, _: &LogQuery, _: &CancellationToken) -> IdeResult<Vec<Commit>> {
Ok(Vec::new())
}
fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
Ok(LogDetails {
message: format!("change {revision}"),
containing_branches: Vec::new(),
signature: "N".into(),
signer: String::new(),
key: String::new(),
fingerprint: String::new(),
})
}
fn commit_files(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn commits_changes(&self, _: &[String]) -> IdeResult<Vec<RevisionChange>> {
Ok(Vec::new())
}
fn diff_revisions(&self, _: &str, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn diff_with_worktree(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
Ok(Vec::new())
}
fn numstat_with_worktree(&self, _: &str) -> IdeResult<Vec<(String, u32, u32)>> {
Ok(Vec::new())
}
fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
self.staged.lock().extend_from_slice(paths);
Ok(())
}
fn unstage(&self, _: &[PathBuf]) -> IdeResult<()> {
Ok(())
}
/// Reverts: the file gets its depot text back.
fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
for path in paths {
std::fs::write(path, "depot\n")?;
}
self.changed.lock().retain(|p| !paths.contains(p));
Ok(())
}
fn commit(&self, _: &str, _: &CommitOptions, _: &dyn Fn(&Path) -> IdeResult<TextEncoding>) -> IdeResult<String> {
Err(IdeError::unavailable("no submit"))
}
fn pending_changes(
&self,
_: &CommitOptions,
_: usize,
_: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<PendingChange>> {
Ok(Vec::new())
}
fn open_for_edit(&self, paths: &[PathBuf]) -> IdeResult<bool> {
self.opened.lock().extend_from_slice(paths);
Ok(true)
}
}
/// Finds the folder holding `.fake-vcs` at or above the one asked about; counts the questions.
#[derive(Default)]
struct Provider {
asked: AtomicUsize,
/// While set, `discover` waits (a slow client); `answered` counts the answers given.
hold: AtomicBool,
answered: AtomicUsize,
found: Mutex<Vec<Arc<Fake>>>,
}
impl Provider {
fn fake(&self) -> Arc<Fake> {
self.found.lock().first().cloned().expect("a working copy was discovered")
}
fn fake_at(&self, root: &Path) -> Arc<Fake> {
self.found.lock().iter().find(|f| f.root == root).cloned().expect("a working copy at that root")
}
}
impl BackendProvider for Provider {
fn marker(&self) -> Option<&str> {
Some(".fake-vcs")
}
fn discover(&self, folder: &Path) -> IdeResult<Option<Arc<dyn Backend>>> {
self.asked.fetch_add(1, Ordering::AcqRel);
while self.hold.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(5));
}
let _answered = Answered(&self.answered);
let Some(root) = folder.ancestors().find(|dir| dir.join(".fake-vcs").is_file()) else { return Ok(None) };
let mut found = self.found.lock();
let fake = match found.iter().find(|f| f.root == root) {
Some(fake) => fake.clone(),
None => {
let fake = Arc::new(Fake {
root: root.to_path_buf(),
changed: Mutex::default(),
unreachable: AtomicBool::new(false),
staged: Mutex::default(),
opened: Mutex::default(),
head: Mutex::new("trunk".into()),
lists: Mutex::default(),
});
found.push(fake.clone());
fake
}
};
Ok(Some(fake))
}
}
/// Counts an answer when `discover` returns, whichever way.
struct Answered<'a>(&'a AtomicUsize);
impl Drop for Answered<'_> {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::AcqRel);
}
}
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
fn host(base: &Path, provider: &Arc<Provider>) -> Host {
Host::new(common::host_config(base)).with_vcs_provider(provider.clone())
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..500 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
fn paths(status: &[FileStatus]) -> BTreeSet<PathBuf> {
status.iter().map(|f| f.path.0.clone()).collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_answers_the_shared_vcs_commands() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
let file = root.join("a.txt");
std::fs::write(&file, "edited\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
let fake = provider.fake();
fake.changed.lock().push(file.clone());
assert_eq!(paths(&vcs::vcs_status(&host, "main").await.unwrap()), BTreeSet::from([file.clone()]));
assert_eq!(paths(&vcs::vcs_status_paths(&host, "main", vec![file.clone()]).await.unwrap()).len(), 1);
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots.len(), 1);
assert_eq!((roots[0].root.0.as_path(), roots[0].kind), (root.as_path(), VcsKind::Perforce));
assert_eq!(roots[0].head.as_deref(), Some("trunk"));
let info = vcs::vcs_branch_info(&host, "main", None).await.unwrap();
assert_eq!(info.head.as_deref(), Some("trunk"));
// The log comes from the working copy; Git-only reads (refs, stashes) answer nothing.
assert!(vcs::vcs_log(&host, "main", None, LogQuery::default()).await.unwrap().is_empty());
assert_eq!(vcs::vcs_log_details(&host, "main", None, "7".into()).await.unwrap().message, "change 7");
assert!(vcs::vcs_log_refs(&host, "main", Some(root.clone())).await.unwrap().is_empty());
assert!(vcs::vcs_stashes(&host, "main", None).await.unwrap().is_empty());
vcs::vcs_stage(&host, "main", vec![file.clone()]).await.unwrap();
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&file));
fs::fs_set_writable(&host, "main", file.clone(), true).await.unwrap();
assert_eq!(*fake.opened.lock(), std::slice::from_ref(&file));
// Rollback rewrites the file: Local History keeps the text from before, between labels.
vcs::vcs_discard(&host, "main", vec![file.clone()]).await.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "depot\n");
let history = project.history.list(&file).unwrap();
let labels: Vec<&str> = history.iter().map(|e| e.label.as_str()).collect();
assert!(labels.contains(&"After Rollback") && labels.contains(&"Before Rollback"), "{labels:?}");
let snapshot = history.iter().find(|e| !e.id.is_empty() && e.label == "Before Rollback").expect("a snapshot");
assert_eq!(project.history.content(&snapshot.id).unwrap(), "edited\n");
// Update Project and the branch widget use the shared commands too.
let output = Arc::new(Mutex::new(Vec::new()));
let lines = output.clone();
let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line));
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert!(report.is_none());
assert_eq!(*output.lock(), ["Updated to revision 8."]);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n");
let labels: Vec<String> = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect();
assert!(labels.iter().any(|l| l == "Before Update") && labels.iter().any(|l| l == "After Update"), "{labels:?}");
let branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
assert_eq!(
branches.iter().map(|b| (b.name.as_str(), b.current)).collect::<Vec<_>>(),
[("trunk", true), ("branches/x", false)]
);
let outcome = vcs::vcs_checkout(&host, "main", None, "branches/x".into(), false, None, None).await.unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/x"));
assert!(vcs::vcs_checkout(&host, "main", None, "branches/y".into(), true, None, None).await.is_err());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_inside_a_working_copy_keeps_its_files_and_its_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let lib = root.join("lib");
std::fs::create_dir_all(&lib).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
git(&lib, &["init", "-q", "-b", "main"]);
git(&lib, &["config", "user.name", "Test"]);
git(&lib, &["config", "user.email", "[email protected]"]);
std::fs::write(lib.join("tracked.txt"), "one\n").unwrap();
git(&lib, &["add", "."]);
git(&lib, &["commit", "-qm", "first"]);
let (outside, tracked, untracked) = (root.join("a.txt"), lib.join("tracked.txt"), lib.join("new.txt"));
std::fs::write(&outside, "edited\n").unwrap();
std::fs::write(&untracked, "new\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("Git and the working copy", || !project.backends().is_empty() && !project.repos().is_empty()).await;
let fake = provider.fake();
// The working copy claims a file of the nested Git repository too: Git keeps it.
fake.changed.lock().extend([outside.clone(), tracked.clone()]);
assert!(project.backend_of(&outside).is_some());
assert!(project.backend_of(&tracked).is_none() && project.backend_of(&lib).is_none());
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([outside.clone(), untracked.clone()]));
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Git, VcsKind::Perforce]);
// Each path goes to its own backend.
vcs::vcs_stage(&host, "main", vec![outside.clone(), untracked.clone()]).await.unwrap();
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&outside));
assert_eq!(git(&lib, &["status", "--porcelain", "new.txt"]), "A new.txt");
// The working copy's own changelists; the Git root keeps the IDE's lists.
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(lib.clone())).await.unwrap(), None);
let id = vcs::vcs_backend_changelist_create(&host, "main", Some(root.clone()), "ui".into(), String::new())
.await
.unwrap();
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
assert!(vcs::vcs_backend_changelist_move(&host, "main", vec![untracked.clone()], id.clone()).await.is_err());
// A list with a path in no working copy is refused whole: nothing moves, not even the
// paths that would have been valid on their own.
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], "default".into()).await.unwrap();
let mixed = vec![outside.clone(), untracked.clone()];
assert!(vcs::vcs_backend_changelist_move(&host, "main", mixed, id.clone()).await.is_err());
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
assert!(lists.iter().all(|l| l.files.is_empty()), "{lists:?}");
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
vcs::vcs_backend_changelist_edit(&host, "main", Some(root.clone()), id.clone(), "UI".into(), "menus".into())
.await
.unwrap();
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
assert_eq!(lists.len(), 1);
assert_eq!((lists[0].name.as_str(), lists[0].comment.as_str()), ("UI", "menus"));
assert_eq!(lists[0].files.iter().map(|f| f.0.clone()).collect::<Vec<_>>(), std::slice::from_ref(&outside));
vcs::vcs_backend_changelist_delete(&host, "main", Some(root.clone()), id).await.unwrap();
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap(), Some(Vec::new()));
assert!(
vcs::vcs_backend_changelist_create(&host, "main", Some(lib.clone()), "x".into(), String::new()).await.is_err()
);
// A server that cannot be reached leaves the Git changes visible.
fake.unreachable.store(true, Ordering::Release);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([untracked.clone()]));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_at_a_git_root_is_left_to_git() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
git(&root, &["init", "-q", "-b", "main"]);
let untracked = root.join("new.txt");
std::fs::write(&untracked, "new\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends.read().is_empty()).await;
provider.fake().changed.lock().push(untracked.clone());
// Found, but shadowed: the root is reported once, as Git's, and Git answers for it.
assert!(project.backends().is_empty() && project.backend_at(Some(&root)).is_none());
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
let roots: Vec<_> = roots.iter().map(|r| (r.root.0.clone(), r.kind)).collect();
assert_eq!(roots, [(root.clone(), VcsKind::Git)]);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([root.join(".fake-vcs"), untracked.clone()]));
assert!(status.iter().all(|f| f.unstaged == Some(ChangeKind::Untracked)));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_mode_asks_no_provider_until_the_project_is_trusted() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
std::fs::create_dir_all(root.join("inner")).unwrap();
std::fs::write(root.join("inner/.fake-vcs"), "").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
let project = host.open_project("main", &root).unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
project.refresh_backends();
assert_eq!(provider.asked.load(Ordering::Acquire), 0);
assert!(project.backends().is_empty() && project.backend_of(&root.join("a.txt")).is_none());
assert!(vcs::vcs_status(&host, "main").await.is_err());
host.set_project_trust(&root, true, false).await.unwrap();
until("both working copies", || project.backends().len() == 2).await;
assert!(provider.asked.load(Ordering::Acquire) > 0);
assert!(vcs::vcs_status(&host, "main").await.unwrap().is_empty());
host.set_project_trust(&root, false, false).await.unwrap();
assert!(project.backends().is_empty());
until("the working copy to go", || project.backends.read().is_empty()).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_slow_scan_started_before_restricting_does_not_bring_the_working_copy_back() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join(".fake-vcs"), "").unwrap();
let provider = Arc::new(Provider::default());
provider.hold.store(true, Ordering::Release);
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan to ask", || provider.asked.load(Ordering::Acquire) > 0).await;
// Restricted while the opening scan still waits for its answer: the rescan this starts
// must come after it, not before.
host.set_project_trust(&root, false, false).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
provider.hold.store(false, Ordering::Release);
until("the opening scan's answer", || provider.answered.load(Ordering::Acquire) > 0).await;
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(project.backends.read().is_empty());
}
fn roots_of(project: &ide_host::Project) -> BTreeSet<PathBuf> {
project.backends().iter().map(|b| b.root().to_path_buf()).collect()
}
fn marked(dir: &Path) {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(".fake-vcs"), "").unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_copies_nested_in_a_working_copy_are_found_like_nested_git_repositories() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
// A separate checkout inside the working copy, a directory external two levels down, and
// one in a dependency folder that is never searched.
let (inner, external) = (root.join("inner"), root.join("ext/lib"));
for dir in [&root, &inner, &external, &root.join("node_modules/pkg")] {
marked(dir);
}
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the nested working copies", || project.backends().len() == 3).await;
assert_eq!(roots_of(&project), BTreeSet::from([root.clone(), inner.clone(), external.clone()]));
// The deepest working copy owns a path.
let owner = |path: &Path| project.backend_of(path).map(|b| b.root().to_path_buf());
assert_eq!(owner(&inner.join("b.txt")), Some(inner.clone()));
assert_eq!(owner(&external.join("x.txt")), Some(external.clone()));
assert_eq!(owner(&root.join("ext/y.txt")), Some(root.clone()));
assert_eq!(owner(&root.join("node_modules/pkg/z.txt")), Some(root.clone()));
// Each changed file is listed once, by its own working copy.
let (outer_file, inner_file) = (root.join("a.txt"), inner.join("b.txt"));
provider.fake_at(&root).changed.lock().extend([outer_file.clone(), inner_file.clone()]);
provider.fake_at(&inner).changed.lock().push(inner_file.clone());
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(status.len(), 2, "{status:?}");
assert_eq!(paths(&status), BTreeSet::from([outer_file, inner_file]));
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Perforce; 3]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_inside_a_git_project_is_found() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let wc = root.join("vendor-src/wc");
std::fs::create_dir_all(&root).unwrap();
git(&root, &["init", "-q", "-b", "main"]);
marked(&wc);
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("Git and the working copy", || !project.repos().is_empty() && !project.backends().is_empty()).await;
assert_eq!(roots_of(&project), BTreeSet::from([wc.clone()]));
assert!(project.backend_of(&wc.join("a.txt")).is_some());
assert!(project.backend_of(&root.join("a.txt")).is_none());
let roots: Vec<_> =
vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| (r.root.0.clone(), r.kind)).collect();
assert_eq!(roots, [(root.clone(), VcsKind::Git), (wc.clone(), VcsKind::Perforce)]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_checked_out_in_the_open_project_shows_up_and_goes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/main.txt"), "x\n").unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan", || provider.answered.load(Ordering::Acquire) > 0).await;
assert!(project.backends().is_empty());
// A checkout writes its folder, the marker, then the files.
let checkout = root.join("checkout");
marked(&checkout);
std::fs::write(checkout.join("a.txt"), "a\n").unwrap();
until("the new working copy", || roots_of(&project) == BTreeSet::from([checkout.clone()])).await;
std::fs::remove_dir_all(&checkout).unwrap();
until("the removed working copy to go", || project.backends().is_empty()).await;
}
/// A folder with a marker that never becomes a working copy (svn missing, an old format) is
/// asked about once, not again on every file saved in it, until its marker changes. (Review N3.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_folder_that_is_no_working_copy_is_not_asked_about_on_every_save() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan", || provider.answered.load(Ordering::Acquire) > 0).await;
// The fake provider finds working copies by a marker file; a marker folder is none.
let broken = root.join("broken");
std::fs::create_dir_all(broken.join(".fake-vcs")).unwrap();
std::fs::write(broken.join("a.txt"), "a\n").unwrap();
let asked = || provider.asked.load(Ordering::Acquire);
until("the folder to be asked about", || asked() > 1).await;
// Let the scan finish, then save there again and again.
until("the scan's answers", || provider.answered.load(Ordering::Acquire) == asked()).await;
tokio::time::sleep(Duration::from_millis(300)).await;
let after_first = asked();
for i in 0..5 {
std::fs::write(broken.join(format!("b{i}.txt")), "b\n").unwrap();
tokio::time::sleep(Duration::from_millis(150)).await;
}
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(asked(), after_first, "saving in it scans no more");
assert!(project.backends().is_empty());
}
-57
Переглянути файл
@@ -572,60 +572,3 @@ async fn a_repository_created_in_the_project_is_known_when_init_returns() {
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
assert_eq!(roots, [project_root]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vcs_roots_reports_unavailable_root_until_it_returns() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let project_root = base.join("project");
let external_main = base.join("external-main");
let wt = project_root.join("wt");
let healthy = project_root.join("healthy");
for root in [&external_main, &healthy] {
std::fs::create_dir_all(root).unwrap();
git(root, &["init", "-b", "main"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
std::fs::write(root.join("file.txt"), "hello\n").unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-m", "initial"]);
}
git(&external_main, &["worktree", "add", "-b", "wt-branch", wt.to_str().unwrap()]);
let host = Host::new(common::host_config(&base));
host.trust.decide(&project_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
for _ in 0..500 {
if project.repos().all().len() == 2 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(project.repos().all().len(), 2);
// Move the linked worktree's metadata dir (outside project_root) aside so the project FileWatcher never races.
let wt_git_dir = external_main.join(".git/worktrees/wt");
let parked_git_dir = base.join("parked-wt-git");
std::fs::rename(&wt_git_dir, &parked_git_dir).unwrap();
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
let wt_root = roots.iter().find(|r| r.root.0 == wt).unwrap();
let healthy_root = roots.iter().find(|r| r.root.0 == healthy).unwrap();
assert!(wt_root.unavailable);
assert!(wt_root.head.is_none());
assert!(wt_root.head_commit.is_none());
assert!(wt_root.operation.is_none());
assert!(wt_root.has_remotes.is_none());
assert_eq!(wt_root.branch_root.0, wt);
assert!(!healthy_root.unavailable);
assert_eq!(healthy_root.head.as_deref(), Some("main"));
std::fs::rename(&parked_git_dir, &wt_git_dir).unwrap();
let restored = vcs::vcs_roots(&host, "main").await.unwrap();
let wt_restored = restored.iter().find(|r| r.root.0 == wt).unwrap();
let healthy_restored = restored.iter().find(|r| r.root.0 == healthy).unwrap();
assert!(!wt_restored.unavailable);
assert_eq!(wt_restored.head.as_deref(), Some("wt-branch"));
assert!(!healthy_restored.unavailable);
host.close_project("main");
}
+1 -50
Переглянути файл
@@ -28,10 +28,6 @@ struct Fixture {
impl Fixture {
async fn new() -> Self {
Self::with_sink(Arc::new(ide_core::NullSink)).await
}
async fn with_sink(sink: ide_core::SharedSink) -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -44,8 +40,7 @@ impl Fixture {
std::fs::write(root.join("file.txt"), "original\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "original"]);
let host =
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
wait_for_repos(&project, 1).await;
@@ -283,50 +278,6 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
/// slow git lets the watcher rescan in between and find no repository there yet.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = changes.clone();
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
let f = Fixture::with_sink(sink).await;
// The watcher reports a batch that rescans only once the rescan is done.
let next_change = || {
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
async move {
for _ in 0..200 {
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("the watcher reported no change");
}
};
let linked = f.root.join("watched");
let gitdir = f.root.join(".git/worktrees/watched");
let registered = next_change();
std::fs::create_dir_all(&gitdir).unwrap();
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
registered.await;
let rescanned = next_change();
std::fs::create_dir_all(&linked).unwrap();
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
rescanned.await;
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
// As git does: through a lock file.
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
wait_for_repos(&f.project, 2).await;
assert!(f.project.repos().roots().contains(&linked));
}
impl Fixture {
async fn open(&self, root: &std::path::Path) {
self.host.trust.decide(root, true, false).unwrap();
-71
Переглянути файл
@@ -530,77 +530,6 @@ src/local/
assert!(listed[0].ignored);
}
#[test]
fn root_anchored_gitignore_is_honoured_and_does_not_match_nested_names() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for f in ["src/a.rs", "build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs"] {
touch(&root, f);
}
std::fs::write(
root.join(".gitignore"),
"# Flutter-style root build output
/build/
tmp/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
// Root-anchored `/build/` ignores only the root `build/` tree. Unanchored
// `tmp/` is also filename-only. A nested directory named `build` is kept.
assert_eq!(
found,
[
(".gitignore", false),
("build/gen.rs", true),
("build/nested/out.rs", true),
("packages/foo/build/x.rs", false),
("src/a.rs", false),
("tmp/scratch.rs", true),
]
.map(|(p, i)| (p.to_owned(), i))
);
for rel in ["build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs", "src/a.rs"] {
assert!(!filter.is_excluded(&root.join(rel)), "{rel}");
}
let mut listed: Vec<(String, bool)> = filter
.list_dir(&root.join("build"))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
listed.sort();
assert_eq!(listed, [("build/gen.rs", true)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn root_anchored_exclude_file_is_honoured() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
touch(&root, "src/a.rs");
touch(&root, "build/gen.rs");
std::fs::create_dir_all(root.join(".git/info")).unwrap();
std::fs::write(
root.join(".git/info/exclude"),
"/build/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
assert_eq!(found, [("build/gen.rs", true), ("src/a.rs", false)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn a_nested_repository_is_not_hidden_by_the_outer_repositorys_gitignore() {
let dir = tempfile::tempdir().unwrap();
-4
Переглянути файл
@@ -390,10 +390,6 @@ impl Store {
})
}
pub(crate) fn snapshot_exists(&self) -> bool {
self.snapshot.is_file()
}
fn open_db(&self) -> Result<Database> {
let file = self.snapshot.with_file_name("index.redb");
let db = match Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file) {
+8 -51
Переглянути файл
@@ -601,11 +601,8 @@ impl Shared {
d.remove(path);
}
}
let index_changed = !stale.is_empty() || !todo.is_empty();
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
if !stale.is_empty() {
self.persist(&[], &stale, false);
}
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
@@ -677,31 +674,25 @@ impl Shared {
return None;
}
let durable_started = Instant::now();
if index_changed {
self.persist(&[], &[], true);
}
self.persist(&[], &[], true);
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
}
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -1452,40 +1443,6 @@ mod metric_tests {
assert_eq!(shared.data.read().symbol_count, 1);
}
#[test]
fn no_change_scan_skips_snapshot_rewrite() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
// A guard after every write, so save_snapshot does not discard the file
// when a directory mtime lands on the same instant as the scan start.
let guard = || SystemTime::now() + std::time::Duration::from_secs(2);
let cold = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(cold.scheduled, 1);
let snapshot = cache.join("index.snapshot");
assert!(snapshot.exists());
let before = std::fs::metadata(&snapshot).unwrap();
// A rewrite would bump mtime; give the filesystem a distinct timestamp.
std::thread::sleep(std::time::Duration::from_millis(20));
let hot = index.scan(None, &[], None, guard()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
let after = std::fs::metadata(&snapshot).unwrap();
assert_eq!(after.len(), before.len(), "a no-change scan must not rewrite the snapshot");
assert_eq!(after.modified().unwrap(), before.modified().unwrap());
std::fs::write(root.join("main.rs"), "fn renamed() {}\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let changed = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(changed.scheduled, 1);
let rewritten = std::fs::metadata(&snapshot).unwrap();
assert!(rewritten.modified().unwrap() > after.modified().unwrap(), "a changed scan must refresh the snapshot");
}
#[test]
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
let dir = tempfile::tempdir().unwrap();
+6 -12
Переглянути файл
@@ -369,20 +369,14 @@ pub fn resolve_spawn_program(command: &str, env: &[(String, String)]) -> std::pa
if path.components().count() > 1 || path.is_absolute() {
return path.to_path_buf();
}
if let Some(found) = env
let search = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.and_then(|(_, v)| ide_core::process::find_executable(command, std::ffi::OsStr::new(v)))
{
return found;
}
if let Some(shell_path) = ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v)
&& let Some(found) = ide_core::process::find_executable(command, &shell_path)
{
return found;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path())
.unwrap_or_else(|| path.to_path_buf())
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(command, &search).unwrap_or_else(|| path.to_path_buf())
}
impl Peer {
-4
Переглянути файл
@@ -227,10 +227,6 @@ pub struct LanguageServerConfig {
/// it parses a document.
#[serde(default)]
pub resync_on_configuration: bool,
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
/// Client-created request tokens are handled independently.
#[serde(default)]
pub ignored_progress_token_prefixes: Vec<String>,
/// Set by the settings hook: what the user sees as the server when another program serves
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
#[serde(skip)]
+1 -19
Переглянути файл
@@ -727,21 +727,6 @@ mod tests {
}
}
#[test]
fn java_analyzer_does_not_fill_empty_files() {
let reg = reg();
let java = reg.get(&LanguageId::new("java")).unwrap();
let analyzer = java.language_servers.iter().find(|s| s.name == "java-analyzer").unwrap();
assert_eq!(
analyzer
.initialization_options
.as_ref()
.and_then(|v| v.get("newFileTemplate"))
.and_then(toml::Value::as_bool),
Some(false)
);
}
#[test]
fn angular_server_joins_typescript_and_html_in_angular_projects() {
let reg = reg();
@@ -924,10 +909,7 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
let phpantom = &cfg.language_servers[1];
assert!(phpantom.fallback && phpantom.args.is_empty());
assert_eq!(phpantom.command, "phpantom_lsp");
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
-1
Переглянути файл
@@ -73,7 +73,6 @@ fn server_config() -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
-17
Переглянути файл
@@ -151,23 +151,6 @@ impl ClientHandler {
}
fn progress(&self, mgr: &LspManager, params: Value) {
if let Some(token) = params["token"].as_str() {
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
self.server.request_progress(mgr.sink(), TaskId(id), update);
}
return;
}
if self
.server
.config
.ignored_progress_token_prefixes
.iter()
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
{
return;
}
}
let token = progress_key(&params["token"]);
let value = &params["value"];
let kind = value.get("kind").and_then(Value::as_str);
Loaded 100 of 588 files, more files were not shown because too many files have changed in this diff. Show more