дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
75
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
e455a18bc5 | ||
|
|
b0033a869d | ||
|
|
4ed4ced5b1 | ||
|
|
7668e4a5ba | ||
|
|
4a6e0dfac1 | ||
|
|
11e8f8a101 | ||
|
|
7a27f285e6 | ||
|
|
f21ae03bdd | ||
|
|
5dacbcd0cd | ||
|
|
281c2ff1e5 | ||
|
|
4276250056 | ||
|
|
ba04491ace | ||
|
|
660a311f21 | ||
|
|
92bf9354fe | ||
|
|
54da9c2c12 | ||
|
|
9ba3150998 | ||
|
|
190e5639f1 | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 | ||
|
|
6d38521498 | ||
|
|
52e6a0f84b | ||
|
|
72873981aa | ||
|
|
d44a104ff8 | ||
|
|
23ea9cf07d | ||
|
|
cea3f4ac9c | ||
|
|
aee715f797 | ||
|
|
711349c6c1 | ||
|
|
9b2d783322 | ||
|
|
72ae354d29 | ||
|
|
dd8de05013 | ||
|
|
a547c8cdee | ||
|
|
a74d5b5dbb | ||
|
|
b895093f6b | ||
|
|
cbb9079577 | ||
|
|
44418411b8 | ||
|
|
5e23076766 | ||
|
|
689d3fd877 | ||
|
|
608ab44fca | ||
|
|
41545d38e5 | ||
|
|
4f86211dd6 | ||
|
|
203e4fbcb2 | ||
|
|
869e52f837 | ||
|
|
02e4c9c7a2 | ||
|
|
61be657209 | ||
|
|
52294c51c2 | ||
|
|
222d0b5ee3 | ||
|
|
cd8f29ea63 | ||
|
|
ba94abcb8b | ||
|
|
937eb0c3a0 | ||
|
|
b2d03ac5f0 | ||
|
|
4e735eadcb | ||
|
|
50ba6b5c56 | ||
|
|
36910712d1 | ||
|
|
5b99b8b5ab | ||
|
|
f3874b9b2e | ||
|
|
18b87b066b | ||
|
|
41a76ca0d7 | ||
|
|
1bf29ab3d7 | ||
|
|
49b52a8bfa | ||
|
|
77342b8e71 | ||
|
|
369ff7cec8 | ||
|
|
4016c410db | ||
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 |
No files matched your search
@@ -34,6 +34,7 @@ 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"
|
||||
@@ -109,7 +110,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|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|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$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"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",
|
||||
|
||||
Створено
@@ -4173,6 +4173,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — 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/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): 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">
|
||||
|
||||
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
@@ -18,6 +18,7 @@ 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
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
//! 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`) and Codex
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
|
||||
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
|
||||
//! `<home>/.codex/session_index.jsonl`).
|
||||
//! `<home>/.codex/session_index.jsonl`), and Copilot
|
||||
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
|
||||
|
||||
use super::native::claude::history;
|
||||
use serde::Serialize;
|
||||
@@ -17,7 +18,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`).
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
|
||||
pub provider: String,
|
||||
/// The id resuming it names (`--resume`, `thread/resume`).
|
||||
pub session_id: String,
|
||||
@@ -26,6 +27,9 @@ 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.
|
||||
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -246,6 +252,289 @@ 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::*;
|
||||
@@ -344,6 +633,111 @@ 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]
|
||||
|
||||
@@ -1409,19 +1409,23 @@ 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 {
|
||||
if let Some(home) = home.as_deref() {
|
||||
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") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
@@ -1488,9 +1492,21 @@ impl AgentManager {
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
let epoch = {
|
||||
let mut tasks = self.tasks.write();
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
tasks.insert(task.id.clone(), handle.clone());
|
||||
epoch
|
||||
};
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -1498,7 +1514,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") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
@@ -1526,7 +1542,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 assigns its own.
|
||||
// The host names the fork's session id for claude; codex and Copilot assign their own.
|
||||
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(root)),
|
||||
@@ -2034,46 +2050,63 @@ impl AgentManager {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
|
||||
// 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 total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
|
||||
let keep = turns.unwrap_or(total).min(total);
|
||||
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
|
||||
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
|
||||
if !capabilities.fork || (keep < total && !capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
}
|
||||
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,
|
||||
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(),
|
||||
)
|
||||
.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();
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let file = {
|
||||
let s = source.state.lock();
|
||||
let mut entries = s.history.conversation.main.entries.clone();
|
||||
@@ -2099,7 +2132,7 @@ impl AgentManager {
|
||||
};
|
||||
TaskFile {
|
||||
task,
|
||||
session_id: Some(session),
|
||||
session_id: session,
|
||||
entries,
|
||||
wanted: s.wanted.clone(),
|
||||
pending_model: None,
|
||||
@@ -2114,12 +2147,19 @@ impl AgentManager {
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: None,
|
||||
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
|
||||
}
|
||||
};
|
||||
// Copying may have started the source's agent: it stops again once idle.
|
||||
source.release_when_idle();
|
||||
if live.is_some() {
|
||||
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();
|
||||
@@ -4933,6 +4973,19 @@ 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!(
|
||||
|
||||
@@ -37,6 +37,15 @@ 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>,
|
||||
@@ -551,6 +560,7 @@ impl CopilotShim {
|
||||
"initialize" => self.initialize().await,
|
||||
"session/new" => self.new_session(¶ms).await,
|
||||
"session/load" => self.load_session(¶ms).await,
|
||||
"session/fork" => self.fork_session(¶ms).await,
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
@@ -569,7 +579,7 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
@@ -649,6 +659,25 @@ 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;
|
||||
@@ -675,7 +704,8 @@ impl CopilotShim {
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).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 Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
|
||||
let _ = settings.set(&catalog, MODEL, model_id);
|
||||
}
|
||||
@@ -686,7 +716,6 @@ 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);
|
||||
@@ -697,6 +726,28 @@ 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();
|
||||
|
||||
@@ -115,6 +115,18 @@ 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!({
|
||||
@@ -434,6 +446,39 @@ 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!({})),
|
||||
@@ -674,6 +719,81 @@ 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 =
|
||||
|
||||
@@ -370,6 +370,55 @@ 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 {
|
||||
|
||||
@@ -2191,6 +2191,41 @@ 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(©.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(©.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, ©.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() }
|
||||
}
|
||||
@@ -3241,6 +3276,58 @@ 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();
|
||||
@@ -3261,6 +3348,28 @@ 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();
|
||||
|
||||
@@ -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, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, maven_system_classpath, 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 == "test" && (!test || p.pom != start.pom)) {
|
||||
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
|
||||
@@ -180,6 +180,30 @@ 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).
|
||||
@@ -233,7 +257,7 @@ pub fn module_classpath_without_build(
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
@@ -270,7 +294,7 @@ pub fn module_classpaths(
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -298,7 +322,7 @@ pub fn module_classpaths(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
@@ -346,7 +370,8 @@ fn classpath(
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
|
||||
Ok(with_system_classpath(root, model, &target.module, classpath))
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
@@ -912,6 +937,64 @@ 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)]
|
||||
|
||||
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// 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 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
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 mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
|
||||
@@ -69,6 +69,9 @@ 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`…).
|
||||
@@ -176,6 +179,7 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -248,6 +252,7 @@ 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"),
|
||||
})
|
||||
}
|
||||
@@ -1519,7 +1524,13 @@ 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 managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.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 dependencies = ctx
|
||||
.deps
|
||||
.iter()
|
||||
@@ -1529,11 +1540,24 @@ 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: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
|
||||
scope: scope(d),
|
||||
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);
|
||||
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1592,6 +1616,7 @@ 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),
|
||||
|
||||
@@ -27,6 +27,10 @@ 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,
|
||||
|
||||
@@ -622,6 +622,30 @@ 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> {
|
||||
@@ -1240,6 +1264,35 @@ 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(
|
||||
|
||||
@@ -530,6 +530,7 @@ 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 {
|
||||
@@ -552,6 +553,7 @@ impl Default for DebuggerSettings {
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,6 +572,14 @@ 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")]
|
||||
@@ -616,6 +626,8 @@ 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,
|
||||
@@ -656,6 +668,7 @@ 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,
|
||||
@@ -800,4 +813,17 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -360,9 +360,46 @@ 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`.
|
||||
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
|
||||
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
|
||||
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)
|
||||
}
|
||||
|
||||
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
@@ -472,7 +509,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".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
pub(crate) 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
|
||||
@@ -513,24 +550,29 @@ 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(&spec.env, &spec.cwd) {
|
||||
if let Some(path) = adapter_path(env, cwd) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
probe.current_dir(&spec.cwd);
|
||||
probe.current_dir(cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.envs(spec.env.iter().cloned())
|
||||
.envs(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 Ok(None);
|
||||
return None;
|
||||
};
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
@@ -543,8 +585,9 @@ 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}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)"
|
||||
"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(),
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
msg.push_str(". ");
|
||||
@@ -1026,6 +1069,48 @@ 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() {
|
||||
|
||||
@@ -22,6 +22,7 @@ mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -1134,21 +1134,27 @@ 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);
|
||||
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),
|
||||
}
|
||||
// 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::shell_env_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(&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) => cmd.env(k, v),
|
||||
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(_) => {}
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
|
||||
+134
-62
@@ -447,6 +447,15 @@ 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 {
|
||||
@@ -1384,8 +1393,61 @@ 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 pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
for r in index_rows? {
|
||||
let mut it = r.into_iter();
|
||||
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
|
||||
else {
|
||||
@@ -1401,11 +1463,7 @@ impl DbManager {
|
||||
}),
|
||||
}
|
||||
}
|
||||
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 fk_rows = fk_rows?;
|
||||
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()) {
|
||||
@@ -1418,15 +1476,7 @@ impl DbManager {
|
||||
.collect();
|
||||
}
|
||||
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
|
||||
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
|
||||
let triggers = trigger_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
@@ -1439,26 +1489,21 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
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 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 mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
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);
|
||||
}
|
||||
match property_rows {
|
||||
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)
|
||||
}
|
||||
@@ -1669,16 +1714,16 @@ impl DbManager {
|
||||
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
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()),
|
||||
// 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 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" };
|
||||
@@ -1686,43 +1731,70 @@ 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 columns = pool
|
||||
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
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?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
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(),
|
||||
})
|
||||
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 })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let constraints = pool
|
||||
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let constraints = key_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
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?
|
||||
let indexes =
|
||||
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let grants = grant_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
.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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+224
-24
@@ -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 \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
|
||||
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,40 +697,70 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
|
||||
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') \
|
||||
"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) \
|
||||
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), default, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
/// 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", "")
|
||||
};
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
pg_get_expr(d.adbin, d.adrelid), 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 \
|
||||
"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} \
|
||||
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) -> String {
|
||||
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
|
||||
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) -> String {
|
||||
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 { "" };
|
||||
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) \
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
|
||||
ORDER BY 1"
|
||||
)
|
||||
}
|
||||
@@ -749,9 +779,10 @@ 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) -> String {
|
||||
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND tgparentid = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
@@ -840,6 +871,12 @@ 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)
|
||||
}
|
||||
@@ -999,10 +1036,42 @@ pub struct DdlColumn {
|
||||
pub name: String,
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub value: Option<DdlColumnValue>,
|
||||
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 {
|
||||
@@ -1021,17 +1090,30 @@ 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), c.data_type);
|
||||
if let Some(v) = &c.default {
|
||||
s.push_str(&format!(" default {v}"));
|
||||
let mut s = format!(" {}", quote_ident(d, &c.name));
|
||||
if partition.is_none() {
|
||||
s.push(' ');
|
||||
s.push_str(&c.data_type);
|
||||
}
|
||||
if c.not_null {
|
||||
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))
|
||||
{
|
||||
s.push_str(" not null");
|
||||
}
|
||||
s
|
||||
@@ -1039,7 +1121,35 @@ 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 mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
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");
|
||||
// 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)));
|
||||
@@ -1416,15 +1526,31 @@ 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, default: None, comment: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
@@ -1435,21 +1561,94 @@ 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, default: None, comment: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
value: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
@@ -1468,6 +1667,7 @@ 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\
|
||||
|
||||
@@ -391,9 +391,12 @@ 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().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
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 text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
@@ -522,6 +525,17 @@ 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> {
|
||||
@@ -843,6 +857,17 @@ 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";
|
||||
|
||||
@@ -1601,15 +1601,21 @@ 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);
|
||||
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() },
|
||||
]
|
||||
);
|
||||
// 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!(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);
|
||||
@@ -1660,11 +1666,17 @@ 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();
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
// 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!(
|
||||
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"
|
||||
|
||||
@@ -90,6 +90,8 @@ 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>>,
|
||||
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
|
||||
pub mcp: mcp::McpService,
|
||||
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
|
||||
@@ -209,6 +211,13 @@ 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
|
||||
}
|
||||
|
||||
/// User home directory used by agent memory discovery.
|
||||
pub fn home_dir(&self) -> Option<PathBuf> {
|
||||
self.home_dir.clone()
|
||||
@@ -237,6 +246,7 @@ impl Host {
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
local_database_tunnels: false,
|
||||
vcs_providers: Vec::new(),
|
||||
mcp_executable: Arc::default(),
|
||||
mcp: Default::default(),
|
||||
diagnostics,
|
||||
|
||||
@@ -213,6 +213,7 @@ 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()?;
|
||||
@@ -490,6 +491,7 @@ 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?;
|
||||
@@ -589,6 +591,7 @@ 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")? {
|
||||
@@ -680,6 +683,7 @@ 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") {
|
||||
|
||||
@@ -429,6 +429,7 @@ 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?;
|
||||
|
||||
@@ -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, IdeError, IdeResult, Severity};
|
||||
use ide_core::{Diagnostic, IdeResult, Severity};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Problems `get_project_problems` lists by default.
|
||||
@@ -51,28 +51,16 @@ Lines and UTF-16 columns are 1-based.",
|
||||
]
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
|
||||
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
|
||||
reported_by_a_window(call).map_err(|mut error| {
|
||||
call.needs_window().map_err(|mut error| {
|
||||
error.message.push_str(" Use check_files for diagnostics.");
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let paths = PathScope::of(&call)?;
|
||||
let windows = call.host.mcp_windows(call.root());
|
||||
let open = call.host.mcp_reports.editors(&windows);
|
||||
@@ -84,7 +72,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
}
|
||||
|
||||
async fn current_file(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let editor = call.host.mcp_reports.focused(call.window());
|
||||
Output::json(match editor {
|
||||
None => json!({}),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub mod service;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
pub(crate) use tool::trusted_attachments;
|
||||
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
|
||||
mod util;
|
||||
|
||||
use crate::Host;
|
||||
@@ -28,6 +28,7 @@ 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;
|
||||
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools
|
||||
}
|
||||
|
||||
// Checked both when listing and calling, so a later trust change takes effect immediately.
|
||||
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
|
||||
// trust change takes effect immediately.
|
||||
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
trusted || tool.read_only
|
||||
}
|
||||
@@ -63,11 +65,36 @@ 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)| tool));
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(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) {
|
||||
@@ -110,6 +137,16 @@ 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> {
|
||||
@@ -150,6 +187,9 @@ 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,
|
||||
@@ -167,19 +207,27 @@ 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)?;
|
||||
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);
|
||||
// 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))?;
|
||||
}
|
||||
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 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 args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
|
||||
let call = tool::Call {
|
||||
host: self.0.clone(),
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Window-bound requests; missing windows, cancellation and timeout all fail closed.
|
||||
//! 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.
|
||||
use super::tool::Call;
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, event::McpUiRequest};
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tokio::sync::oneshot;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, oneshot};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Requests(Mutex<State>);
|
||||
@@ -13,10 +17,24 @@ struct State {
|
||||
pending: HashMap<u32, Pending>,
|
||||
}
|
||||
struct Pending {
|
||||
window: String,
|
||||
/// 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>,
|
||||
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 {
|
||||
@@ -25,10 +43,18 @@ 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.ready.remove(window);
|
||||
state.pending.retain(|_, p| p.window != window);
|
||||
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);
|
||||
}
|
||||
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
|
||||
self.answer_with(window, id, allow, error, None)
|
||||
@@ -43,10 +69,10 @@ impl Requests {
|
||||
value: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let mut state = self.0.lock();
|
||||
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
|
||||
if !state.pending.get(&id).is_some_and(|p| p.shown_in == window) {
|
||||
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
|
||||
}
|
||||
let pending = state.pending.remove(&id).unwrap();
|
||||
let pending = state.pending.remove(&id).expect("the request was just found");
|
||||
let _ = pending.value.send(value);
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
@@ -64,30 +90,96 @@ 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, rx) = oneshot::channel();
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
let (value_tx, value_rx) = oneshot::channel();
|
||||
{
|
||||
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 });
|
||||
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,
|
||||
}
|
||||
struct Close<'a>(&'a Requests, &'a Call, u32);
|
||||
impl Drop for Close<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.0.lock().pending.remove(&self.2);
|
||||
self.1.project.sink.emit(IdeEvent::McpRequestClosed { id: self.2 });
|
||||
self.requests.0.lock().pending.remove(&self.id);
|
||||
self.call.host.window_sink(&self.shown_in).emit(IdeEvent::McpRequestClosed { id: self.id });
|
||||
}
|
||||
}
|
||||
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()),
|
||||
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() });
|
||||
}
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
|
||||
@@ -96,3 +188,109 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ 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() {
|
||||
|
||||
@@ -5,6 +5,14 @@ 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,
|
||||
@@ -88,12 +96,24 @@ impl Call {
|
||||
client: self.client.clone(),
|
||||
tool: self.tool.clone(),
|
||||
subject: subject.into(),
|
||||
project: self.root().to_string_lossy().into_owned(),
|
||||
project: ide_core::ipc_path::to_ipc(self.root()),
|
||||
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()
|
||||
}
|
||||
@@ -242,9 +262,7 @@ impl Tool {
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
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": [] }),
|
||||
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
}
|
||||
|
||||
@@ -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), `headCommit` and a merge, \
|
||||
rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
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).",
|
||||
|call| async move {
|
||||
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
|
||||
let list: Vec<Value> = roots
|
||||
@@ -117,6 +117,9 @@ rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
if let Some(op) = r.operation {
|
||||
v["operationInProgress"] = op.into();
|
||||
}
|
||||
if r.unavailable {
|
||||
v["unavailable"] = true.into();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -256,10 +259,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>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
@@ -271,12 +274,25 @@ 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(repo) => repo,
|
||||
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),
|
||||
None => match find_git_root(call.root(), &path) {
|
||||
Some(root) => {
|
||||
// JetBrains reads the branch of any repository it reports.
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
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::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
#[command(trust = trusted)]
|
||||
@@ -140,6 +142,17 @@ 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());
|
||||
@@ -152,11 +165,13 @@ 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 = ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
let path = native
|
||||
.or_else(|| 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())
|
||||
};
|
||||
@@ -188,6 +203,19 @@ 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.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -246,7 +246,17 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
#[command(trust = always)]
|
||||
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),
|
||||
Ok(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)
|
||||
}
|
||||
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +246,7 @@ 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) {
|
||||
@@ -563,6 +564,9 @@ 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() {
|
||||
@@ -681,6 +685,15 @@ 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,
|
||||
@@ -1275,6 +1288,34 @@ 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 = root.join("src/main/resources/lib/offline.jar");
|
||||
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".
|
||||
|
||||
@@ -929,9 +929,14 @@ 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).await
|
||||
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())))
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
@@ -2492,6 +2497,18 @@ 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::*;
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
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> {
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
paths
|
||||
@@ -120,6 +135,38 @@ 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]
|
||||
|
||||
@@ -552,19 +552,19 @@ async fn start_inner(
|
||||
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
|
||||
.flatten();
|
||||
if config.kind == "xcode" {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
ide_run::xcode::prepare(&dir, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
ide_run::xcode_clean::prepare(&dir, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -7,19 +7,7 @@ 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 || {
|
||||
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
|
||||
host.blocking(move || merged_status(&project, None)).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -42,19 +30,67 @@ 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 || {
|
||||
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"));
|
||||
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.
|
||||
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()?,
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
};
|
||||
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())));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("status of {}: {e}", backend.root().display());
|
||||
failure = Some(e);
|
||||
}
|
||||
}
|
||||
repos.status_paths(&paths)
|
||||
})
|
||||
.await
|
||||
}
|
||||
match failure {
|
||||
Some(e) if !answered => Err(e),
|
||||
_ => Ok(status),
|
||||
}
|
||||
}
|
||||
|
||||
pub mod commands;
|
||||
|
||||
@@ -94,13 +94,14 @@ async fn revision_text(
|
||||
project: &Option<std::sync::Arc<Project>>,
|
||||
external: &Option<std::sync::Arc<ide_vcs::Repo>>,
|
||||
path: &Path,
|
||||
f: impl FnOnce(&ide_vcs::Repo) -> IdeResult<T>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
match project {
|
||||
Some(project) => project.with_log_repo_of(path, f),
|
||||
Some(project) => project.with_log_backend_of(path, f),
|
||||
None => f(external
|
||||
.as_ref()
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?),
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
|
||||
.as_ref()),
|
||||
}
|
||||
}
|
||||
let (text_encoding, charset) = match &encoding {
|
||||
@@ -148,20 +149,46 @@ 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(Serialize, Deserialize, Type)]
|
||||
#[derive(Default, 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.
|
||||
@@ -190,6 +217,10 @@ 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)]
|
||||
@@ -422,14 +453,32 @@ fn per_repo(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `per_repo` through the backend-agnostic Changes-view surface.
|
||||
/// `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.
|
||||
fn per_backend(
|
||||
project: &Project,
|
||||
paths: &[PathBuf],
|
||||
recorded: Option<&str>,
|
||||
f: impl Fn(&dyn Backend, &[PathBuf]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
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))
|
||||
}
|
||||
|
||||
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
|
||||
@@ -531,29 +580,58 @@ 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(),
|
||||
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| (repo, repo.metadata_dirs().ok())).collect();
|
||||
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 mut branch_roots = std::collections::HashMap::new();
|
||||
for (repo, dirs) in &roots {
|
||||
if let Some([git_dir, common_dir]) = dirs {
|
||||
for (repo, available, dirs) in &roots {
|
||||
if *available && 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(roots
|
||||
let mut roots: Vec<VcsRoot> = roots
|
||||
.iter()
|
||||
.map(|(r, dirs)| {
|
||||
.map(|(r, available, dirs)| {
|
||||
if !available {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
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();
|
||||
@@ -565,14 +643,20 @@ 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: r.is_shallow().unwrap_or(false),
|
||||
shallow,
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
@@ -580,11 +664,21 @@ 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: trusted.then(|| r.has_remotes().ok()).flatten(),
|
||||
has_remotes,
|
||||
resolved_conflicts,
|
||||
unavailable: false,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
.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)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -592,7 +686,13 @@ 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 || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
|
||||
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
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -863,6 +963,9 @@ 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)
|
||||
@@ -900,13 +1003,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_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
|
||||
blocking(move || project.with_git_log_or_default(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_log_repo_at(repo.as_deref(), |r| r.log_users())).await
|
||||
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_users())).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -936,7 +1039,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_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
|
||||
blocking(move || project.with_log_backend_at(repo.as_deref(), |b| b.log_details(&revision))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -950,6 +1053,9 @@ 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)
|
||||
@@ -1093,13 +1199,23 @@ 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 || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
|
||||
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
|
||||
}
|
||||
|
||||
#[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 || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
|
||||
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
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1303,6 +1419,15 @@ 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() {
|
||||
if create {
|
||||
return Err(ide_core::IdeError::unavailable("creating a branch is not supported here"));
|
||||
}
|
||||
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
|
||||
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
|
||||
});
|
||||
}
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| {
|
||||
r.checkout_with(&branch, create, &options)
|
||||
})
|
||||
@@ -1802,6 +1927,15 @@ 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 } => {
|
||||
@@ -3236,6 +3370,103 @@ 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)?;
|
||||
@@ -3319,6 +3550,11 @@ 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,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! 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: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
|
||||
//! the config, then restarts sourcekit-lsp.
|
||||
//! 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.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -24,6 +25,39 @@ fn tool_args(tool: &str, container: &str) -> Vec<String> {
|
||||
vec!["config".into(), flag.into(), container.into()]
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// An Xcode project without a BSP config, at the project root.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -69,8 +103,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`, then restarts the project's
|
||||
/// sourcekit-lsp so it reads it.
|
||||
/// 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.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
|
||||
if !TOOLS.contains(&tool.as_str()) {
|
||||
@@ -93,6 +127,10 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
|
||||
.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);
|
||||
@@ -136,6 +174,81 @@ mod tests {
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["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)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_only_bundle_names_in_the_root() {
|
||||
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
|
||||
|
||||
@@ -118,21 +118,50 @@ 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 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());
|
||||
let arguments = arguments_for(&declared.input_schema, args)?;
|
||||
let tool = tool.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();
|
||||
|
||||
@@ -3008,11 +3008,16 @@ impl PluginHost {
|
||||
{
|
||||
let mut plugins = self.plugins.write();
|
||||
if let Some(existing) = plugins.get(&id) {
|
||||
tracing::warn!(
|
||||
"plugin {id:?} at {} ignored: already loaded from {}",
|
||||
dir.display(),
|
||||
existing.dir().display()
|
||||
);
|
||||
// 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()
|
||||
);
|
||||
}
|
||||
return (id, None);
|
||||
}
|
||||
plugins.insert(id.clone(), plugin.clone());
|
||||
|
||||
@@ -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, Repo, Repos};
|
||||
use ide_vcs::{Backend, BackendProvider, FileStatus, Repo, Repos};
|
||||
use ide_vfs::Watcher;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder};
|
||||
@@ -41,6 +41,14 @@ 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<()>>,
|
||||
/// 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.
|
||||
@@ -386,8 +394,12 @@ impl Host {
|
||||
}));
|
||||
}
|
||||
{
|
||||
let documents = documents.clone();
|
||||
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
|
||||
// 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 syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
@@ -425,6 +437,9 @@ 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();
|
||||
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = self.vcs_providers.clone().into();
|
||||
let backend_scan: Arc<Mutex<()>> = Arc::default();
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
}
|
||||
@@ -463,6 +478,9 @@ 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) =
|
||||
(backends.clone(), vcs_providers.clone(), backend_scan.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,6 +618,41 @@ 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 appeared = folders
|
||||
.iter()
|
||||
.any(|d| !known.iter().any(|r| r == d) && markers.iter().any(|m| d.join(m).exists()));
|
||||
let gone = batch.removed.iter().any(|p| known.iter().any(|r| r.starts_with(p)));
|
||||
if appeared || gone {
|
||||
let (backends, providers, lock, trust) =
|
||||
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), trusted.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);
|
||||
};
|
||||
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
|
||||
@@ -681,9 +734,14 @@ 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)
|
||||
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);
|
||||
})?;
|
||||
}
|
||||
mark("git");
|
||||
@@ -724,6 +782,9 @@ impl Host {
|
||||
index,
|
||||
lsp,
|
||||
repos,
|
||||
backends,
|
||||
vcs_providers,
|
||||
backend_scan,
|
||||
external_log_repos: RwLock::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
@@ -1025,6 +1086,9 @@ impl Host {
|
||||
index,
|
||||
lsp,
|
||||
repos: Arc::default(),
|
||||
backends: Arc::default(),
|
||||
vcs_providers: Arc::new([]),
|
||||
backend_scan: Arc::default(),
|
||||
external_log_repos: RwLock::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
@@ -1063,17 +1127,16 @@ 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("Project is in Restricted Mode. Trust the project to enable execution."))
|
||||
}
|
||||
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
@@ -1231,6 +1294,94 @@ fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::S
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// 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() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// The repository roots detection finds, before Directory Mappings exclude or add any.
|
||||
pub fn detected_repository_roots(&self) -> IdeResult<Vec<PathBuf>> {
|
||||
@@ -1248,6 +1399,53 @@ 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) {
|
||||
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());
|
||||
}
|
||||
|
||||
/// 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();
|
||||
}
|
||||
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).
|
||||
@@ -1349,8 +1547,12 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// `with_repo_of` through the backend-agnostic Changes-view surface.
|
||||
/// Runs `f` with the backend `path` belongs to: its non-Git working copy, else its Git
|
||||
/// repository.
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -1366,8 +1568,12 @@ impl Project {
|
||||
f(repo)
|
||||
}
|
||||
|
||||
/// `with_repo_at` through the backend-agnostic Changes-view surface.
|
||||
/// `with_repo_at` through the backend-agnostic Changes-view surface; `at` may name a
|
||||
/// non-Git working copy ([`Self::backend_at`]).
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -1377,22 +1583,43 @@ 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.
|
||||
/// `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.
|
||||
pub fn with_backend_recorded<T>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend))
|
||||
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))
|
||||
}
|
||||
|
||||
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
|
||||
@@ -1417,16 +1644,27 @@ impl Project {
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
|
||||
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) };
|
||||
self.history_label(&format!("Before {name}"));
|
||||
if let Ok(changed) = self.with_backend_at(at, |r| r.status()) {
|
||||
if let Ok(changed) = changed() {
|
||||
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(|| self.with_repo_at(at, f));
|
||||
let result = self.with_disk_sync(run);
|
||||
self.history_label(&format!("After {name}"));
|
||||
result
|
||||
}
|
||||
@@ -1658,7 +1896,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_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
|
||||
let bytes = self.with_log_backend_of(path, |b| b.file_bytes_at(path, rev))?.unwrap_or_default();
|
||||
Ok(self.documents.detect_encoding(path, &bytes))
|
||||
}
|
||||
|
||||
|
||||
@@ -500,6 +500,7 @@ 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(),
|
||||
|
||||
@@ -260,6 +260,10 @@ 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();
|
||||
@@ -314,6 +318,7 @@ 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);
|
||||
|
||||
@@ -87,3 +87,46 @@ 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"
|
||||
);
|
||||
}
|
||||
@@ -742,38 +742,43 @@ async fn typescript_import_style() {
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
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 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""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
set("importModuleSpecifier", r#""non-relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
set("importModuleSpecifierEnding", r#""index""#).await;
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
set("importModuleSpecifierEnding", r#""minimal""#).await;
|
||||
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"]"#);
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#).await;
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#).await;
|
||||
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", "[]");
|
||||
set("autoImportFileExcludePatterns", "[]").await;
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
set("autoImportSpecifierExcludeRegexes", "[]").await;
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
mod common;
|
||||
|
||||
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
|
||||
use ide_core::{
|
||||
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
|
||||
};
|
||||
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_mcp::ToolRegistry;
|
||||
@@ -12,7 +14,8 @@ struct Harness {
|
||||
host: Arc<Host>,
|
||||
root: PathBuf,
|
||||
tmp: tempfile::TempDir,
|
||||
events: Arc<std::sync::Mutex<Vec<IdeEvent>>>,
|
||||
/// Every event, with the window whose sink it was emitted on.
|
||||
events: Arc<std::sync::Mutex<Vec<(String, IdeEvent)>>>,
|
||||
}
|
||||
impl Harness {
|
||||
fn new() -> Self {
|
||||
@@ -27,9 +30,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 |_| {
|
||||
let events = sink.clone();
|
||||
Arc::new(move |e| events.lock().unwrap().push(e))
|
||||
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)))
|
||||
}),
|
||||
local_data_dir: tmp.path().join("local"),
|
||||
..common::host_config(tmp.path())
|
||||
@@ -55,7 +58,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,
|
||||
}) {
|
||||
@@ -67,6 +70,54 @@ 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 || {
|
||||
@@ -252,6 +303,10 @@ 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!(
|
||||
@@ -391,7 +446,11 @@ 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
|
||||
@@ -399,7 +458,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");
|
||||
@@ -438,14 +497,16 @@ 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 = h.request().await;
|
||||
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:?}");
|
||||
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 {
|
||||
@@ -774,7 +835,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) =>
|
||||
{
|
||||
@@ -847,11 +908,9 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert_eq!(tabs[0].name, "MCP test");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
/// A shell configuration named `MCP test` that prints `windowless` and exits with 3.
|
||||
fn windowless_config() -> ide_run::RunConfig {
|
||||
ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
@@ -864,8 +923,14 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
@@ -873,7 +938,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")]
|
||||
@@ -1020,7 +1085,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")]
|
||||
@@ -1052,7 +1117,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 },
|
||||
@@ -1546,22 +1611,91 @@ 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_is_refused() {
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
|
||||
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"}}));
|
||||
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}");
|
||||
}
|
||||
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}");
|
||||
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();
|
||||
@@ -1720,31 +1854,215 @@ async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_that_ask_the_user_fail_closed_in_a_background_project() {
|
||||
async fn tools_that_need_a_window_refuse_in_a_background_project_before_asking() {
|
||||
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();
|
||||
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}");
|
||||
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.")
|
||||
);
|
||||
}
|
||||
}
|
||||
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();
|
||||
@@ -1850,7 +2168,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!(
|
||||
|
||||
@@ -70,6 +70,20 @@ 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()
|
||||
}
|
||||
@@ -189,21 +203,66 @@ 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.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 inventory = f.serve_inventory();
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
//! 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).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;
|
||||
}
|
||||
@@ -572,3 +572,60 @@ 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");
|
||||
}
|
||||
@@ -530,6 +530,77 @@ 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();
|
||||
|
||||
@@ -390,6 +390,10 @@ 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) {
|
||||
|
||||
@@ -601,8 +601,11 @@ 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();
|
||||
self.persist(&[], &stale, false);
|
||||
if !stale.is_empty() {
|
||||
self.persist(&[], &stale, false);
|
||||
}
|
||||
|
||||
let total = todo.len();
|
||||
if task.is_none() && total >= QUIET_SCAN_FILES {
|
||||
@@ -674,25 +677,31 @@ impl Shared {
|
||||
return None;
|
||||
}
|
||||
let durable_started = Instant::now();
|
||||
self.persist(&[], &[], true);
|
||||
if index_changed {
|
||||
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();
|
||||
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}");
|
||||
// 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());
|
||||
}
|
||||
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 {
|
||||
@@ -1443,6 +1452,40 @@ 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();
|
||||
|
||||
@@ -727,6 +727,21 @@ 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();
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! Java project queries for launches when jdtls does not serve the module: another Java
|
||||
//! language server (java-analyzer) answers the classpath and JDK, if it supports it.
|
||||
//! Java project queries and class-file navigation for servers other than jdtls.
|
||||
|
||||
use crate::LspManager;
|
||||
use crate::jdtls::{JavaClasspath, SERVER as JDTLS};
|
||||
use crate::{ErrorKind, LspManager, Target, uri};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use serde_json::{Value, json};
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `{ uri, scope: "runtime" | "test" }` → `{ projectRoot, classPaths, modulePaths, jdkHome }`.
|
||||
const CLASSPATH: &str = "java-analyzer/projectClasspath";
|
||||
const CLASS_FILE: &str = "java-analyzer/classFile";
|
||||
/// Waiting for the server to start and import the project.
|
||||
const READY_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
@@ -37,6 +38,54 @@ impl LspManager {
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve a compiled class to the document that the project's Java server opens.
|
||||
/// The internal name is only read for disk classes handled by a server other than jdtls.
|
||||
pub async fn java_class_file(
|
||||
&self,
|
||||
path: &Path,
|
||||
archive: Option<(PathBuf, String)>,
|
||||
internal_name: impl Future<Output = IdeResult<String>>,
|
||||
) -> IdeResult<String> {
|
||||
if self.java_served_by_jdtls(&self.project_root) {
|
||||
let result = self.jdtls_class_file(path, archive.clone()).await;
|
||||
// Starting jdtls can expose a configured fallback.
|
||||
if result.is_ok() || self.java_served_by_jdtls(&self.project_root) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
// Use the workspace's server for archives, which can live outside the project.
|
||||
let route = if archive.is_some() { &self.project_root } else { path };
|
||||
let servers: Vec<_> = self
|
||||
.servers_for(&LanguageId::new("java"), route)
|
||||
.into_iter()
|
||||
.filter(|s| s.name != JDTLS && !s.gave_up())
|
||||
.collect();
|
||||
if servers.is_empty() {
|
||||
return self.jdtls_class_file(path, archive).await;
|
||||
}
|
||||
for server in &servers {
|
||||
self.ensure_started(server);
|
||||
let Some(run) = server.wait_ready(READY_TIMEOUT).await else { continue };
|
||||
if run.caps.read().raw["experimental"][CLASS_FILE] != true {
|
||||
continue;
|
||||
}
|
||||
let params = match archive {
|
||||
Some((jar, entry)) => json!({ "archive": uri::path_to_uri_string(&jar), "entry": entry }),
|
||||
None => disk_class_params(path, &internal_name.await?),
|
||||
};
|
||||
let target = Target { server: server.clone(), run };
|
||||
let result: Option<ClassFileDocument> =
|
||||
self.call(&target, CLASS_FILE, params, None, REQUEST_TIMEOUT).await?;
|
||||
let doc = result
|
||||
.ok_or_else(|| IdeError::not_found(format!("{} could not resolve {}", server.name, path.display())))?;
|
||||
// Go-to-definition also opens these materialized file URIs as ordinary editor paths.
|
||||
return uri::uri_to_path(&doc.uri)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.ok_or_else(|| IdeError::new(ErrorKind::Protocol, format!("{CLASS_FILE}: expected a file URI")));
|
||||
}
|
||||
Err(crate::unsupported(&servers, "Java class-file resolution"))
|
||||
}
|
||||
|
||||
/// Runtime (`test == false`) or test classpath of the module at `path` from the first
|
||||
/// Java server other than jdtls. `None` when there is none or it doesn't support the query.
|
||||
pub async fn java_server_classpath(
|
||||
@@ -77,6 +126,24 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ClassFileDocument {
|
||||
uri: String,
|
||||
}
|
||||
|
||||
fn disk_class_params(path: &Path, name: &str) -> Value {
|
||||
let entry = format!("{name}.class");
|
||||
// Supplying the output directory disambiguates classes with the same name in different modules.
|
||||
if path.ends_with(&entry)
|
||||
&& let Some(output) = path.ancestors().nth(Path::new(&entry).components().count())
|
||||
&& !output.as_os_str().is_empty()
|
||||
{
|
||||
json!({ "archive": uri::path_to_uri_string(output), "entry": entry })
|
||||
} else {
|
||||
json!({ "binaryName": name.replace('/', ".") })
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` for a `null` answer (the server has no module for the path).
|
||||
fn parse(v: &Value) -> Option<ServerClasspath> {
|
||||
if v.is_null() {
|
||||
|
||||
@@ -503,12 +503,30 @@ impl LaunchScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// m2e can run package-phase mojos such as `dependency:copy-dependencies` during
|
||||
/// `java/buildWorkspace`. In an incremental IDE build the reactor jars are not
|
||||
/// packaged, so the plugin fails with MDEP-187 (copy) or MDEP-98 (unpack). That is
|
||||
/// not a Java compile error, and a main-class launch does not need the copied jars.
|
||||
/// Debug uses this workspace build (so java-debug can HotSwap the classes jdtls
|
||||
/// compiled); Run uses the IDE's Java build and never hits the mojo. Ignoring the
|
||||
/// marker keeps the two consistent when the Java sources compiled.
|
||||
fn is_reactor_packaging_mojo_error(message: &str) -> bool {
|
||||
let lower = message.to_ascii_lowercase();
|
||||
lower.contains("has not been packaged yet") && lower.contains("executed after packaging")
|
||||
}
|
||||
|
||||
/// JDTLS reports all imported projects; report errors for the launch and its dependencies.
|
||||
fn launch_compile_errors(
|
||||
scope: &LaunchScope,
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
) -> (Vec<JavaCompileError>, u32) {
|
||||
compile_errors(diagnostics.into_iter().filter(|(path, _)| scope.includes(path)).collect(), MAX_LAUNCH_ERRORS)
|
||||
compile_errors(
|
||||
diagnostics
|
||||
.into_iter()
|
||||
.filter(|(path, d)| scope.includes(path) && !is_reactor_packaging_mojo_error(&d.message))
|
||||
.collect(),
|
||||
MAX_LAUNCH_ERRORS,
|
||||
)
|
||||
}
|
||||
|
||||
/// `java.project.getClasspaths` result.
|
||||
@@ -1239,7 +1257,7 @@ impl LspManager {
|
||||
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
|
||||
/// A class in an output directory opens as itself even when its project source exists:
|
||||
/// the user asked for the compiled class, not the file it was built from.
|
||||
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
|
||||
pub(crate) async fn jdtls_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
|
||||
if let Some((jar, entry)) = archive {
|
||||
return self.archive_class(jar, entry, false).await;
|
||||
}
|
||||
@@ -1759,6 +1777,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_launch_ignores_mdep_reactor_packaging_errors() {
|
||||
let cp = JavaClasspath {
|
||||
class_paths: vec!["/p/app/target/classes".into(), "/p/library/target/classes".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let scope = LaunchScope::new(Path::new("/p/app"), false, Some(&cp));
|
||||
let diagnostic = |message: &str| lsp_types::Diagnostic {
|
||||
severity: Some(lsp_types::DiagnosticSeverity::ERROR),
|
||||
message: message.into(),
|
||||
range: lsp_types::Range::new(lsp_types::Position::new(299, 21), lsp_types::Position::new(299, 31)),
|
||||
..Default::default()
|
||||
};
|
||||
// m2e's BuildProblemInfo: the CoreException message, then the execution key,
|
||||
// then the stack whose cause is the plugin's MDEP-187 / MDEP-98 text.
|
||||
let copy = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies} (org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies:copy-dependencies:package)\n\norg.eclipse.core.runtime.CoreException: Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies}\n\t at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:57)\nCaused by: org.apache.maven.plugin.MojoExecutionException:\nArtifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.";
|
||||
let unpack = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:unpack-dependencies {execution: unpack-dependencies}\nCaused by: org.apache.maven.plugin.MojoExecutionException: Artifact has not been packaged yet. When used on reactor artifact, unpack should be executed after packaging: see MDEP-98.";
|
||||
let other_mojo = "Failed to execute mojo org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile {execution: default-compile}";
|
||||
let (errors, count) = launch_compile_errors(
|
||||
&scope,
|
||||
vec![
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(copy)),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(unpack)),
|
||||
(PathBuf::from("/p/app/src/main/java/App.java"), diagnostic("App cannot be resolved to a type")),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(other_mojo)),
|
||||
],
|
||||
);
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(&*errors[0].path, Path::new("/p/app/pom.xml"));
|
||||
assert_eq!(errors[0].message, other_mojo);
|
||||
assert_eq!(&*errors[1].path, Path::new("/p/app/src/main/java/App.java"));
|
||||
assert_eq!(errors[1].message, "App cannot be resolved to a type");
|
||||
let (_, only_packaging) =
|
||||
launch_compile_errors(&scope, vec![(PathBuf::from("/p/app/pom.xml"), diagnostic(copy))]);
|
||||
assert_eq!(only_packaging, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_classpaths_retain_all_errors() {
|
||||
for cp in [
|
||||
|
||||
@@ -3405,10 +3405,17 @@ impl LspManager {
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// jdtls rebuilds a source file that changed on disk but keeps the diagnostics of the
|
||||
// open files it checked before: a reference to a class another tool adds after
|
||||
// rewriting the open file stays "cannot be resolved" until the file is reopened.
|
||||
// Sending the open files again makes it check them against the new sources.
|
||||
let recheck_open = jdtls && changes.iter().any(|(p, _)| p.extension().is_some_and(|e| e == "java"));
|
||||
let changes: Vec<Value> =
|
||||
changes.iter().map(|(p, c)| json!({ "uri": uri::path_to_uri(p), "type": *c as u8 })).collect();
|
||||
if let Err(e) = run.peer.notify("workspace/didChangeWatchedFiles", json!({ "changes": changes })) {
|
||||
tracing::debug!("{}: didChangeWatchedFiles: {e}", s.name);
|
||||
} else if recheck_open {
|
||||
self.resync_documents(&s, run.generation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,6 +482,31 @@ async fn dart_file_watching_requires_an_explicit_registration() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_sources_changed_on_disk_send_the_open_files_to_jdtls_again() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (_, main) = h.open("Main.java", "class Main { String s = Helper.greet(); }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let resent = || {
|
||||
s.notified("textDocument/didChange")
|
||||
.iter()
|
||||
.filter(|v| v["textDocument"]["uri"] == uri_of(&main) && v["contentChanges"][0]["text"].is_string())
|
||||
.count()
|
||||
};
|
||||
// Another tool adds the class the open file refers to.
|
||||
let helper = h.root.join("Helper.java");
|
||||
h.mgr.watched_files_changed(std::slice::from_ref(&helper), &[], &[], &[]);
|
||||
eventually(|| s.notified("workspace/didChangeWatchedFiles").len() == 1).await;
|
||||
eventually(|| resent() == 1).await;
|
||||
// Files that are not Java sources leave the open files alone.
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("notes.txt")], &[], &[]);
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("pom.xml")], &[], &[]);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(resent(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tests
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -5745,7 +5770,12 @@ async fn jar_library_sources_reload_with_another_encoding() {
|
||||
async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["workspaceSymbolProvider"] = json!(true);
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let h = harness_for(
|
||||
"java",
|
||||
"java",
|
||||
&[("jdtls", caps), ("java-analyzer", json!({"experimental":{"java-analyzer/classFile":true}}))],
|
||||
&[],
|
||||
);
|
||||
h.open("App.java", "class App {}\n");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
@@ -5754,12 +5784,17 @@ async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
{"name":"Outer", "kind":5, "location":{"uri":jdt,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}}
|
||||
]));
|
||||
let archive = Some((PathBuf::from("/m2/lib.jar"), "p/Outer$1.class".into()));
|
||||
assert_eq!(h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive).await.unwrap(), jdt);
|
||||
let unused_name = || async { panic!("jdtls does not need the internal class name") };
|
||||
assert_eq!(
|
||||
h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive, unused_name()).await.unwrap(),
|
||||
jdt
|
||||
);
|
||||
assert!(
|
||||
h.mgr
|
||||
.java_class_file(
|
||||
Path::new("/other/lib.jar!/p/Outer.class"),
|
||||
Some(("/other/lib.jar".into(), "p/Outer.class".into()))
|
||||
Some(("/other/lib.jar".into(), "p/Outer.class".into())),
|
||||
unused_name(),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
@@ -5772,16 +5807,71 @@ async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
|
||||
for class in ["Outer", "Outer$Nested", "Outer$1"] {
|
||||
let path = h.root.join(format!("target/classes/p/{class}.class"));
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri_of(&path));
|
||||
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri_of(&path));
|
||||
}
|
||||
let path = h.root.join("build/classes/java/main/p/Missing.class");
|
||||
let uri = uri_of(&path);
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri);
|
||||
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri);
|
||||
let vd = h.mgr.virtual_document(&uri).await.unwrap();
|
||||
assert!(vd.decompiled);
|
||||
assert_eq!(vd.language_id.as_str(), "java");
|
||||
assert_eq!(vd.title, "Missing.class");
|
||||
assert!(s.requested("java/classFileContents").iter().any(|p| p["uri"] == uri));
|
||||
assert!(h.launcher.state("java-analyzer").requested("java-analyzer/classFile").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn class_file_opening_starts_java_analyzer_for_archive_classes() {
|
||||
const METHOD: &str = "java-analyzer/classFile";
|
||||
for with_jdtls in [false, true] {
|
||||
let mut servers = vec![("java-analyzer", json!({"experimental":{METHOD:true}}))];
|
||||
if with_jdtls {
|
||||
servers.insert(0, ("jdtls", incremental_caps()));
|
||||
}
|
||||
let h = harness_for("java", "java", &servers, &["java-analyzer"]);
|
||||
h.launcher.state("jdtls").missing.store(true, Ordering::SeqCst);
|
||||
let server = h.launcher.state("java-analyzer");
|
||||
let source = h.root.join("cache with spaces/p/Outer.java");
|
||||
server.respond(METHOD, json!({"uri":uri_of(&source)}));
|
||||
let archive = h.root.join("external Maven cache/lib.jar");
|
||||
let entry = "META-INF/versions/17/p/Outer$Inner.class";
|
||||
let path = PathBuf::from(format!("{}!/{entry}", archive.display()));
|
||||
let opened = h
|
||||
.mgr
|
||||
.java_class_file(&path, Some((archive.clone(), entry.into())), async {
|
||||
panic!("archive entries do not need the internal class name")
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(Path::new(&opened), source);
|
||||
assert_eq!(server.requested(METHOD), [json!({"archive":uri_of(&archive), "entry":entry})]);
|
||||
assert!(server.requested("workspace/textDocumentContent").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn class_file_opening_routes_disk_classes_by_internal_name() {
|
||||
const METHOD: &str = "java-analyzer/classFile";
|
||||
let h = harness_for("java", "java", &[("java-analyzer", json!({"experimental":{METHOD:true}}))], &[]);
|
||||
let server = h.launcher.state("java-analyzer");
|
||||
let source = h.root.join("src/main/java/p/Outer.java");
|
||||
server.respond(METHOD, json!({"uri":uri_of(&source)}));
|
||||
let output = h.root.join("target/classes");
|
||||
let class = output.join("p/Outer$Inner.class");
|
||||
let moved = h.root.join("moved.class");
|
||||
let internal_name = || async { Ok("p/Outer$Inner".into()) };
|
||||
for path in [&class, &moved] {
|
||||
assert_eq!(Path::new(&h.mgr.java_class_file(path, None, internal_name()).await.unwrap()), source);
|
||||
}
|
||||
assert_eq!(
|
||||
server.requested(METHOD),
|
||||
[json!({"archive":uri_of(&output), "entry":"p/Outer$Inner.class"}), json!({"binaryName":"p.Outer$Inner"})]
|
||||
);
|
||||
server.respond(METHOD, Value::Null);
|
||||
assert_eq!(
|
||||
h.mgr.java_class_file(&class, None, internal_name()).await.unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::NotFound
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
//! `Origin` or `Host` are refused (DNS rebinding).
|
||||
//! - **Projects:** the `X-OpenIDEA-Project` header or the `?project=` query
|
||||
//! names a folder; the server picks the open project containing it, or the
|
||||
//! project the IDE serves it from without a window.
|
||||
//! project the IDE serves it from without a window. A connection whose
|
||||
//! folder no project serves lists the tools a trusted project gets, and each
|
||||
//! call names its project with `projectPath`. `openidea/servesFolder`
|
||||
//! answers which project serves the connection's folder (`{"root": null}`
|
||||
//! for none).
|
||||
//! - **Discovery:** `<app-data>/mcp/server.json` (`address`, `port`, `token`,
|
||||
//! `pid`, `version`; readable only by the user) while the server runs.
|
||||
//! - **Stdio:** `<app exe> --mcp-stdio [--project <path>]` reads the discovery
|
||||
@@ -76,6 +80,12 @@ pub trait ToolRegistry: Send + Sync + 'static {
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
/// [`Self::resolve`] gave). `Err` says why there are none (an unsupported project).
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String>;
|
||||
/// The tools listed on a connection whose project doesn't resolve (a folder no project
|
||||
/// serves, or no folder and not exactly one window): those a trusted project gets. Each
|
||||
/// call still resolves its project and refuses by that project's trust.
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
Vec::new()
|
||||
}
|
||||
fn call_with_client(
|
||||
&self,
|
||||
project: &Path,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`
|
||||
//! and notifications, for one POST body (a message or a batch). Blocking: the
|
||||
//! server runs it on a blocking thread.
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`,
|
||||
//! our own `openidea/servesFolder` and notifications, for one POST body (a
|
||||
//! message or a batch). Blocking: the server runs it on a blocking thread.
|
||||
|
||||
use crate::{CancellationToken, Tool, ToolCallError, ToolRegistry};
|
||||
use serde_json::{Value, json};
|
||||
@@ -26,16 +26,22 @@ impl Drop for InFlight<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a cancellation that arrived before its call is kept.
|
||||
const EARLY_CANCELLATION: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// The protocol version answered when the client asks for one this server doesn't know.
|
||||
pub(crate) const LATEST: &str = "2025-06-18";
|
||||
pub(crate) const SUPPORTED: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
pub(crate) const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
/// The requested folder isn't in a project the IDE serves (or has no tools there).
|
||||
pub(crate) const NOT_OPEN: i64 = -32001;
|
||||
/// Which project serves the connection's folder: `{"root": "<path>"}`, or `{"root": null}`
|
||||
/// for none. The stdio bridge asks it to pick the IDE process for its folder.
|
||||
pub(crate) const SERVES_FOLDER: &str = "openidea/servesFolder";
|
||||
|
||||
pub(crate) struct RpcError {
|
||||
code: i64,
|
||||
@@ -105,7 +111,12 @@ impl Session<'_> {
|
||||
let mut state = self.requests.0.lock().unwrap();
|
||||
if let Some(cancel) = state.running.get(&key) {
|
||||
cancel.cancel();
|
||||
} else if state.early.len() < 1024 {
|
||||
return None;
|
||||
}
|
||||
// The stdio bridge sends a cancellation to every server, so one that runs few
|
||||
// calls drops the stale ones here as well.
|
||||
state.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if state.early.len() < 1024 {
|
||||
state.early.insert(key, std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
@@ -116,7 +127,7 @@ impl Session<'_> {
|
||||
let cancel = self.cancel.child_token();
|
||||
{
|
||||
let mut requests = self.requests.0.lock().unwrap();
|
||||
requests.early.retain(|_, at| at.elapsed() < std::time::Duration::from_secs(60));
|
||||
requests.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if requests.running.contains_key(&key) {
|
||||
return Some(error_response(id, INVALID_REQUEST, "request id already in flight"));
|
||||
}
|
||||
@@ -139,11 +150,18 @@ impl Session<'_> {
|
||||
"initialize" => Ok(self.initialize(¶ms)),
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => {
|
||||
let project = self.project()?;
|
||||
let tools = self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?;
|
||||
let tools = match self.project() {
|
||||
Ok(project) => self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?,
|
||||
Err(_) => self.registry.tools_without_project(),
|
||||
};
|
||||
Ok(json!({ "tools": tools.iter().map(tool_json).collect::<Vec<_>>() }))
|
||||
}
|
||||
"tools/call" => self.call(params, cancel),
|
||||
SERVES_FOLDER => {
|
||||
// A root without tools here (a remote window's) is another server's to serve.
|
||||
let root = self.project().ok().filter(|root| self.registry.tools(root).is_ok());
|
||||
Ok(json!({ "root": root.map(|root| root.display().to_string()) }))
|
||||
}
|
||||
_ => Err(RpcError::new(METHOD_NOT_FOUND, format!("no method {method:?}"))),
|
||||
}
|
||||
}
|
||||
@@ -157,9 +175,13 @@ impl Session<'_> {
|
||||
}
|
||||
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(LATEST);
|
||||
let version = if SUPPORTED.contains(&asked) { asked } else { LATEST };
|
||||
let about = match self.project() {
|
||||
Ok(root) => format!("the project OpenIDEA serves at {}", root.display()),
|
||||
Err(_) => "a project open in OpenIDEA or served in the background".to_owned(),
|
||||
let (about, without_project) = match self.project() {
|
||||
Ok(root) => (format!("the project OpenIDEA serves at {}", root.display()), ""),
|
||||
Err(_) => (
|
||||
"a project open in OpenIDEA or served in the background".to_owned(),
|
||||
" This connection has no project of its own: pass `projectPath`, a folder inside a project \
|
||||
OpenIDEA serves, in every call, `get_workspace_roots` included.",
|
||||
),
|
||||
};
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
@@ -174,7 +196,7 @@ impl Session<'_> {
|
||||
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
|
||||
not a list of projects to change; it doesn't change your working directory or \
|
||||
permissions. Pass another root as `projectPath` to reach that project. Call it again \
|
||||
when the user switches projects or attaches one."
|
||||
when the user switches projects or attaches one.{without_project}"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! running IDE's server, found through the discovery file.
|
||||
|
||||
use crate::discovery::Discovery;
|
||||
use crate::protocol::{NOT_OPEN, error_response};
|
||||
use crate::protocol::{METHOD_NOT_FOUND, NOT_OPEN, SERVES_FOLDER, error_response};
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::{Request, StatusCode, header};
|
||||
@@ -17,7 +17,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
#[derive(Default)]
|
||||
struct BridgeState {
|
||||
preferred: Option<SocketAddr>,
|
||||
/// The server that serves the connection's folder, or the first one when none does. A
|
||||
/// server restarted on its port is another one: its entry names another process or token.
|
||||
preferred: Option<Discovery>,
|
||||
/// The servers there were when `preferred` was picked: one started since may serve the folder.
|
||||
picked_among: Vec<Discovery>,
|
||||
init_message: Option<Value>,
|
||||
initialized_on: HashSet<SocketAddr>,
|
||||
}
|
||||
@@ -171,18 +175,28 @@ async fn post(
|
||||
if candidates.is_empty() {
|
||||
return Err(not_running());
|
||||
}
|
||||
if let Some(preferred) = state.lock().unwrap().preferred
|
||||
&& let Some(pos) = candidates.iter().position(|c| SocketAddr::new(c.address, c.port) == preferred)
|
||||
{
|
||||
if message.get("method").and_then(Value::as_str) == Some("notifications/cancelled") {
|
||||
return cancel_everywhere(candidates, project, message, scope, sent).await.ok_or_else(not_running);
|
||||
}
|
||||
let preferred = state.lock().unwrap().preferred.clone();
|
||||
if let Some(pos) = preferred.and_then(|preferred| candidates.iter().position(|c| *c == preferred)) {
|
||||
let chosen = candidates.remove(pos);
|
||||
candidates.insert(0, chosen);
|
||||
}
|
||||
// `initialize` picks the server that serves the connection's folder, and later messages
|
||||
// keep it: a call whose `projectPath` another server serves doesn't move `tools/list`
|
||||
// there. A message after that server stopped, or after another one started, picks again.
|
||||
let initializing = is_initialize(message);
|
||||
let mut fallback: Option<(SocketAddr, Answer)> = None;
|
||||
if !initializing {
|
||||
pick_again(&mut candidates, project, scope, state).await;
|
||||
}
|
||||
let listed = candidates.clone();
|
||||
let mut answered = None;
|
||||
let mut fallback: Option<(Discovery, Answer)> = None;
|
||||
let mut last_error: Option<String> = None;
|
||||
let total = candidates.len();
|
||||
for (idx, info) in candidates.into_iter().enumerate() {
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(&info);
|
||||
if !initializing {
|
||||
let init = {
|
||||
let guard = state.lock().unwrap();
|
||||
@@ -190,7 +204,7 @@ async fn post(
|
||||
};
|
||||
if let Some(mut init_msg) = init {
|
||||
if let Some(obj) = init_msg.as_object_mut() {
|
||||
obj.insert("id".into(), Value::String(format!("__openidea_init_{idx}__")));
|
||||
obj.insert("id".into(), Value::String(own_id("init")));
|
||||
}
|
||||
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
@@ -202,34 +216,120 @@ async fn post(
|
||||
if initializing {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
if total > 1 && !serves_project(&info, project, scope).await {
|
||||
fallback.get_or_insert((at, answer));
|
||||
fallback.get_or_insert((info, answer));
|
||||
continue;
|
||||
}
|
||||
} else if idx + 1 < total && is_not_open_reply(&answer) {
|
||||
fallback = Some((at, answer));
|
||||
fallback = Some((info, answer));
|
||||
continue;
|
||||
}
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
answered = Some((info, answer));
|
||||
break;
|
||||
}
|
||||
Err(err) => last_error = Some(err),
|
||||
}
|
||||
}
|
||||
if let Some((at, answer)) = fallback {
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
let Some((info, answer)) = answered.or(fallback) else {
|
||||
return Err(last_error.unwrap_or_else(not_running));
|
||||
};
|
||||
if initializing {
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(info);
|
||||
state.picked_among = listed;
|
||||
}
|
||||
Err(last_error.unwrap_or_else(not_running))
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// Whether the server of `info` has `project` open: its `tools/list` doesn't answer "not open".
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = serde_json::json!({ "jsonrpc": "2.0", "id": "__openidea_probe__", "method": "tools/list" });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
match post_one(info, project, &probe, scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
fn address(info: &Discovery) -> SocketAddr {
|
||||
SocketAddr::new(info.address, info.port)
|
||||
}
|
||||
|
||||
/// An id of the bridge's own for a request it makes: concurrent messages can make one to the
|
||||
/// same server at once, and a server refuses an id that is already in flight.
|
||||
fn own_id(kind: &str) -> String {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
format!("__openidea_{kind}_{}__", NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// How long a server has to answer a probe or take a cancellation.
|
||||
const PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Sends a cancellation to every server at once, since the call may run in any of them (its
|
||||
/// `projectPath` picks one); the answer of one that took it. A server that doesn't run the call
|
||||
/// keeps the id for a while, in case the call reaches it later. One that doesn't answer in
|
||||
/// time holds up neither the others nor the bridge.
|
||||
async fn cancel_everywhere(
|
||||
candidates: Vec<Discovery>,
|
||||
project: &Path,
|
||||
message: &Value,
|
||||
scope: &str,
|
||||
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
|
||||
) -> Option<Answer> {
|
||||
let mut posts = tokio::task::JoinSet::new();
|
||||
for info in candidates {
|
||||
let (project, message, scope, sent) = (project.to_owned(), message.clone(), scope.to_owned(), sent.clone());
|
||||
posts.spawn(async move {
|
||||
tokio::time::timeout(PROBE_WAIT, post_one(&info, &project, &message, &scope, &sent)).await
|
||||
});
|
||||
}
|
||||
let mut accepted = None;
|
||||
while let Some(posted) = posts.join_next().await {
|
||||
if let Ok(Ok(Ok(answer))) = posted {
|
||||
accepted.get_or_insert(answer);
|
||||
}
|
||||
}
|
||||
accepted
|
||||
}
|
||||
|
||||
/// Picks the server for the connection's folder again when the one picked is gone or another
|
||||
/// server started since, as `initialize` picks it: the first of `candidates` (the one picked
|
||||
/// before leads) that serves the folder, else the first. Puts it first.
|
||||
async fn pick_again(candidates: &mut Vec<Discovery>, project: &Path, scope: &str, state: &Mutex<BridgeState>) {
|
||||
{
|
||||
let state = state.lock().unwrap();
|
||||
let kept = state.preferred.as_ref().is_some_and(|preferred| candidates.contains(preferred));
|
||||
if kept && candidates.iter().all(|c| state.picked_among.contains(c)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut chosen = 0;
|
||||
if candidates.len() > 1 {
|
||||
for (pos, info) in candidates.iter().enumerate() {
|
||||
if serves_project(info, project, scope).await {
|
||||
chosen = pos;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let picked = candidates.remove(chosen);
|
||||
candidates.insert(0, picked);
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(candidates[0].clone());
|
||||
state.picked_among = candidates.clone();
|
||||
}
|
||||
|
||||
/// Whether the server of `info` serves `project`: its `openidea/servesFolder` names a root.
|
||||
/// An IDE older than that method answers "method not found"; its `tools/list` answers "not
|
||||
/// open" for a folder it doesn't serve, so that answers instead. A server that doesn't answer
|
||||
/// in time doesn't serve it.
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = |method| serde_json::json!({ "jsonrpc": "2.0", "id": own_id("probe"), "method": method });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
let ask = async {
|
||||
let reply = match post_one(info, project, &probe(SERVES_FOLDER), scope, &discard).await {
|
||||
Ok(Answer::Body(StatusCode::OK, body)) => serde_json::from_slice::<Value>(&body).ok(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(reply) = reply else { return false };
|
||||
if reply.pointer("/error/code").and_then(Value::as_i64) == Some(METHOD_NOT_FOUND) {
|
||||
return match post_one(info, project, &probe("tools/list"), scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
reply.pointer("/result/root").is_some_and(Value::is_string)
|
||||
};
|
||||
tokio::time::timeout(PROBE_WAIT, ask).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn is_not_open_reply(answer: &Answer) -> bool {
|
||||
@@ -253,7 +353,7 @@ async fn post_one(
|
||||
project.display()
|
||||
)
|
||||
};
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(info);
|
||||
let stream = tokio::net::TcpStream::connect(at).await.map_err(|_| not_running())?;
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
|
||||
.await
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegi
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
struct Registry {
|
||||
project: PathBuf,
|
||||
@@ -28,6 +28,10 @@ impl ToolRegistry for Registry {
|
||||
}])
|
||||
}
|
||||
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("everything")]
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -48,6 +52,18 @@ impl ToolRegistry for Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only tool with no arguments.
|
||||
fn named(name: &str) -> Tool {
|
||||
Tool {
|
||||
name: name.into(),
|
||||
description: format!("The tool {name}"),
|
||||
input_schema: json!({ "type": "object" }),
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
_tmp: tempfile::TempDir,
|
||||
project: PathBuf,
|
||||
@@ -215,25 +231,30 @@ async fn requests_without_the_token_or_from_web_pages_are_refused() {
|
||||
async fn folders_that_are_not_open_are_named_in_the_error() {
|
||||
let s = setup();
|
||||
let elsewhere = s.project.parent().unwrap().join("elsewhere");
|
||||
let header = format!("X-OpenIDEA-Project: {}", elsewhere.display());
|
||||
let (status, body) =
|
||||
post(&s, "/mcp", &[&bearer(&s), &header], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert_eq!(status, 200);
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert!(reply["error"]["message"].as_str().unwrap().contains("isn't open in OpenIDEA"));
|
||||
// The connection's folder isn't open: the list is the one without a project, and a call
|
||||
// that names no project of its own is refused with the folder named.
|
||||
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
|
||||
assert_eq!(call["error"]["code"], -32001, "{call}");
|
||||
let message = call["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
|
||||
// No folder named and one window: that window's project lists its tools.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
|
||||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
|
||||
}
|
||||
|
||||
/// One project open in a window and the folders served without a window.
|
||||
/// One project open in a window, the folders served without a window and, optionally, the
|
||||
/// root of a window on a remote host (which has no tools here).
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Vec<PathBuf>,
|
||||
remote: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
|
||||
}
|
||||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||||
/// background policy answers.
|
||||
@@ -242,7 +263,13 @@ impl ToolRegistry for WithBackground {
|
||||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||||
served.max_by_key(|root| root.components().count()).cloned()
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anything")]
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
if self.remote.as_deref() == Some(project) {
|
||||
return Err("project is on a remote host".into());
|
||||
}
|
||||
Ok(vec![Tool {
|
||||
name: "where".into(),
|
||||
description: format!("Names {}", project.display()),
|
||||
@@ -257,20 +284,23 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the server of `s` and serves `registry` in its place.
|
||||
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
|
||||
s.server.take().unwrap().stop();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
|
||||
}
|
||||
|
||||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||||
/// that holds the open project; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
);
|
||||
let registry = WithBackground { open: s.project.clone(), background, remote: None };
|
||||
restart(&mut s, registry);
|
||||
(s, inventory)
|
||||
}
|
||||
|
||||
@@ -291,6 +321,7 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||||
assert!(!instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||||
@@ -334,16 +365,41 @@ async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_ser
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||||
let (s, inventory) = setup_with_background(&[]);
|
||||
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
|
||||
let reply = rpc_for(&s, &inventory, method, params).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
}
|
||||
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
|
||||
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
|
||||
assert!(init["result"]["instructions"].is_string(), "initialize answers without a project: {init}");
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(
|
||||
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
|
||||
"{instructions}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
|
||||
let (mut s, inventory) = setup_with_background(&[]);
|
||||
let base = s.project.parent().unwrap().to_owned();
|
||||
let remote = base.join("remote");
|
||||
let registry =
|
||||
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
|
||||
restart(&mut s, registry);
|
||||
let cases = [
|
||||
(s.project.join("src"), json!(s.project)),
|
||||
(inventory.join("src"), json!(inventory)),
|
||||
(base.join("elsewhere"), Value::Null),
|
||||
// A remote window's root is that host's to serve.
|
||||
(remote, Value::Null),
|
||||
];
|
||||
for (folder, root) in cases {
|
||||
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
|
||||
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -413,6 +469,9 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anywhere")]
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -436,8 +495,14 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
// No folder named and two windows: the list without a project, and a call has to name one.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
|
||||
let list: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
|
||||
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(reply["error"]["code"], -32602, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
|
||||
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
|
||||
@@ -624,3 +689,370 @@ async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_clos
|
||||
server_a.stop();
|
||||
assert!(!discovery.exists());
|
||||
}
|
||||
|
||||
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
|
||||
/// out once the answer to the one before has come back.
|
||||
struct Client {
|
||||
input: tokio::io::DuplexStream,
|
||||
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
|
||||
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn start(discovery: &Path, folder: &Path) -> Self {
|
||||
let (input, bridge_input) = tokio::io::duplex(1 << 16);
|
||||
let (bridge_output, output) = tokio::io::duplex(1 << 16);
|
||||
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
|
||||
let bridge = tokio::spawn(async move {
|
||||
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
|
||||
});
|
||||
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
|
||||
}
|
||||
|
||||
/// Sends a request without waiting for its answer; its id.
|
||||
async fn send(&mut self, method: &str, params: Value) -> u64 {
|
||||
self.id += 1;
|
||||
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
|
||||
self.id
|
||||
}
|
||||
|
||||
async fn notify(&mut self, message: Value) {
|
||||
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
|
||||
}
|
||||
|
||||
async fn answer(&mut self, id: u64) -> Value {
|
||||
let answer = async {
|
||||
loop {
|
||||
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
if reply["id"] == id {
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
|
||||
}
|
||||
|
||||
async fn ask(&mut self, method: &str, params: Value) -> Value {
|
||||
let id = self.send(method, params).await;
|
||||
self.answer(id).await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
let Self { input, output, bridge, .. } = self;
|
||||
drop(input);
|
||||
bridge.await.unwrap().unwrap();
|
||||
drop(output);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
|
||||
/// servers that share its data directory.
|
||||
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for folder in folders {
|
||||
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
|
||||
}
|
||||
let discovery = discovery_path(&base.join("app-data"));
|
||||
(tmp, base, discovery)
|
||||
}
|
||||
|
||||
impl WithBackground {
|
||||
/// A window on `open` and `background` served without one.
|
||||
fn serving(open: &Path, background: &Path) -> Self {
|
||||
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
|
||||
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
|
||||
/// Each order makes the other server the one in `server.json`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let servers = if b_first {
|
||||
[start_in(&discovery, b()), start_in(&discovery, a())]
|
||||
} else {
|
||||
[start_in(&discovery, a()), start_in(&discovery, b())]
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A client started in `work`, a folder neither server serves: the tools of the server
|
||||
/// `initialize` picked, and each call goes where its `projectPath` is served.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
|
||||
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
|
||||
let repo = work.join("repo");
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &repo);
|
||||
// The server started last is in `server.json`; with neither serving the folder,
|
||||
// `initialize` settles on it.
|
||||
let (servers, listed) = if b_first {
|
||||
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
|
||||
} else {
|
||||
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &work);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
|
||||
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
|
||||
let call = client.ask("tools/call", in_repo).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
|
||||
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
|
||||
let call = client.ask("tools/call", in_a).await;
|
||||
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
|
||||
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
|
||||
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
|
||||
// A call sent to the other server doesn't move the connection there.
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The server `initialize` picked stops, or one that serves the folder starts later: the
|
||||
/// next message picks again, as `initialize` does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let serving_b = format!("Names {}", proj_b.display());
|
||||
|
||||
// Only A runs at `initialize`; B starts afterwards.
|
||||
let server_a = start_in(&discovery, a());
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let server_b = start_in(&discovery, b());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
|
||||
|
||||
// B restarts, and A restarts after it, so A is first in the discovery file.
|
||||
server_b.stop();
|
||||
let server_b = start_in(&discovery, b());
|
||||
server_a.stop();
|
||||
let server_a = start_in(&discovery, a());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
|
||||
/// that didn't serve the folder may serve it now.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||||
let server_b = start_in(&discovery, WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
let port = server_b.port();
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
|
||||
server_b.stop();
|
||||
// stop signals the accept task; the listener is closed asynchronously. Wait for
|
||||
// the old port to be released, as the IDE does before restarting its server.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the stopped server should release its port");
|
||||
let server_b = McpServer::start_with(
|
||||
Arc::new(WithBackground::serving(&proj_c, &proj_b)),
|
||||
Some(discovery.clone()),
|
||||
&tokio::runtime::Handle::current(),
|
||||
ServerOptions { port: Some(port), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(server_b.port(), port, "{:?}", server_b.port_unavailable());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
|
||||
struct Holding {
|
||||
open: PathBuf,
|
||||
background: PathBuf,
|
||||
}
|
||||
|
||||
impl ToolRegistry for Holding {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
|
||||
path.starts_with(&self.background).then(|| self.background.clone())
|
||||
}
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![named("hold")])
|
||||
}
|
||||
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
|
||||
tokio::runtime::Handle::current().block_on(cancel.cancelled());
|
||||
Err(ToolCallError::Failed("cancelled".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
|
||||
/// cancellation reaches B.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_a);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
|
||||
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
|
||||
client
|
||||
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
|
||||
.await;
|
||||
let answer = client.answer(call).await;
|
||||
assert_eq!(answer["result"]["isError"], true, "{answer}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
|
||||
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
|
||||
/// outside `serves`.
|
||||
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
|
||||
use http_body_util::{BodyExt, Full};
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let serves = serves.clone();
|
||||
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
|
||||
let serves = serves.clone();
|
||||
async move {
|
||||
let query = request.uri().query().unwrap_or_default().to_owned();
|
||||
let folder = query.strip_prefix("project=").unwrap_or_default();
|
||||
let folder =
|
||||
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
|
||||
let body = request.into_body().collect().await.unwrap().to_bytes();
|
||||
let message: Value = serde_json::from_slice(&body).unwrap();
|
||||
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
|
||||
let id = message["id"].clone();
|
||||
let reply = match message["method"].as_str().unwrap_or_default() {
|
||||
_ if id.is_null() => None,
|
||||
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
|
||||
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
|
||||
"instructions": "an older OpenIDEA" } })),
|
||||
"tools/list" if served => {
|
||||
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
|
||||
}
|
||||
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
|
||||
"tools/list" | "tools/call" => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
|
||||
),
|
||||
_ => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
|
||||
),
|
||||
};
|
||||
let response = match reply {
|
||||
Some(reply) => hyper::Response::builder()
|
||||
.header("content-type", "application/json")
|
||||
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
|
||||
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
|
||||
};
|
||||
Ok::<_, std::convert::Infallible>(response.unwrap())
|
||||
}
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
let io = hyper_util::rt::TokioIo::new(stream);
|
||||
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
// Written once it listens, so the stale-entry sweep of the next server keeps it.
|
||||
let info = Discovery {
|
||||
address: std::net::Ipv4Addr::LOCALHOST.into(),
|
||||
port,
|
||||
token: "test-token-older".into(),
|
||||
pid: std::process::id(),
|
||||
version: "0.1.0".into(),
|
||||
};
|
||||
info.write(discovery).unwrap();
|
||||
server
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
|
||||
for older_serves in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
|
||||
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
|
||||
// Either way the server that doesn't serve the folder is in `server.json`.
|
||||
let (older, real) = if older_serves {
|
||||
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
|
||||
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
|
||||
} else {
|
||||
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
|
||||
(fake_older_ide(&discovery, None).await, real)
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &folder.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
|
||||
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
let answered = match older_serves {
|
||||
true => call["result"]["content"][0]["text"] == "older",
|
||||
false => call["result"]["structuredContent"]["project"] == json!(folder),
|
||||
};
|
||||
assert!(answered, "older_serves {older_serves}: {call}");
|
||||
client.close().await;
|
||||
real.stop();
|
||||
older.abort();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
|
||||
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project.
|
||||
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all
|
||||
//! and links what they depend on (CocoaPods, Tuist, a SwiftPM workspace), so its schemes and theirs
|
||||
//! are built through it, even when it has no schemes of its own.
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
use crate::RunConfig;
|
||||
@@ -25,7 +26,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
.iter()
|
||||
.map(|s| s.container.clone())
|
||||
.find(|c| c.extension().is_some_and(|x| x == "xcworkspace"))
|
||||
.or_else(|| crate::xcode::pods_workspace(dir));
|
||||
.or_else(|| crate::xcode::root_workspace(dir));
|
||||
for scheme in &found {
|
||||
let container = workspace.as_ref().unwrap_or(&scheme.container);
|
||||
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
|
||||
@@ -98,13 +99,15 @@ mod tests {
|
||||
std::fs::create_dir_all(&schemes).unwrap();
|
||||
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
|
||||
}
|
||||
// `pod install`'s workspace has no schemes of its own.
|
||||
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
|
||||
|
||||
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
|
||||
// Project only.
|
||||
std::fs::rename(root.join("Pods"), root.join("Pods.off")).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]);
|
||||
std::fs::rename(root.join("Pods.off"), root.join("Pods")).unwrap();
|
||||
// `pod install`'s (or Tuist's) workspace has no schemes of its own.
|
||||
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
|
||||
// Without a Podfile, a `Pods/` folder is just another project.
|
||||
assert!(is_project(&root.join("Pods")));
|
||||
|
||||
@@ -122,10 +125,86 @@ mod tests {
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
|
||||
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace")));
|
||||
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("App.xcworkspace")));
|
||||
// Without a workspace named after a project, the first by name.
|
||||
std::fs::remove_dir(root.join("App.xcworkspace")).unwrap();
|
||||
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
|
||||
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace")));
|
||||
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("Aardvark.xcworkspace")));
|
||||
}
|
||||
|
||||
fn project_with_scheme(root: &Path) {
|
||||
let scheme = std::fs::read_to_string(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
|
||||
)
|
||||
.unwrap();
|
||||
let schemes = root.join("App.xcodeproj/xcshareddata/xcschemes");
|
||||
std::fs::create_dir_all(&schemes).unwrap();
|
||||
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
|
||||
}
|
||||
|
||||
fn workspace(root: &Path, name: &str, location: &str) {
|
||||
std::fs::create_dir(root.join(name)).unwrap();
|
||||
let data = format!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"{location}\">\n </FileRef>\n</Workspace>\n"
|
||||
);
|
||||
std::fs::write(root.join(name).join("contents.xcworkspacedata"), data).unwrap();
|
||||
}
|
||||
|
||||
fn run_and_test_args(root: &Path) -> (Vec<String>, Vec<String>) {
|
||||
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
|
||||
let (mut out, mut tests) = (Vec::new(), Vec::new());
|
||||
detect(root, &mut out);
|
||||
super::super::xcode_test::detect(root, &mut tests);
|
||||
(args(&out), args(&tests))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_workspace_beside_the_project_is_not_built() {
|
||||
// No Podfile: a leftover or playground workspace that doesn't name the project.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
project_with_scheme(root);
|
||||
workspace(root, "Playground.xcworkspace", "group:Playground.playground");
|
||||
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
|
||||
assert_eq!(crate::xcode::root_workspace(root), None);
|
||||
let (run, test) = run_and_test_args(root);
|
||||
assert_eq!(run, ["-project App.xcodeproj -scheme App -configuration Staging"]);
|
||||
assert_eq!(test, ["test -project App.xcodeproj -scheme App"]);
|
||||
// A project in a subfolder with the same name is not this one.
|
||||
workspace(root, "Sub.xcworkspace", "group:Sub/App.xcodeproj");
|
||||
assert_eq!(crate::xcode::root_workspace(root), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tuist_workspace_that_references_the_project_is_built() {
|
||||
// Tuist names the workspace after the manifest, not after the project.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
project_with_scheme(root);
|
||||
workspace(root, "Wasai.xcworkspace", "container:App.xcodeproj");
|
||||
let (run, test) = run_and_test_args(root);
|
||||
assert_eq!(run, ["-workspace Wasai.xcworkspace -scheme App -configuration Staging"]);
|
||||
assert_eq!(test, ["test -workspace Wasai.xcworkspace -scheme App"]);
|
||||
std::fs::remove_dir_all(root.join("Wasai.xcworkspace")).unwrap();
|
||||
workspace(root, "Other.xcworkspace", "group:./App.xcodeproj");
|
||||
assert_eq!(crate::xcode::root_workspace(root), Some(root.join("Other.xcworkspace")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_without_schemes_builds_the_projects_schemes() {
|
||||
// A hand-made workspace named after the project, with no Podfile and no schemes.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
project_with_scheme(root);
|
||||
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
|
||||
let (run, test) = run_and_test_args(root);
|
||||
assert_eq!(run, ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
|
||||
assert_eq!(test, ["test -workspace App.xcworkspace -scheme App"]);
|
||||
// Workspace only: nothing to build without a scheme.
|
||||
std::fs::remove_dir_all(root.join("App.xcodeproj")).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests,
|
||||
//! through the CocoaPods workspace when the project has one.
|
||||
//! through the workspace beside the project when there is one (CocoaPods, Tuist).
|
||||
//! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`).
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
@@ -7,14 +7,14 @@ use crate::RunConfig;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
// With a Podfile every scheme is built through the Pods workspace, assuming one app project
|
||||
// per folder: the workspace `pod install` writes links that project's targets.
|
||||
let pods = crate::xcode::pods_workspace(root);
|
||||
// Every scheme is built through the workspace beside the projects, assuming it links their
|
||||
// targets, as the one `pod install` or Tuist writes does.
|
||||
let workspace = crate::xcode::root_workspace(root);
|
||||
for scheme in crate::xcode::schemes(root) {
|
||||
if !scheme.has_tests {
|
||||
continue;
|
||||
}
|
||||
let path = pods.as_ref().unwrap_or(&scheme.container);
|
||||
let path = workspace.as_ref().unwrap_or(&scheme.container);
|
||||
let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue };
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
out.push(
|
||||
@@ -41,7 +41,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
("xcode:test:App.xcodeproj:App", "test -project App.xcodeproj -scheme App".to_owned(), true),
|
||||
// Built through the workspace beside the project, as its run configuration is.
|
||||
("xcode:test:App.xcworkspace:App", "test -workspace App.xcworkspace -scheme App".to_owned(), true),
|
||||
(
|
||||
"xcode:test:App.xcworkspace:Everything",
|
||||
"test -workspace App.xcworkspace -scheme Everything".to_owned(),
|
||||
|
||||
@@ -636,23 +636,24 @@ impl ProcessManager {
|
||||
let mut cmd = CommandBuilder::new(&inv.program);
|
||||
cmd.args(&inv.args);
|
||||
cmd.cwd(cwd);
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
} else {
|
||||
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),
|
||||
}
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
if !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::shell_env_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
for (k, v) in &env.vars {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let wait_writable = ide_core::input::nonblocking(
|
||||
|
||||
@@ -47,22 +47,35 @@ pub fn schemes(root: &Path) -> Vec<XcodeScheme> {
|
||||
containers.iter().flat_map(|c| container_schemes(c)).collect()
|
||||
}
|
||||
|
||||
/// The `.xcworkspace` `pod install` wrote next to the app's project, when `root` has a `Podfile`:
|
||||
/// the one named after an `.xcodeproj` in `root`, else the first by name (a leftover workspace
|
||||
/// may sit beside it). The project alone doesn't link the pods, so its schemes are built through
|
||||
/// this workspace, which usually has no schemes of its own. The frontend picks the same one
|
||||
/// (`podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
|
||||
pub fn pods_workspace(root: &Path) -> Option<PathBuf> {
|
||||
if !root.join("Podfile").is_file() {
|
||||
return None;
|
||||
}
|
||||
/// The `.xcworkspace` in `root` that its projects are built through. CocoaPods, Tuist and
|
||||
/// SwiftPM-workspace projects link their dependencies only in the workspace, which often has no
|
||||
/// schemes of its own, so the projects' schemes are built through it too. Without a `Podfile`
|
||||
/// only a workspace that is named after an `.xcodeproj` in `root`, or that references one
|
||||
/// ([`references_project`]), counts: a leftover or unrelated workspace would lack the schemes.
|
||||
/// With a `Podfile` it is the one `pod install` wrote: named after a project, else the first by
|
||||
/// name (the frontend's `podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
|
||||
pub fn root_workspace(root: &Path) -> Option<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = fs::read_dir(root).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
|
||||
dirs.sort();
|
||||
let has_ext = |p: &Path, ext: &str| p.extension().is_some_and(|e| e == ext);
|
||||
let projects: Vec<_> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).filter_map(|p| p.file_stem()).collect();
|
||||
let projects: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).collect();
|
||||
let workspaces: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcworkspace")).collect();
|
||||
let named = workspaces.iter().find(|w| w.file_stem().is_some_and(|s| projects.contains(&s)));
|
||||
named.or(workspaces.first()).map(|w| (*w).clone())
|
||||
let named = workspaces.iter().find(|w| projects.iter().any(|p| p.file_stem() == w.file_stem()));
|
||||
if root.join("Podfile").is_file() {
|
||||
return named.or(workspaces.first()).map(|w| (*w).clone());
|
||||
}
|
||||
let names: Vec<&str> = projects.iter().filter_map(|p| p.file_name()?.to_str()).collect();
|
||||
named.or_else(|| workspaces.iter().find(|w| references_project(w, &names))).map(|w| (*w).clone())
|
||||
}
|
||||
|
||||
/// Whether the workspace's `contents.xcworkspacedata` has a `FileRef` to one of `projects` (bundle
|
||||
/// names in the workspace's own folder), as `group:App.xcodeproj` or `container:App.xcodeproj`.
|
||||
fn references_project(workspace: &Path, projects: &[&str]) -> bool {
|
||||
let Ok(data) = fs::read_to_string(workspace.join("contents.xcworkspacedata")) else { return false };
|
||||
data.split("location").skip(1).filter_map(|rest| rest.split('"').nth(1)).any(|location| {
|
||||
let path = location.strip_prefix("group:").or_else(|| location.strip_prefix("container:"));
|
||||
path.map(|p| p.trim_start_matches("./")).is_some_and(|p| projects.contains(&p))
|
||||
})
|
||||
}
|
||||
|
||||
/// The `Pods/` folder of a CocoaPods project: its `Pods.xcodeproj` is generated, not the app.
|
||||
@@ -253,12 +266,10 @@ pub const MAC: &str = "macos";
|
||||
|
||||
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the `-destination`
|
||||
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme).
|
||||
pub fn build_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: Option<&str>,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme). There is no `-derivedDataPath`:
|
||||
/// a run builds where Xcode does, so Xcode's builds and the IDE's share one build folder, and the
|
||||
/// build log that xcode-build-server's `build_root` reads (`buildServer.json`) is the latest of either.
|
||||
pub fn build_args(params: &BTreeMap<String, String>, destination: Option<&str>) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
@@ -270,7 +281,6 @@ pub fn build_args(
|
||||
if let Some(destination) = destination {
|
||||
args.extend(["-destination".to_owned(), destination.to_owned()]);
|
||||
}
|
||||
args.extend(["-derivedDataPath".to_owned(), derived_data.to_string_lossy().into_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
@@ -458,13 +468,11 @@ fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
|
||||
/// Where a run of `params` builds: [`MAC_DESTINATION`] when the scheme's app runs on the Mac
|
||||
/// ([`runs_on_mac`]), else `id=<udid>` of the configured simulator or the default one. A Clean
|
||||
/// Build Folder of the configuration uses the same destination.
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data: &Path) -> IdeResult<String> {
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<String> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
let args = [
|
||||
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
|
||||
vec!["-showBuildSettings".into(), "-json".into()],
|
||||
]
|
||||
.concat();
|
||||
let args =
|
||||
[build_args(params, None).map_err(IdeError::invalid)?, vec!["-showBuildSettings".into(), "-json".into()]]
|
||||
.concat();
|
||||
if runs_on_mac(&output(dir, "xcodebuild", &args)?, simulator).map_err(IdeError::invalid)? {
|
||||
return Ok(MAC_DESTINATION.to_owned());
|
||||
}
|
||||
@@ -476,20 +484,19 @@ pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data:
|
||||
}
|
||||
|
||||
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
|
||||
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; it builds in Xcode's
|
||||
/// DerivedData location ([`build_args`]). The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
|
||||
}
|
||||
let params = &config.extras.params;
|
||||
let derived_data = crate::xcode_clean::ide_derived_data(cache_dir);
|
||||
let show =
|
||||
|args: &[String]| output(dir, "xcodebuild", &[args, &["-showBuildSettings".into(), "-json".into()]].concat());
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
let destination = destination(dir, params)?;
|
||||
if destination == MAC_DESTINATION {
|
||||
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
|
||||
let args = build_args(params, Some(MAC_DESTINATION)).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
config.command = "/bin/sh".into();
|
||||
@@ -506,7 +513,7 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I
|
||||
if let Some(reason) = device.as_ref().and_then(device_unready) {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
|
||||
let args = build_args(params, Some(&destination)).map_err(IdeError::invalid)?;
|
||||
let settings = show(&args)?;
|
||||
let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
@@ -666,30 +673,18 @@ mod tests {
|
||||
[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Staging")]
|
||||
.map(|(k, v)| (k.to_owned(), v.to_owned()))
|
||||
.into();
|
||||
let dd = Path::new("/cache/DerivedData");
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-configuration",
|
||||
"Staging",
|
||||
"-destination",
|
||||
"id=U1",
|
||||
"-derivedDataPath",
|
||||
"/cache/DerivedData"
|
||||
]
|
||||
build_args(¶ms, Some("id=U1")).unwrap(),
|
||||
["-workspace", "App.xcworkspace", "-scheme", "App", "-configuration", "Staging", "-destination", "id=U1"]
|
||||
);
|
||||
params.insert("container".into(), "App.xcodeproj".into());
|
||||
params.remove("configuration");
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap()[..5],
|
||||
build_args(¶ms, Some("id=U1")).unwrap()[..5],
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
|
||||
);
|
||||
params.remove("scheme");
|
||||
assert_eq!(build_args(¶ms, Some("id=U1"), dd).unwrap_err(), "No scheme is set");
|
||||
assert_eq!(build_args(¶ms, Some("id=U1")).unwrap_err(), "No scheme is set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -790,23 +785,13 @@ mod tests {
|
||||
PathBuf::from("/dd/Build/Products/Debug/My App.app/Contents/MacOS/My App")
|
||||
);
|
||||
assert_eq!(mac_executable(&settings("macosx")).unwrap_err(), "The scheme builds no macOS application");
|
||||
let dd = Path::new("/dd");
|
||||
let params: BTreeMap<String, String> =
|
||||
[("container", "App.xcodeproj"), ("scheme", "App")].map(|(k, v)| (k.to_owned(), v.to_owned())).into();
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("platform=macOS"), dd).unwrap(),
|
||||
[
|
||||
"-project",
|
||||
"App.xcodeproj",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-destination",
|
||||
"platform=macOS",
|
||||
"-derivedDataPath",
|
||||
"/dd"
|
||||
]
|
||||
build_args(¶ms, Some("platform=macOS")).unwrap(),
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-destination", "platform=macOS"]
|
||||
);
|
||||
assert!(!build_args(¶ms, None, dd).unwrap().iter().any(|a| a == "-destination"));
|
||||
assert!(!build_args(¶ms, None).unwrap().iter().any(|a| a == "-destination"));
|
||||
}
|
||||
|
||||
/// The script builds, then runs the executable in its place: the stub app logs its arguments
|
||||
|
||||
@@ -8,29 +8,25 @@ use std::path::{Path, PathBuf};
|
||||
/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's.
|
||||
pub const KIND: &str = "xcode-clean";
|
||||
|
||||
/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache.
|
||||
/// Where the IDE's runs of a project built before they built in Xcode's DerivedData location
|
||||
/// (`xcodebuild -derivedDataPath`, under the project's cache): still deleted with the rest.
|
||||
pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
|
||||
cache_dir.join("xcode/DerivedData")
|
||||
}
|
||||
|
||||
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
|
||||
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
|
||||
/// macOS app) and DerivedData. `dir` is the configuration's working directory.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
/// macOS app). `dir` is the configuration's working directory.
|
||||
pub fn prepare(dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
let params = &config.extras.params;
|
||||
let derived_data = ide_derived_data(cache_dir);
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
config.args = clean_args(params, &destination, &derived_data).map_err(IdeError::invalid)?;
|
||||
let destination = destination(dir, params)?;
|
||||
config.args = clean_args(params, &destination).map_err(IdeError::invalid)?;
|
||||
config.command = "xcodebuild".into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: &str,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut args = build_args(params, Some(destination), derived_data)?;
|
||||
fn clean_args(params: &BTreeMap<String, String>, destination: &str) -> Result<Vec<String>, String> {
|
||||
let mut args = build_args(params, Some(destination))?;
|
||||
args.push("clean".into());
|
||||
Ok(args)
|
||||
}
|
||||
@@ -66,7 +62,8 @@ pub fn derived_data_of(settings: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's
|
||||
/// `<Name>-<hash>` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one.
|
||||
/// `<Name>-<hash>` one (Xcode's builds, and the IDE's runs and tests) and the one older IDE
|
||||
/// runs left in the project's cache.
|
||||
/// `dir` is the configuration's working directory.
|
||||
pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<Vec<PathBuf>> {
|
||||
let args = settings_args(params).map_err(IdeError::invalid)?;
|
||||
@@ -95,7 +92,7 @@ mod tests {
|
||||
fn clean_cleans_the_build_a_run_makes() {
|
||||
let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]);
|
||||
assert_eq!(
|
||||
clean_args(&p, "id=UDID", Path::new("/cache/xcode/DerivedData")).unwrap(),
|
||||
clean_args(&p, "id=UDID").unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
@@ -105,8 +102,6 @@ mod tests {
|
||||
"Debug",
|
||||
"-destination",
|
||||
"id=UDID",
|
||||
"-derivedDataPath",
|
||||
"/cache/xcode/DerivedData",
|
||||
"clean"
|
||||
]
|
||||
);
|
||||
|
||||
@@ -62,6 +62,22 @@ fn round_trip() {
|
||||
assert!(!loaded[0].detected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docker_detach_round_trips_in_project_params() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut configs = sample();
|
||||
for (config, (kind, detach)) in configs.iter_mut().zip([("docker-dockerfile", "true"), ("docker-image", "false")]) {
|
||||
config.kind = kind.into();
|
||||
config.extras.params.insert("detach".into(), detach.into());
|
||||
}
|
||||
save_user_configs(dir.path(), &configs).unwrap();
|
||||
|
||||
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
|
||||
assert!(project.contains("params = { detach = \"true\" }"), "{project}");
|
||||
assert!(project.contains("params = { detach = \"false\" }"), "{project}");
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_unrelated_content() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -344,15 +344,18 @@ impl TerminalManager {
|
||||
resolve_cwd(&options.cwd)
|
||||
};
|
||||
cmd.cwd(&cwd);
|
||||
// In a project folder: the project's environment (its direnv `.envrc`) too.
|
||||
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),
|
||||
}
|
||||
// portable-pty starts from a base env that re-reads HKCU\Environment on
|
||||
// Windows. A REG_MULTI_SZ value's interior NULs split the environment
|
||||
// block and CreateProcessW fails with os error 87 (#6806). Build the
|
||||
// child's environment from sanitized host vars instead.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(&cwd) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
for (k, v) in env {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(&k), std::ffi::OsStr::new(&v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
apply_powershell_env(&shell, &mut cmd);
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ impl LineEnding {
|
||||
}
|
||||
|
||||
/// How long [`Document::diff`] may look for separate regions, so a reload never stalls on a huge file.
|
||||
const DIFF_BUDGET: Duration = Duration::from_millis(50);
|
||||
pub const DIFF_BUDGET: Duration = Duration::from_millis(50);
|
||||
|
||||
type LineRange = std::ops::Range<usize>;
|
||||
|
||||
@@ -741,6 +741,12 @@ mod tests {
|
||||
assert_eq!(doc.text(), "😀x😀");
|
||||
}
|
||||
|
||||
/// `diff` without its time budget: a loaded machine can spend 50 ms before the first deadline
|
||||
/// check, and the coarser result is right too, just not what these tests pin down.
|
||||
fn unhurried_diff(doc: &Document, text: &str) -> ChangeSet {
|
||||
doc.diff_until(text, std::time::Instant::now() + std::time::Duration::from_secs(3600))
|
||||
}
|
||||
|
||||
fn numbered_lines(n: usize) -> String {
|
||||
(0..n).map(|i| format!("line {i}\n")).collect()
|
||||
}
|
||||
@@ -750,7 +756,7 @@ mod tests {
|
||||
let old = numbered_lines(400);
|
||||
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
|
||||
let at = |line: &str| (old.find(line).unwrap() + line.len() - 1) as u32;
|
||||
let set = Document::new(&old).diff(&new);
|
||||
let set = unhurried_diff(&Document::new(&old), &new);
|
||||
assert_eq!(
|
||||
set.changes,
|
||||
vec![tc(at("line 20\n"), at("line 20\n"), "x"), tc(at("line 299\n"), at("line 299\n"), "x")]
|
||||
@@ -760,14 +766,14 @@ mod tests {
|
||||
#[test]
|
||||
fn diff_handles_added_and_removed_lines() {
|
||||
let old = "a\nb\nc\nd\ne\nf\n";
|
||||
let set = Document::new(old).diff("a\nnew\nb\nc\ne\nf\n");
|
||||
let set = unhurried_diff(&Document::new(old), "a\nnew\nb\nc\ne\nf\n");
|
||||
assert_eq!(set.changes, vec![tc(2, 2, "new\n"), tc(5, 7, "")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_counts_utf16_past_astral_text() {
|
||||
let old = "😀 one\nsame\n😀 two\n";
|
||||
let set = Document::new(old).diff("😀 ONE\nsame\n😀 TWO\n");
|
||||
let set = unhurried_diff(&Document::new(old), "😀 ONE\nsame\n😀 TWO\n");
|
||||
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
|
||||
}
|
||||
|
||||
|
||||
@@ -171,6 +171,14 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
|
||||
dirs
|
||||
}
|
||||
|
||||
/// How [`Method::DotnetTool`] installs a package.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DotnetToolOptions {
|
||||
package: &'static str,
|
||||
prerelease: bool,
|
||||
min_sdk: u32,
|
||||
}
|
||||
|
||||
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
|
||||
match spec.fallback.unwrap_or(spec.method) {
|
||||
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
|
||||
@@ -1049,7 +1057,10 @@ impl Tools {
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::DotnetTool { package, prerelease, min_sdk } => {
|
||||
let options = DotnetToolOptions { package, prerelease, min_sdk };
|
||||
self.install_dotnet_tool(spec, options, langs, cancel, emit)?
|
||||
}
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
@@ -1220,20 +1231,28 @@ impl Tools {
|
||||
fn install_dotnet_tool(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let DotnetToolOptions { package, prerelease, .. } = options;
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let tool = dir.join("tool");
|
||||
std::fs::create_dir_all(&tool)?;
|
||||
let dotnet = self.which("dotnet").expect("checked");
|
||||
let version = self.dotnet_tool_version(spec, package, &dotnet, cancel, emit)?;
|
||||
let version = self.dotnet_tool_version(spec, options, langs, &dotnet, cancel, emit)?;
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool).args(["--verbosity", "normal"]);
|
||||
if let Some(version) = &version {
|
||||
c.args(["--version", version]);
|
||||
match &version {
|
||||
Some(version) => {
|
||||
c.args(["--version", version]);
|
||||
}
|
||||
None if prerelease => {
|
||||
c.arg("--prerelease");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let result = run_streamed_picking(c, cancel, emit, dotnet::nuget_errors).and_then(|_| {
|
||||
// The tool's apphost looks for .NET in the default location only; a
|
||||
@@ -1268,17 +1287,20 @@ impl Tools {
|
||||
}
|
||||
|
||||
/// The `--version` to install `package` with: `None` for the latest, or the newest version
|
||||
/// the installed SDK supports. Fails when there is no SDK, or no version runs on it.
|
||||
/// the installed SDK supports. Fails when there is no SDK, it is older than `min_sdk`, or no
|
||||
/// version runs on it.
|
||||
fn dotnet_tool_version(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
dotnet: &Path,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let mut c = self.command(dotnet);
|
||||
c.arg("--list-sdks");
|
||||
let DotnetToolOptions { package, prerelease, min_sdk } = options;
|
||||
let Some((true, out)) = run_quiet(c, Duration::from_secs(20)) else { return Ok(None) };
|
||||
let Some(sdk) = dotnet::newest_sdk(&out) else {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
@@ -1287,6 +1309,29 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
if sdk.major < min_sdk {
|
||||
// An alternative server for the same files that this SDK can install.
|
||||
let instead = usages(langs)
|
||||
.get(spec.name)
|
||||
.into_iter()
|
||||
.flat_map(|u| u.alternatives.iter())
|
||||
.filter(|name| *name != spec.name)
|
||||
.filter_map(|name| registry::find(name))
|
||||
.find(|alt| matches!(alt.method, Method::DotnetTool { min_sdk, .. } if min_sdk <= sdk.major))
|
||||
.map(|alt| format!(", or install {}, which runs on it", alt.display))
|
||||
.unwrap_or_default();
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{} needs the .NET {min_sdk} SDK or newer; found {}. Install it from {}{instead}",
|
||||
spec.display,
|
||||
sdk.version,
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
}
|
||||
// nuget.org's version index used below lists SemVer 1 versions only, which leaves out
|
||||
// most prereleases: let `--prerelease` pick the newest one.
|
||||
if prerelease {
|
||||
return Ok(None);
|
||||
}
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
|
||||
@@ -61,8 +61,10 @@ pub enum Method {
|
||||
/// (`~/Library/Application Support`: Bundler `exec`s a lone path string, and Ruby splits it).
|
||||
GemActive { gem: &'static str },
|
||||
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`.
|
||||
DotnetTool { package: &'static str },
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`. `prerelease` installs the newest version,
|
||||
/// prerelease or not, for packages that publish no stable one; `min_sdk` is the lowest
|
||||
/// .NET SDK major that can install the package (0: any).
|
||||
DotnetTool { package: &'static str, prerelease: bool, min_sdk: u32 },
|
||||
/// Platform archive download into `<tools>/<name>/`.
|
||||
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
|
||||
}
|
||||
@@ -1426,12 +1428,24 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://solargraph.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "roslyn-language-server",
|
||||
display: "Roslyn (C#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["roslyn-language-server"],
|
||||
// Prerelease builds only, as platform-specific tool packages: the .NET 10 SDK installs them.
|
||||
method: Method::DotnetTool { package: "roslyn-language-server", prerelease: true, min_sdk: 10 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/dotnet/roslyn",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "csharp-ls",
|
||||
display: "csharp-ls",
|
||||
kind: LanguageServer,
|
||||
commands: &["csharp-ls"],
|
||||
method: Method::DotnetTool { package: "csharp-ls" },
|
||||
method: Method::DotnetTool { package: "csharp-ls", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/razzmatazz/csharp-language-server",
|
||||
@@ -1442,7 +1456,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
display: "FsAutoComplete (F#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["fsautocomplete"],
|
||||
method: Method::DotnetTool { package: "fsautocomplete" },
|
||||
method: Method::DotnetTool { package: "fsautocomplete", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/ionide/FsAutoComplete",
|
||||
|
||||
@@ -838,7 +838,7 @@ esac"#,
|
||||
assert!(!env.root.join("ruby-lsp").exists());
|
||||
}
|
||||
|
||||
/// Installs of one tool name share a slot, so parallel csharp-ls tests would join each other's install.
|
||||
/// Installs of one tool name share a slot, so parallel .NET tool tests would join each other's install.
|
||||
#[cfg(unix)]
|
||||
static CSHARP_LS_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
|
||||
|
||||
@@ -1020,6 +1020,37 @@ exit 1"#,
|
||||
assert!(skipped);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn prerelease_dotnet_tool_installs_with_prerelease_on_a_new_enough_sdk() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(
|
||||
&env,
|
||||
"10.0.404",
|
||||
r#"/bin/mkdir -p "$5"; printf '#!/bin/sh\n' > "$5/roslyn-language-server"; /bin/chmod +x "$5/roslyn-language-server""#,
|
||||
);
|
||||
let info = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
let call = fs::read_to_string(&calls).unwrap();
|
||||
assert!(call.trim_end().ends_with("--verbosity normal --prerelease"), "{call}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_on_an_older_sdk_names_the_sdk_and_an_alternative_that_runs_on_it() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "8.0.416", FAKE_TOOL_INSTALL);
|
||||
let err = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
"Roslyn (C#) needs the .NET 10 SDK or newer; found 8.0.416. Install it from https://dotnet.microsoft.com/download, or install csharp-ls, which runs on it"
|
||||
);
|
||||
assert!(!calls.exists(), "dotnet tool install ran");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
|
||||
let spec = registry::find("kotlin-debug-adapter").unwrap();
|
||||
|
||||
@@ -16,13 +16,42 @@
|
||||
//! Mode. A caller that needs them downcasts through [`Backend::as_git`]; a
|
||||
//! caller that must work for every backend uses only the trait. As Perforce
|
||||
//! support lands, methods that turn out to be needed generically move here.
|
||||
//!
|
||||
//! Git repositories stay where they are (`ide-host`'s `Repos`). Every other
|
||||
//! backend comes from a [`BackendProvider`] registered with the host, which
|
||||
//! finds its working copies in a trusted project; the host then routes the
|
||||
//! Changes view, status, log and the IDE's file operations to them. A
|
||||
//! backend's own commands (changelists, locks…) reach its concrete type by
|
||||
//! upcasting to `&dyn Any` and downcasting.
|
||||
|
||||
use crate::{
|
||||
BlameLine, BlockHistory, ChangedFile, Commit, CommitOptions, FileStatus, LineHunk, LogQuery, PendingChange, Repo,
|
||||
RevisionChange, TextEncoding,
|
||||
BackendChangelist, BlameLine, BlockHistory, Branch, ChangedFile, Commit, CommitOptions, FileStatus, LineHunk,
|
||||
LogDetails, LogQuery, PendingChange, Repo, RevisionChange, TextEncoding, VcsKind,
|
||||
};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::any::Any;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Finds the working copies of one non-Git version control system. Registered
|
||||
/// once at host startup; the host asks it about the project root and each
|
||||
/// content root of a trusted project only, because answering may run the
|
||||
/// system's client (a `P4CONFIG` can name a program as its server).
|
||||
pub trait BackendProvider: Send + Sync {
|
||||
/// The working copy holding `folder` (at it or above it), `None` when
|
||||
/// there is none. An unreachable server or a missing client is `Ok(None)`
|
||||
/// or an error the host logs; either way the folder gets no backend.
|
||||
fn discover(&self, folder: &Path) -> IdeResult<Option<Arc<dyn Backend>>>;
|
||||
|
||||
/// A file or folder a working copy's root holds (Subversion's `.svn`, also in each
|
||||
/// directory external). The host looks for it below the project root and content roots,
|
||||
/// as it looks for nested `.git`, asks [`discover`](Self::discover) about each folder
|
||||
/// holding it, and rescans when one appears. `None` (Perforce, which has no marker): only
|
||||
/// the project root and content roots are asked.
|
||||
fn marker(&self) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The version-control surface the Changes view, diff viewer, annotate and log
|
||||
/// need from a repository. Implemented by every supported backend; today that
|
||||
@@ -32,10 +61,20 @@ use std::path::{Path, PathBuf};
|
||||
/// `:0` for the index, ids, `<id>^`…) for the Git backend; a Perforce backend
|
||||
/// takes `#have`, `@label` or a change number, and its "index" side is the
|
||||
/// opened-file state.
|
||||
pub trait Backend: Send + Sync {
|
||||
pub trait Backend: Send + Sync + Any {
|
||||
/// The repository's working root.
|
||||
fn root(&self) -> &Path;
|
||||
|
||||
/// The version control system this is.
|
||||
fn kind(&self) -> VcsKind;
|
||||
|
||||
/// What the branch widget shows where Git shows the current branch: a
|
||||
/// Perforce stream or client, Subversion's `trunk` or `branches/x`.
|
||||
/// `None` shows nothing; Git's own branch comes from `Repo::branch_info`.
|
||||
fn head_label(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Working-area changes, in the same shape `git status` gives: staged and
|
||||
/// unstaged kinds per path. A backend without an index reports everything
|
||||
/// as `unstaged`.
|
||||
@@ -49,6 +88,10 @@ pub trait Backend: Send + Sync {
|
||||
self.status()
|
||||
}
|
||||
|
||||
/// Raw bytes of `path` at `rev` (the encoding detection of a file that
|
||||
/// is not on disk reads them); `None` when absent there.
|
||||
fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>>;
|
||||
|
||||
/// Text of `path` at `rev`; `None` when absent there.
|
||||
fn file_at(&self, path: &Path, rev: Option<&str>, encoding: TextEncoding) -> IdeResult<Option<String>>;
|
||||
|
||||
@@ -107,6 +150,10 @@ pub trait Backend: Send + Sync {
|
||||
/// The change log, newest first.
|
||||
fn log(&self, query: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>>;
|
||||
|
||||
/// The full description of a change in the log (its message, and for Git
|
||||
/// the containing branches and signature).
|
||||
fn log_details(&self, revision: &str) -> IdeResult<LogDetails>;
|
||||
|
||||
/// Files `commit` changed.
|
||||
fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>>;
|
||||
|
||||
@@ -154,8 +201,71 @@ pub trait Backend: Send + Sync {
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
|
||||
) -> IdeResult<Vec<PendingChange>>;
|
||||
|
||||
// ---- shared actions a backend may support ----
|
||||
|
||||
/// Update Project (`vcs.update`): brings the working copy up to date with the
|
||||
/// server (`svn update`, `p4 sync`), sending output lines to `output`. Git's
|
||||
/// pull stays on [`Repo`].
|
||||
fn update(&self, _cancel: &CancellationToken, _output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
Err(IdeError::unavailable("this version control system cannot update the working copy"))
|
||||
}
|
||||
|
||||
/// The branch widget's list: what the working copy can switch to
|
||||
/// (Subversion's `trunk`, `branches/*`, `tags/*`; Perforce streams), the
|
||||
/// current one marked. Empty when there is nothing to switch to.
|
||||
fn branches(&self) -> IdeResult<Vec<Branch>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Switches the working copy to one of [`branches`](Self::branches)
|
||||
/// (`svn switch`, `p4 switch`).
|
||||
fn switch_to(&self, _branch: &str) -> IdeResult<()> {
|
||||
Err(IdeError::unavailable("this version control system cannot switch branches"))
|
||||
}
|
||||
|
||||
// ---- changelists the system keeps itself ----
|
||||
|
||||
/// The working copy's own changelists (`svn changelist`, Perforce pending
|
||||
/// changes), which the Commit window shows for this root instead of the
|
||||
/// IDE's lists. `None` (Git) leaves the grouping to the IDE
|
||||
/// (`.openidea/changelists.json`).
|
||||
fn changelists(&self) -> IdeResult<Option<Vec<BackendChangelist>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Creates an empty changelist and returns its id (`p4 change`; a
|
||||
/// Subversion list is its name, and exists once a file is moved to it).
|
||||
fn create_changelist(&self, _name: &str, _comment: &str) -> IdeResult<String> {
|
||||
Err(no_changelists())
|
||||
}
|
||||
|
||||
/// Renames or re-describes changelist `id`.
|
||||
fn edit_changelist(&self, _id: &str, _name: &str, _comment: &str) -> IdeResult<()> {
|
||||
Err(no_changelists())
|
||||
}
|
||||
|
||||
/// Deletes changelist `id`; its files go to the default list.
|
||||
fn delete_changelist(&self, _id: &str) -> IdeResult<()> {
|
||||
Err(no_changelists())
|
||||
}
|
||||
|
||||
/// Moves `paths` to changelist `id` ([`crate::changelists::DEFAULT_ID`] is
|
||||
/// the default list): `svn changelist` / `--remove`, `p4 reopen -c`.
|
||||
fn move_to_changelist(&self, _paths: &[PathBuf], _id: &str) -> IdeResult<()> {
|
||||
Err(no_changelists())
|
||||
}
|
||||
|
||||
// ---- IDE file operations ----
|
||||
|
||||
/// The editor is about to make read-only `paths` writable (Make File
|
||||
/// Writable, or typing into a read-only file). A checkout backend opens
|
||||
/// them for edit (`p4 edit`, `svn lock` for `svn:needs-lock`) first.
|
||||
/// Returns whether that changed what [`status`](Self::status) reports.
|
||||
/// Git keeps files writable, so this is a no-op.
|
||||
fn open_for_edit(&self, _paths: &[PathBuf]) -> IdeResult<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Files or folders the IDE created (project tree New File, refactorings).
|
||||
/// A checkout backend opens them for add (`p4 add`); Git tracks new files
|
||||
/// by content, so this is a no-op. Called after the files exist on disk;
|
||||
@@ -188,11 +298,27 @@ pub trait Backend: Send + Sync {
|
||||
}
|
||||
}
|
||||
|
||||
fn no_changelists() -> IdeError {
|
||||
IdeError::unavailable("this version control system keeps no changelists; the IDE does")
|
||||
}
|
||||
|
||||
impl Backend for Repo {
|
||||
fn root(&self) -> &Path {
|
||||
Repo::root(self)
|
||||
}
|
||||
|
||||
fn kind(&self) -> VcsKind {
|
||||
VcsKind::Git
|
||||
}
|
||||
|
||||
fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
|
||||
Repo::file_bytes_at(self, path, rev)
|
||||
}
|
||||
|
||||
fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
|
||||
Repo::log_details(self, revision)
|
||||
}
|
||||
|
||||
fn status(&self) -> IdeResult<Vec<FileStatus>> {
|
||||
Repo::status(self)
|
||||
}
|
||||
|
||||
@@ -16,17 +16,17 @@ struct CommitMeta {
|
||||
/// Parses `git blame --porcelain` output into one entry per final line.
|
||||
pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Vec<BlameLine> {
|
||||
let mut metas: HashMap<String, CommitMeta> = HashMap::new();
|
||||
let mut lines: Vec<(u32, String, Option<IpcPath>)> = Vec::new();
|
||||
let mut current: Option<(u32, String)> = None;
|
||||
let mut lines: Vec<(u32, String, Option<IpcPath>, Option<u32>)> = Vec::new();
|
||||
let mut current: Option<(u32, String, Option<u32>)> = None;
|
||||
for line in out.split('\n') {
|
||||
if line.starts_with('\t') {
|
||||
if let Some((number, id)) = current.take() {
|
||||
if let Some((number, id, origin_line)) = current.take() {
|
||||
let origin = metas.get(&id).and_then(|m| m.origin_path.clone());
|
||||
lines.push((number, id, origin));
|
||||
lines.push((number, id, origin, origin_line));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((_, id)) = current.as_ref() {
|
||||
if let Some((_, id, _)) = current.as_ref() {
|
||||
let meta = metas.entry(id.clone()).or_default();
|
||||
if let Some(v) = line.strip_prefix("author ") {
|
||||
meta.author = v.to_string();
|
||||
@@ -48,7 +48,7 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
|
||||
}
|
||||
// Header: <sha> <orig-line> <final-line> [<group-count>]
|
||||
let mut parts = line.split(' ');
|
||||
let (Some(sha), Some(_orig), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
let (Some(sha), Some(orig_line), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
continue;
|
||||
};
|
||||
if sha.len() < 40 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
@@ -56,14 +56,23 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
|
||||
}
|
||||
let Ok(final_line) = final_line.parse::<u32>() else { continue };
|
||||
metas.entry(sha.to_string()).or_default();
|
||||
current = Some((final_line, sha.to_string()));
|
||||
// 1-based in the porcelain header.
|
||||
let origin_line = orig_line.parse::<u32>().ok().and_then(|n| n.checked_sub(1));
|
||||
current = Some((final_line, sha.to_string(), origin_line));
|
||||
}
|
||||
lines.sort_by_key(|(n, ..)| *n);
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|(_, sha, origin_path)| {
|
||||
.map(|(_, sha, origin_path, origin_line)| {
|
||||
let meta = metas.get(&sha).cloned().unwrap_or_default();
|
||||
BlameLine { commit: sha, author: meta.author, time_ms: meta.time_ms, summary: meta.summary, origin_path }
|
||||
BlameLine {
|
||||
commit: sha,
|
||||
author: meta.author,
|
||||
time_ms: meta.time_ms,
|
||||
summary: meta.summary,
|
||||
origin_path,
|
||||
origin_line,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -77,14 +86,16 @@ mod tests {
|
||||
let sha_a = "a".repeat(40);
|
||||
let sha_z = "0".repeat(40);
|
||||
let out = format!(
|
||||
"{sha_a} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
|
||||
{sha_a} 2 2\n\tl2\n\
|
||||
{sha_z} 3 3 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
|
||||
"{sha_a} 11 17 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
|
||||
{sha_a} 12 18\n\tl2\n\
|
||||
{sha_z} 19 19 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
|
||||
);
|
||||
let lines = parse_porcelain(&out, Path::new("root"), "f");
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert_eq!(lines[1].author, "Ann");
|
||||
assert_eq!(lines[1].time_ms, 100_000.0);
|
||||
assert_eq!(lines[2].author, "Not Committed Yet");
|
||||
// Where each line is in the attributed commit's file, 0-based: Show Diff opens there.
|
||||
assert_eq!(lines.iter().map(|l| l.origin_line).collect::<Vec<_>>(), [Some(10), Some(11), Some(18)]);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,17 @@ pub struct StagingPatchEntry {
|
||||
pub side: StagingPatchSide,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
/// The version control system holding a root.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VcsKind {
|
||||
#[default]
|
||||
Git,
|
||||
Perforce,
|
||||
Subversion,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BranchInfo {
|
||||
/// `None` when HEAD is detached.
|
||||
@@ -131,6 +141,10 @@ pub struct BlameLine {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub origin_path: Option<ide_core::IpcPath>,
|
||||
/// The line's 0-based number in the attributed commit's version of the file.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub origin_line: Option<u32>,
|
||||
}
|
||||
|
||||
/// History for Selection: the commits that changed a block of lines, newest first.
|
||||
@@ -960,6 +974,18 @@ pub struct Changelist {
|
||||
pub applied_commit: Option<CommitApplySource>,
|
||||
}
|
||||
|
||||
/// A changelist a version control system keeps itself (`svn changelist`, a Perforce
|
||||
/// pending change), with its files. Id [`changelists::DEFAULT_ID`] is the default list.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackendChangelist {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub comment: String,
|
||||
pub files: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
/// User change lists of a project and which list each changed file belongs to.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1025,7 +1051,7 @@ pub use submodules::SubmoduleRollbackSource;
|
||||
mod text_encoding;
|
||||
mod write;
|
||||
|
||||
pub use backend::Backend;
|
||||
pub use backend::{Backend, BackendProvider};
|
||||
pub use cherry_pick_plan::CherryPickOptions;
|
||||
pub use cli::{
|
||||
GitCommandObserver, detected_git_executable, filter_overrides_from, git_version, restrict, set_askpass_env,
|
||||
@@ -1048,7 +1074,7 @@ pub use rebase_editor::{
|
||||
RebaseEdit, RebaseEditKind, RebaseEditorOperation, RebaseEditorReply, RebaseFixupMessage, RebaseTodoRow,
|
||||
};
|
||||
pub use remotes::{FetchReport, Remote};
|
||||
pub use roots::{ProjectUpdateTarget, Repos};
|
||||
pub use roots::{ProjectUpdateTarget, Repos, marked_folders};
|
||||
pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey, SshSigningKey};
|
||||
pub use staged_text::{StagedText, StagedTextEdit, StagingLineHunk, StagingLineHunks};
|
||||
|
||||
|
||||
@@ -105,16 +105,26 @@ fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
|
||||
|
||||
pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
let start = if path.is_file() { path.parent().unwrap_or(path) } else { path };
|
||||
if let Err(e) = gix::discover::upwards(start) {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. } | E::NoGitRepositoryWithinCeiling { .. } | E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
let ts = gix::ThreadSafeRepository::discover(start).map_err(gx)?;
|
||||
let found = match gix::discover::upwards(start) {
|
||||
Ok((found, _trust)) => found,
|
||||
Err(e) => {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. }
|
||||
| E::NoGitRepositoryWithinCeiling { .. }
|
||||
| E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
};
|
||||
// Opened like `gix()` reopens it, not with `ThreadSafeRepository::discover`: that picks the
|
||||
// options for the folder owner's trust, and for a repository another user owns (reduced trust)
|
||||
// they cap the object database at 32 pack indices. A repository with more packs then fails to
|
||||
// read any object, so `HEAD` doesn't resolve (#7138). Trust is still decided per repository.
|
||||
let (git_dir, worktree) = found.into_repository_and_work_tree_directories();
|
||||
let ts = gix::ThreadSafeRepository::open(worktree.unwrap_or(git_dir)).map_err(gx)?;
|
||||
let repo = ts.to_thread_local();
|
||||
let Some(workdir) = repo.workdir() else {
|
||||
// Bare repositories have no worktree to show changes for.
|
||||
@@ -178,7 +188,7 @@ impl Repo {
|
||||
/// Verifies that the worktree root and its git directory exist on disk. A missing one marks
|
||||
/// the repository stale and is logged once; when both are back (a drive reconnected, `git
|
||||
/// worktree repair`), the mark is cleared, so a stale repository costs two `stat`s per check.
|
||||
pub(crate) fn check_valid(&self) -> IdeResult<()> {
|
||||
pub fn check_valid(&self) -> IdeResult<()> {
|
||||
use std::sync::atomic::Ordering;
|
||||
if self.root.is_dir() && self.git_dir.is_dir() {
|
||||
if self.stale.swap(false, Ordering::AcqRel) {
|
||||
@@ -658,6 +668,53 @@ mod tests {
|
||||
assert!(cmd.status().unwrap().success(), "{cmd:?}");
|
||||
}
|
||||
|
||||
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
|
||||
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
|
||||
/// pack directory: objects in every pack stay readable through the cached handle.
|
||||
#[test]
|
||||
fn a_repository_with_many_packs_reads_objects_from_all_of_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("repo");
|
||||
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
|
||||
let git = |args: &[&str]| {
|
||||
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}");
|
||||
String::from_utf8(out.stdout).unwrap().trim().to_owned()
|
||||
};
|
||||
git(&["config", "gc.auto", "0"]);
|
||||
git(&["config", "maintenance.auto", "false"]);
|
||||
let mut oids = Vec::new();
|
||||
for i in 0..40 {
|
||||
std::fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", &format!("c{i}")]);
|
||||
oids.push(git(&["rev-parse", "HEAD"]));
|
||||
let mut pack = Command::new("git")
|
||||
.current_dir(&root)
|
||||
.args(["pack-objects", "-q", "--revs", ".git/objects/pack/pack"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
use std::io::Write;
|
||||
let range = if i == 0 { "HEAD\n" } else { "HEAD\n^HEAD~1\n" };
|
||||
pack.stdin.take().unwrap().write_all(range.as_bytes()).unwrap();
|
||||
assert!(pack.wait().unwrap().success());
|
||||
git(&["prune-packed"]);
|
||||
}
|
||||
let packs = std::fs::read_dir(root.join(".git/objects/pack"))
|
||||
.unwrap()
|
||||
.filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|x| x == "idx"))
|
||||
.count();
|
||||
assert!(packs > 32, "{packs} pack indices");
|
||||
let repo = discover(&root).unwrap().unwrap();
|
||||
let gix = repo.gix().unwrap();
|
||||
assert_eq!(gix.head_id().unwrap().to_string(), *oids.last().unwrap());
|
||||
for oid in &oids {
|
||||
gix.find_commit(gix::ObjectId::from_hex(oid.as_bytes()).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a remounted volume looks like: every path and modification time is the same, but
|
||||
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
|
||||
#[test]
|
||||
|
||||
@@ -21,6 +21,42 @@ fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
|
||||
}
|
||||
|
||||
/// Calls `visit` with every folder below `root` that nested repositories are looked for in:
|
||||
/// up to [`MAX_DEPTH`] levels, skipping hidden and dependency folders and those `skip` rejects.
|
||||
fn walk_nested(root: &Path, skip: &dyn Fn(&Path) -> bool, mut visit: impl FnMut(&Path)) {
|
||||
let mut stack: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
if not_searched(&path, skip) {
|
||||
continue;
|
||||
}
|
||||
visit(&path);
|
||||
if depth + 1 < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Folders below `root` holding one of `markers` (a working copy's `.svn`), searched like
|
||||
/// nested Git repositories are: the same depth, and the same hidden, dependency and `skip`
|
||||
/// folders left out. `root` itself is not included. Sorted.
|
||||
pub fn marked_folders(root: &Path, markers: &[&str], skip: &dyn Fn(&Path) -> bool) -> Vec<PathBuf> {
|
||||
let mut found = Vec::new();
|
||||
walk_nested(root, skip, |path| {
|
||||
if markers.iter().any(|m| path.join(m).exists()) {
|
||||
found.push(path.to_path_buf());
|
||||
}
|
||||
});
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
/// The repositories of a project, sorted by root; lookups pick the innermost one.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repos {
|
||||
@@ -72,29 +108,15 @@ impl Repos {
|
||||
if let Some(r) = Repo::discover(project_root)? {
|
||||
repos.push(r);
|
||||
}
|
||||
let mut stack: Vec<(PathBuf, usize)> = vec![(project_root.to_path_buf(), 0)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
if not_searched(&path, skip) {
|
||||
continue;
|
||||
}
|
||||
if path.join(".git").exists()
|
||||
&& let Ok(Some(r)) = Repo::discover(&path)
|
||||
&& r.root() == path
|
||||
&& !repos.iter().any(|x| x.root() == r.root())
|
||||
{
|
||||
repos.push(r);
|
||||
}
|
||||
if depth + 1 < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
walk_nested(project_root, skip, |path| {
|
||||
if path.join(".git").exists()
|
||||
&& let Ok(Some(r)) = Repo::discover(path)
|
||||
&& r.root() == path
|
||||
&& !repos.iter().any(|x| x.root() == r.root())
|
||||
{
|
||||
repos.push(r);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Declared submodules remain Git roots under ignored folders or beyond the
|
||||
// filesystem scan's depth. An uninitialized submodule has no Git worktree.
|
||||
let mut next = 0;
|
||||
|
||||
@@ -287,6 +287,7 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
|
||||
time_ms: now,
|
||||
summary: String::new(),
|
||||
origin_path: None,
|
||||
origin_line: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -215,20 +215,20 @@ impl GitignoreStack {
|
||||
{
|
||||
let mut nested = self.nested.lock();
|
||||
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
|
||||
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
|
||||
nested.by_dir.retain(|k, _| !k.starts_with(target));
|
||||
nested.by_root.retain(|k, _| !k.starts_with(target));
|
||||
}
|
||||
// Always drop descendant keys. Requiring `target` itself to be a key
|
||||
// misses a repository created after the watch started: lookups then
|
||||
// stop at the new `.git`, so the filesystem root is never recorded,
|
||||
// and `reload_ignore_rules` from that root would leave a stale
|
||||
// "no rules" cache behind.
|
||||
nested.by_dir.retain(|k, _| !k.starts_with(target));
|
||||
nested.by_root.retain(|k, _| !k.starts_with(target));
|
||||
for stack in nested.by_root.values() {
|
||||
stack.invalidate_tree(dir);
|
||||
}
|
||||
}
|
||||
let mut cache = self.cache.lock();
|
||||
self.generation.fetch_add(1, Ordering::Relaxed);
|
||||
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
|
||||
if cache.contains_key(dir) {
|
||||
cache.retain(|k, _| !k.starts_with(dir));
|
||||
}
|
||||
cache.retain(|k, _| !k.starts_with(dir));
|
||||
}
|
||||
|
||||
pub fn repo_root(&self) -> Option<&Path> {
|
||||
@@ -545,4 +545,28 @@ mod tests {
|
||||
stack.invalidate_tree(&workspace.join("sub/.git"));
|
||||
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_init_after_the_first_listing_is_picked_up_from_the_filesystem_root() {
|
||||
// The project was opened before `git init`. A listing after the repository
|
||||
// appears, but before any ignore file is written, caches a nested stack whose
|
||||
// keys stop at the new `.git` and never include the filesystem root. Reloading
|
||||
// from that root must still drop those stale "no rules" entries.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("shared.ignore-me"), "x").unwrap();
|
||||
std::fs::write(root.join("private.ignore-me"), "x").unwrap();
|
||||
let stack = GitignoreStack::new(&root);
|
||||
assert_eq!(stack.repo_root(), None);
|
||||
std::fs::create_dir_all(root.join(".git/info")).unwrap();
|
||||
assert!(!stack.is_ignored(&root.join("shared.ignore-me"), false));
|
||||
assert!(!stack.is_ignored(&root.join("private.ignore-me"), false));
|
||||
std::fs::write(root.join(".gitignore"), "/shared.ignore-me\n").unwrap();
|
||||
std::fs::write(root.join(".git/info/exclude"), "/private.ignore-me\n").unwrap();
|
||||
stack.reload_repo_level();
|
||||
let top = root.ancestors().last().unwrap();
|
||||
stack.invalidate_tree(top);
|
||||
assert!(stack.is_ignored(&root.join("shared.ignore-me"), false));
|
||||
assert!(stack.is_ignored(&root.join("private.ignore-me"), false));
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,14 @@ impl Watcher {
|
||||
// `.git` that now exists (`git init`). `/` is no ancestor of `C:\…` on Windows, so take
|
||||
// the watch root's own topmost ancestor.
|
||||
let top = self.root.ancestors().last().unwrap_or(&self.root);
|
||||
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(top));
|
||||
let origin = self.rules.repo_root().unwrap_or(top);
|
||||
self.rules.invalidate_tree(origin);
|
||||
// After `git init`, a listing may have cached a nested stack whose keys
|
||||
// stop at the new `.git` and never include `top`. Drop the watched tree
|
||||
// itself too, which also covers a Windows `C:\` vs `\\?\C:\` mismatch.
|
||||
if origin != self.root.as_path() {
|
||||
self.rules.invalidate_tree(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
/// The watched directory (canonical).
|
||||
|
||||
@@ -371,6 +371,28 @@ fn watcher_read_dir_sees_a_repository_made_after_it_started() {
|
||||
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
|
||||
}
|
||||
|
||||
/// Same as above, but the first listing happens after `git init` and before the
|
||||
/// ignore files exist. That caches a nested stack that never recorded the
|
||||
/// filesystem root as a key — the case `reload_ignore_rules` hits when the
|
||||
/// watcher has already seen the new `.git`.
|
||||
#[test]
|
||||
fn watcher_read_dir_sees_ignore_files_written_after_a_post_init_listing() {
|
||||
let (_t, r) = root();
|
||||
write(&r.join("shared.ignore-me"), "x");
|
||||
write(&r.join("private.ignore-me"), "x");
|
||||
let sink: SharedSink = Arc::new(|_| {});
|
||||
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
|
||||
assert_eq!(watcher.repo_root(), None);
|
||||
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
|
||||
assert!(watcher.read_dir(&r, &[]).unwrap().iter().all(|e| !e.ignored));
|
||||
write(&r.join(".gitignore"), "/shared.ignore-me\n");
|
||||
write(&r.join(".git/info/exclude"), "/private.ignore-me\n");
|
||||
watcher.reload_ignore_rules();
|
||||
let ignored: BTreeSet<String> =
|
||||
watcher.read_dir(&r, &[]).unwrap().into_iter().filter(|e| e.ignored).map(|e| e.name).collect();
|
||||
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watcher_reports_changes() {
|
||||
let (_t, r) = root();
|
||||
|
||||
@@ -604,7 +604,9 @@ fn external_change_in_two_places_patches_each() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
|
||||
fs::write(&path, &new).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let in_budget = started.elapsed() < ide_text::DIFF_BUDGET;
|
||||
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, new);
|
||||
let events = f.events.lock();
|
||||
@@ -612,7 +614,18 @@ fn external_change_in_two_places_patches_each() {
|
||||
IdeEvent::DocPatched { changes, .. } => Some(changes),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(changes.map(Vec::len), Some(2));
|
||||
let changes = changes.expect("a patch");
|
||||
let mut replayed = ide_text::Document::new(&old);
|
||||
replayed.apply(0, &ChangeSet { changes: changes.clone() }).unwrap();
|
||||
assert_eq!(replayed.text(), new);
|
||||
// Merged or not, the patch stays between the two edited lines.
|
||||
let first = old.find("line 20\n").unwrap() as u32;
|
||||
let last = (old.find("line 299\n").unwrap() + "line 299\n".len()) as u32;
|
||||
assert!(changes[0].from >= first && changes[changes.len() - 1].to <= last, "{changes:?}");
|
||||
// Past the diff budget (a loaded machine) the two regions may come as one, still correctly.
|
||||
if in_budget {
|
||||
assert_eq!(changes.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -488,7 +488,7 @@
|
||||
"footer": {
|
||||
"socials": {
|
||||
"github": "https://github.com/l0ng-ai/openidea",
|
||||
"discord": "https://discord.gg/2Zy4yn7gP"
|
||||
"discord": "https://discord.gg/AsZqMgxZm"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,8 @@ Use the executable path from **Copy Stdio Config**; the macOS path above is only
|
||||
|
||||
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
|
||||
|
||||
A client started in a folder outside every project, such as a folder that only holds repositories, still gets the tools. Each call then names its project with `projectPath`, and the server refuses a call without one.
|
||||
|
||||
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
|
||||
|
||||
## Tools
|
||||
@@ -121,7 +123,7 @@ Notes on what they do:
|
||||
|
||||
`run_command` runs a shell command line in a tab of the Run tool window, with the shell of **Settings › Tools › Terminal**. The agent names the tab and OpenIDEA shows it as `_agent_<name>`, so you see the output as it comes and can type into the command, rerun it or stop it like any run.
|
||||
|
||||
Run configurations an agent starts with `execute_run_configuration` open a tab in the Run tool window too, as when you press Run: the console shows their output and Stop ends them. In a background project without a window (brave mode) they run without a tab.
|
||||
Run configurations an agent starts with `execute_run_configuration` open a tab in the Run tool window too, as when you press Run: the console shows their output and Stop ends them. In a background project without a window they run without a tab, after you allow them in a project window or under brave mode.
|
||||
|
||||
As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print plain lines instead of progress bars and redraws. The agent gets that output cleaned of escape sequences and cut to 2000 lines (`maxLinesCount`); beyond that the end stays, or the start or both ends with `truncateMode`. The tab's raw output log stays complete.
|
||||
|
||||
@@ -168,15 +170,15 @@ What trust decides: a trusted project works as one open in a window, with its la
|
||||
|
||||
A background project has no window, so some tools differ:
|
||||
|
||||
- `run_command` and `open_file_in_editor` need a window.
|
||||
- `run_command`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
|
||||
- `get_file_problems` and `get_project_problems` report what a window shows. In a background project they answer with an error that points to `check_files`.
|
||||
- `get_current_file` and `get_all_open_file_paths` also describe a window. In a background project they answer with an error that says the project needs a window.
|
||||
- `execute_run_configuration` and `build_project` work in a background project when **Run tools without confirmation (brave mode)** is on.
|
||||
- `execute_run_configuration`, `build_project`, `http_run_request` and destructive plugin tools ask in the project window you used last. The dialog has a line `Background project <folder name>` with the full path under it, and requests queue there. The dialog does not take keyboard focus: answer it with a click, or click into it first and then use the keys. If that window closes or loses trust, the request moves to another open project window. With no project window open, the call fails with "no project window is available". Brave mode runs these tools without asking, with or without a window.
|
||||
|
||||
## Safety
|
||||
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up.
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` ask in the project window you used last, and the dialog names the project.
|
||||
- Tools that write refuse paths outside the project.
|
||||
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
|
||||
|
||||
|
||||
@@ -79,26 +79,27 @@ With **Shell integration** on, zsh, bash and fish report the current directory a
|
||||
|
||||
**Settings › Tools › Terminal**:
|
||||
|
||||
| Setting | Default | Notes |
|
||||
| ---------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
| Setting | Default | Notes |
|
||||
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Let programs copy to the clipboard (OSC 52)** | on | tmux (`set-clipboard on`), Neovim and other programs set the clipboard, also over SSH. They can't read it; payloads over 1 MiB are ignored. |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
|
||||
Changes apply to open sessions right away. Colours follow the IDE theme.
|
||||
|
||||
|
||||
@@ -278,7 +278,7 @@ Retention is set in the **Local History** section of **Settings › Appearance &
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Commit** | Non-modal commit interface, clearing the message after commit, message inspections (blank line after subject, subject and body length, right margin), default commit checks. |
|
||||
| **Confirmation** | What to do when files are created or deleted, **Show options before Update**, confirm before dropping commits, highlight modified folders in the Project view, history row limit. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. Unreachable mapped repositories are marked unavailable while other repositories keep working. |
|
||||
| **Issue Navigation** | Regex patterns that turn issue IDs in commit messages into links (presets for JIRA, YouTrack and GitHub). |
|
||||
| **Log** | Reference and time display, visible columns. |
|
||||
| **Shelf** | Remove applied files from the shelf. |
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
---
|
||||
title: "C# and .NET"
|
||||
description: "C# with csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
description: "C# with the Roslyn language server or csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
---
|
||||
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through [csharp-ls](https://github.com/razzmatazz/csharp-language-server) and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). Both are installed as .NET tools, and both debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server](https://github.com/dotnet/roslyn) or [csharp-ls](https://github.com/razzmatazz/csharp-language-server), and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). All of them are installed as .NET tools, and both languages debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
|
||||
## Language server
|
||||
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | -------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
|
||||
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
|
||||
|
||||
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
|
||||
|
||||
When you go to the definition of a library type, csharp-ls returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
|
||||
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
|
||||
|
||||
@@ -22,17 +24,18 @@ When you go to the definition of a library type, csharp-ls returns decompiled so
|
||||
|
||||
You need the [.NET SDK](https://dotnet.microsoft.com/download) with `dotnet` on your `PATH`. The IDE runs every build, test and package command through it, and installs the language servers with it.
|
||||
|
||||
When a server is missing, opening a C# or F# file shows a "csharp-ls is not installed" (or FsAutoComplete) notification with **Install**. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
When no server is installed, opening a C# or F# file shows a "Roslyn (C#) is not installed" (or FsAutoComplete) notification with **Install**. If your SDK is older than .NET 10, the install says so and suggests csharp-ls instead. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
|
||||
| Tool | How it is installed |
|
||||
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` into the IDE's tools folder; nuget.org has only prerelease builds of it |
|
||||
| csharp-ls | `dotnet tool install --tool-path` into the IDE's tools folder (not a global tool) |
|
||||
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
|
||||
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
|
||||
|
||||
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
|
||||
|
||||
A `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
A `roslyn-language-server`, `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
|
||||
## The .NET tool window
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
|
||||
| `go install` | gopls, Delve, sqls. Needs Go. |
|
||||
| `rustup component add` | rust-analyzer (falls back to a download from Open VSX). |
|
||||
| `gem install` | Solargraph into its own gem home; Ruby LSP into the project's Ruby. |
|
||||
| `dotnet tool install` | csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| `dotnet tool install` | Roslyn (C#), csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| Release download | clangd, CodeLLDB, vscode-js-debug, JDT LS, java-debug, Kotlin LSP, Lua, Marksman, Taplo, ZLS, terraform-ls and others, from GitHub, Open VSX, Maven Central, the Eclipse download site or HashiCorp. |
|
||||
| Bundled | The Lombok agent for JDT LS ships with the app. |
|
||||
|
||||
@@ -99,7 +99,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
|
||||
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
|
||||
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
|
||||
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
|
||||
|
||||
@@ -76,9 +76,9 @@ When Git asks whether to add a new file you created in the IDE, the `.meta` file
|
||||
|
||||
## Code intelligence
|
||||
|
||||
C# in a Unity project uses the same language server as any other C# project, csharp-ls; see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
C# in a Unity project uses the same language server as any other C# project (Roslyn, or csharp-ls); see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
|
||||
csharp-ls reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
The server reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
|
||||
> C# project files are missing. In Unity, select an external script editor in Preferences > External Tools, then regenerate project files.
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
|
||||
```
|
||||
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
|
||||
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
|
||||
|
||||
@@ -49,33 +49,33 @@ Later:
|
||||
|
||||
## Capability reference
|
||||
|
||||
| Capability | Risk | Unlocks | API |
|
||||
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
|
||||
| `project.read` | Low | `Project::root`, `read_file`, `find_files`, `symbols`, `search_text`, `host::projects`, publishing diagnostics, `problems`, opening editors, decorations | 1.0 |
|
||||
| `project.write` | High | `Project::write_file`: creates and replaces text files inside the open projects, never git's own files (`.git`) | 1.3 |
|
||||
| `editor.read` | Low | `TextEditor::document`, `selections`, `host::open_editors` | 1.0 |
|
||||
| `editor.write` | Medium | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | Low | `vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff`, the pending commit, before-commit checks | 1.0 |
|
||||
| `vcs.write` | Medium | `vcs_fetch` (trusted projects only), `host::set_commit_message` | 1.0 |
|
||||
| `build.read` | Low | `build_dependencies`: the Maven / Gradle dependency graph the IDE resolved; trusted projects only | 1.10 |
|
||||
| `storage` | Low | `host::storage`, 64 MiB per plugin | 1.0 |
|
||||
| `events` | Low | File opened, closed and saved, files changed, editor focused, repository changed, settings changed | 1.0 |
|
||||
| `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 |
|
||||
| `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 |
|
||||
| `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 |
|
||||
| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project; trusted projects only | 1.18 |
|
||||
| `secrets` | Medium | `{{secret:<name>}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 |
|
||||
| `net:<host>` | Medium | `host::fetch` / `host::fetch_stream` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 |
|
||||
| `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 |
|
||||
| `net.http:<host>` | Medium | Unencrypted HTTP to that host | 1.4 |
|
||||
| `database.sources` | Medium | Manage only the plugin's own project database sources and write their credentials; trusted projects only | 1.4 |
|
||||
| `fs.read:<path>` | High | `host::fs` reads outside the projects, under that path | 1.0 (the `fs` interface: 1.3) |
|
||||
| `fs.write:<path>` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 |
|
||||
| `process:<program>` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 |
|
||||
| `lsp:<server>` | High | Send that running language server its own requests (`language_server_request`); trusted projects only | 1.9 |
|
||||
| `java.agent` | High | Run the plugin's Java agent inside the Java applications you start (see [Java agents](#java-agents)) | 1.10 |
|
||||
| `ipc:<path>` | High | Local Unix sockets or Windows named pipes on the project machine | 1.4 |
|
||||
| `ide.commands` | High | Run any IDE action or another plugin's command as if the user chose it, including running programs, committing and pushing. The plugin's own commands are exempt. | 1.4 |
|
||||
| Capability | Risk | Unlocks | API |
|
||||
| ------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
|
||||
| `project.read` | Low | `Project::root`, `read_file`, `find_files`, `symbols`, `search_text`, `host::projects`, publishing diagnostics, `problems`, opening editors, decorations | 1.0 |
|
||||
| `project.write` | High | `Project::write_file`: creates and replaces text files inside the open projects, never git's own files (`.git`) | 1.3 |
|
||||
| `editor.read` | Low | `TextEditor::document`, `selections`, `host::open_editors` | 1.0 |
|
||||
| `editor.write` | Medium | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | Low | `vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff`, the pending commit, before-commit checks | 1.0 |
|
||||
| `vcs.write` | Medium | `vcs_fetch` (trusted projects only), `host::set_commit_message` | 1.0 |
|
||||
| `build.read` | Low | `build_dependencies`: the Maven / Gradle dependency graph the IDE resolved; trusted projects only | 1.10 |
|
||||
| `storage` | Low | `host::storage`, 64 MiB per plugin | 1.0 |
|
||||
| `events` | Low | File opened, closed and saved, files changed, editor focused, repository changed, settings changed | 1.0 |
|
||||
| `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 |
|
||||
| `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 |
|
||||
| `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 |
|
||||
| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project; trusted projects only | 1.18 |
|
||||
| `secrets` | Medium | `{{secret:<name>}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 |
|
||||
| `net:<host>` | Medium | `host::fetch` / `host::fetch_stream` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 |
|
||||
| `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 |
|
||||
| `net.http:<host>` | Medium | Unencrypted HTTP to that host | 1.4 |
|
||||
| `database.sources` | Medium | Manage only the plugin's own project database sources and write their credentials; trusted projects only | 1.4 |
|
||||
| `fs.read:<path>` | High | `host::fs` reads outside the projects, under that path | 1.0 (the `fs` interface: 1.3) |
|
||||
| `fs.write:<path>` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 |
|
||||
| `process:<program>` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 |
|
||||
| `lsp:<server>` | High | Send that running language server its own requests (`language_server_request`); trusted projects only | 1.9 |
|
||||
| `java.agent` | High | Run the plugin's Java agent inside the Java applications you start (see [Java agents](#java-agents)) | 1.10 |
|
||||
| `ipc:<path>` | High | Local Unix sockets or Windows named pipes on the project machine | 1.4 |
|
||||
| `ide.commands` | High | Run any IDE action or another plugin's command as if the user chose it, including running programs, committing and pushing. The plugin's own commands are exempt. | 1.4 |
|
||||
|
||||
The **API** column is the oldest plugin API the manifest may admit when it declares the capability. For example, a manifest with `net.http:` must require `engines.openidea = "^1.4"` or later; installing and `openidea-plugin check` refuse it otherwise.
|
||||
|
||||
|
||||
Loaded 100 of 349 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача