дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 22:54:14 +02:00
Порівняти коміти
63
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c6b8d23159 | ||
|
|
d838df534b | ||
|
|
a9e92d0665 | ||
|
|
fa0be07436 | ||
|
|
fea27f5608 | ||
|
|
a4d172ac83 | ||
|
|
c40d06c702 | ||
|
|
619ae7f727 | ||
|
|
c725b1629d | ||
|
|
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 |
No files matched your search
Створено
+1
-1
@@ -4166,7 +4166,6 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"libsqlite3-sys",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
@@ -4174,6 +4173,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
|
||||
@@ -115,7 +115,6 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
|
||||
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
|
||||
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
|
||||
|
||||
+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">
|
||||
|
||||
@@ -15,10 +15,10 @@ ide-mcp.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-tools = { path = "../ide-tools" }
|
||||
libsqlite3-sys.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -27,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.
|
||||
@@ -124,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -194,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -332,80 +337,6 @@ fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
|
||||
|
||||
impl SqliteDb {
|
||||
fn open_readonly(path: &Path) -> Option<Self> {
|
||||
if !path.is_file() {
|
||||
return None;
|
||||
}
|
||||
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
|
||||
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
|
||||
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
|
||||
let guard = Self(raw);
|
||||
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
|
||||
}
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
|
||||
let c_sql = std::ffi::CString::new(sql).ok()?;
|
||||
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
|
||||
let rc =
|
||||
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
|
||||
let guard = SqliteStmt(stmt);
|
||||
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteDb {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_close(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
|
||||
|
||||
impl SqliteStmt {
|
||||
fn step(&self) -> bool {
|
||||
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
|
||||
}
|
||||
|
||||
fn text(&self, col: std::ffi::c_int) -> Option<String> {
|
||||
unsafe {
|
||||
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
|
||||
if len <= 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::slice::from_raw_parts(ptr, len as usize);
|
||||
std::str::from_utf8(bytes).ok().map(str::to_owned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteStmt {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_finalize(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -462,9 +393,11 @@ fn pick_vscode_chat_title(
|
||||
None
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
/// 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 \
|
||||
@@ -474,40 +407,85 @@ fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
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";
|
||||
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 path in vscode_agent_host_dbs(home) {
|
||||
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
|
||||
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
|
||||
while stmt.step() {
|
||||
let Some(pdata) = stmt.text(0) 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;
|
||||
};
|
||||
let scs_title = stmt.text(1);
|
||||
let scs_source = stmt.text(2);
|
||||
let metadata = stmt.text(3);
|
||||
let payload = stmt.text(4);
|
||||
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);
|
||||
}
|
||||
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.
|
||||
@@ -535,10 +513,15 @@ pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
Some((
|
||||
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
|
||||
cli_user_named,
|
||||
))
|
||||
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() {
|
||||
@@ -653,27 +636,16 @@ mod tests {
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &str) {
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
|
||||
let c_sql = std::ffi::CString::new(sql).unwrap();
|
||||
unsafe {
|
||||
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_open_v2(
|
||||
c_path.as_ptr(),
|
||||
&mut db,
|
||||
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
|
||||
std::ptr::null(),
|
||||
),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
libsqlite3_sys::sqlite3_close(db);
|
||||
}
|
||||
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]
|
||||
@@ -727,6 +699,9 @@ mod tests {
|
||||
&[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();
|
||||
@@ -756,10 +731,13 @@ mod tests {
|
||||
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");
|
||||
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2050,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();
|
||||
@@ -2115,7 +2132,7 @@ impl AgentManager {
|
||||
};
|
||||
TaskFile {
|
||||
task,
|
||||
session_id: Some(session),
|
||||
session_id: session,
|
||||
entries,
|
||||
wanted: s.wanted.clone(),
|
||||
pending_model: None,
|
||||
@@ -2130,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();
|
||||
@@ -4949,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!(
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
|
||||
@@ -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,26 @@ 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);
|
||||
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
|
||||
(!path.contains("${") && Path::new(&path).is_absolute())
|
||||
.then(|| Path::new(&path).components().collect::<PathBuf>())
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1592,6 +1618,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),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -585,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(". ");
|
||||
@@ -1068,6 +1069,26 @@ 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]
|
||||
|
||||
@@ -508,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
|
||||
fn is_native(adapter: &str) -> bool {
|
||||
matches!(adapter, "lldb-dap" | "codelldb")
|
||||
}
|
||||
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
@@ -1638,11 +1643,16 @@ impl DebugManager {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && (!own_terminate || killed) {
|
||||
// A native attach to a program a run started for the debugger (an Xcode app launched
|
||||
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
|
||||
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
|
||||
// simulator then holds its launch (and the next one) forever.
|
||||
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -6,7 +6,7 @@ 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::PathBuf;
|
||||
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";
|
||||
@@ -36,7 +36,7 @@ pub async fn choose(
|
||||
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((major, minor)))),
|
||||
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")?,
|
||||
},
|
||||
@@ -52,11 +52,12 @@ enum Found {
|
||||
Nothing,
|
||||
}
|
||||
|
||||
fn missing(gdb: Option<(u32, u32)>) -> IdeError {
|
||||
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)"
|
||||
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(),
|
||||
};
|
||||
@@ -103,7 +104,6 @@ fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
@@ -187,9 +187,11 @@ mod tests {
|
||||
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 e = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap_err();
|
||||
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)]
|
||||
|
||||
@@ -4019,6 +4019,28 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
|
||||
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
|
||||
#[tokio::test]
|
||||
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
let h = harness(Script::default());
|
||||
let linked = |adapter: &str| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
|
||||
..config()
|
||||
};
|
||||
let id = h.start(linked("lldb-dap")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
|
||||
|
||||
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(linked("debugpy")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
|
||||
+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\
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)]
|
||||
@@ -143,8 +145,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
// 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| {
|
||||
ide_sdk::apply::tool_command(&root, &settings, 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?;
|
||||
@@ -161,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())
|
||||
};
|
||||
@@ -197,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 = ["src", "main", "resources", "lib", "offline.jar"].iter().fold(root.clone(), |p, c| p.join(c));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
|
||||
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
|
||||
</dependency></dependencies></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let model = ide_build::load(&root, &root.join("cache"), None);
|
||||
let jar = jar.to_string_lossy().into_owned();
|
||||
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes", &jar]);
|
||||
|
||||
info.class_paths.pop();
|
||||
info.module_paths.push(jar);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes"]);
|
||||
}
|
||||
|
||||
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
|
||||
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
|
||||
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
|
||||
|
||||
@@ -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,23 @@ 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();
|
||||
let say = on_output.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
// Reading build settings can take a minute on a large workspace: say what's going on.
|
||||
ide_run::xcode::prepare(&dir, &mut config, &|text| {
|
||||
say(OutputChunk::System { text: format!("{text}\n") })
|
||||
})?;
|
||||
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};
|
||||
@@ -14,14 +15,68 @@ use std::process::{Command, Stdio};
|
||||
/// The generators, in order of preference, and their arguments for `container`.
|
||||
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
|
||||
|
||||
fn tool_args(tool: &str, container: &str) -> Vec<String> {
|
||||
fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<String> {
|
||||
if tool == "sourcekit-xcode-bsp" {
|
||||
// Detects the workspace or project in the working directory itself.
|
||||
return vec!["init".into()];
|
||||
}
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
// Without `-scheme` it binds the scheme built last.
|
||||
vec!["config".into(), flag.into(), container.into()]
|
||||
let mut args: Vec<String> = vec!["config".into(), flag.into(), container.into()];
|
||||
if let Some(dir) = build_root {
|
||||
args.extend(["--build_root".into(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
|
||||
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
|
||||
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
|
||||
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
|
||||
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
|
||||
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
let mut cmd = Command::new("xcodebuild");
|
||||
ide_core::process::prepare(&mut cmd)
|
||||
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
|
||||
.current_dir(root)
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let out = cmd.output().ok().filter(|o| o.status.success())?;
|
||||
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// The config `tool` writes at the project root.
|
||||
fn config_name(tool: &str) -> &'static str {
|
||||
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
|
||||
}
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> Option<std::process::Output> {
|
||||
let mut cmd = Command::new("git");
|
||||
ide_core::process::prepare(&mut cmd).arg("-C").arg(root).args(args).stdin(Stdio::null());
|
||||
cmd.output().ok()
|
||||
}
|
||||
|
||||
/// Adds `name` (a file or folder at `root`) to the repository's `info/exclude`, so a generated
|
||||
/// machine-specific config doesn't show up as a change. Nothing when `root` isn't in a Git
|
||||
/// repository or `name` is already tracked or ignored. Returns whether it added the line.
|
||||
fn exclude_from_git(root: &Path, name: &str) -> std::io::Result<bool> {
|
||||
let ok = |args: &[&str]| git(root, args).filter(|o| o.status.success());
|
||||
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_owned();
|
||||
let Some(exclude) = ok(&["rev-parse", "--git-path", "info/exclude"]).map(text) else { return Ok(false) };
|
||||
let prefix = ok(&["rev-parse", "--show-prefix"]).map(text).unwrap_or_default();
|
||||
if ok(&["ls-files", "--error-unmatch", "--", name]).is_some() || ok(&["check-ignore", "-q", "--", name]).is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let exclude = root.join(exclude);
|
||||
if let Some(dir) = exclude.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let before = std::fs::read_to_string(&exclude).unwrap_or_default();
|
||||
let sep = if before.is_empty() || before.ends_with('\n') { "" } else { "\n" };
|
||||
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&exclude)?;
|
||||
std::io::Write::write_all(&mut file, format!("{sep}/{prefix}{name}\n").as_bytes())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// An Xcode project without a BSP config, at the project root.
|
||||
@@ -69,8 +124,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()) {
|
||||
@@ -87,12 +142,17 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{tool} is not installed")))?;
|
||||
let mut cmd = Command::new(exe);
|
||||
ide_core::process::prepare(&mut cmd)
|
||||
.args(tool_args(&tool, &container))
|
||||
// An absolute path: with `--build_root` it is written to the config as given.
|
||||
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
|
||||
.current_dir(&root)
|
||||
.env("PATH", &search)
|
||||
.stdin(Stdio::null());
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
|
||||
if out.status.success() {
|
||||
// Best effort: a config that shows up in `git status` is a nuisance, not a failure.
|
||||
if let Err(e) = exclude_from_git(&root, config_name(&tool)) {
|
||||
tracing::warn!("could not add {} to .git/info/exclude: {e}", config_name(&tool));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
@@ -131,9 +191,95 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn passes_the_container_to_xcode_build_server() {
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace"), ["config", "-workspace", "A.xcworkspace"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj"), ["config", "-project", "A.xcodeproj"]);
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace", None), ["config", "-workspace", "A.xcworkspace"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj", None), ["config", "-project", "A.xcodeproj"]);
|
||||
let dd = Path::new("/Users/me/Library/Developer/Xcode/DerivedData/A-abc");
|
||||
assert_eq!(
|
||||
tool_args("xcode-build-server", "A.xcworkspace", Some(dd)),
|
||||
[
|
||||
"config",
|
||||
"-workspace",
|
||||
"A.xcworkspace",
|
||||
"--build_root",
|
||||
"/Users/me/Library/Developer/Xcode/DerivedData/A-abc"
|
||||
]
|
||||
);
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj", Some(dd)), ["init"]);
|
||||
}
|
||||
|
||||
fn git_in(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git").arg("-C").arg(dir).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn exclude_file(repo: &Path) -> String {
|
||||
std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_generated_config_from_git_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("\n/buildServer.json\n"), "{}", exclude_file(repo));
|
||||
// Now ignored: not added twice.
|
||||
assert!(!exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(repo).matches("buildServer.json").count(), 1);
|
||||
// sourcekit-xcode-bsp's folder.
|
||||
std::fs::create_dir(repo.join(".bsp")).unwrap();
|
||||
std::fs::write(repo.join(".bsp/x.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, config_name("sourcekit-xcode-bsp")).unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/buildServer.json\n/.bsp\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_tracked_and_ignored_configs_and_non_repos_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Not a Git repository: nothing to do, no `.git` created.
|
||||
let plain = tmp.path().join("plain");
|
||||
std::fs::create_dir(&plain).unwrap();
|
||||
assert!(!exclude_from_git(&plain, "buildServer.json").unwrap());
|
||||
assert!(!plain.join(".git").exists());
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git_in(&repo, &["init", "-q"]);
|
||||
let before = exclude_file(&repo);
|
||||
// Tracked: the team shares it.
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
git_in(&repo, &["add", "buildServer.json"]);
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
// Already in .gitignore.
|
||||
git_in(&repo, &["rm", "-q", "--cached", "buildServer.json"]);
|
||||
std::fs::write(repo.join(".gitignore"), "buildServer.json\n").unwrap();
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(&repo), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_config_of_a_project_in_a_subfolder_of_the_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
let ios = repo.join("apps/ios");
|
||||
std::fs::create_dir_all(&ios).unwrap();
|
||||
assert!(exclude_from_git(&ios, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/apps/ios/buildServer.json\n"));
|
||||
std::fs::write(ios.join("buildServer.json"), "{}").unwrap();
|
||||
// The line matches the file in the subfolder only.
|
||||
git_in(&ios, &["check-ignore", "-q", "buildServer.json"]);
|
||||
assert!(
|
||||
Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(["check-ignore", "-q", "buildServer.json"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.code()
|
||||
== Some(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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,
|
||||
@@ -1230,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>> {
|
||||
@@ -1247,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).
|
||||
@@ -1348,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))
|
||||
}
|
||||
|
||||
@@ -1365,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))
|
||||
}
|
||||
|
||||
@@ -1376,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.
|
||||
@@ -1416,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
|
||||
}
|
||||
@@ -1657,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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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 [
|
||||
|
||||
@@ -5770,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");
|
||||
@@ -5779,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()
|
||||
@@ -5797,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")]
|
||||
|
||||
@@ -881,14 +881,9 @@ async fn the_bridge_picks_the_server_again_when_the_servers_change() {
|
||||
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"));
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||||
let fixed = ServerOptions { port: Some(port), ..Default::default() };
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let start_b = |registry: WithBackground| {
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.clone()), &runtime, fixed.clone()).unwrap()
|
||||
};
|
||||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||||
let server_b = start_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
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;
|
||||
@@ -896,8 +891,23 @@ async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
|
||||
server_b.stop();
|
||||
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
|
||||
assert_eq!(server_b.port(), port);
|
||||
// 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;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct XcodeScheme {
|
||||
@@ -47,22 +48,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 +267,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 +282,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)
|
||||
}
|
||||
|
||||
@@ -343,7 +354,11 @@ fn sh_quote(s: &str) -> String {
|
||||
/// The script a run executes: build, boot the simulator and show it (Xcode 27 replaced the
|
||||
/// Simulator app with DeviceHub), install, then launch with the app's output on the console.
|
||||
/// The app's arguments follow the script as `$@`. `simctl` passes SIGTERM on to the app but not
|
||||
/// the SIGINT a Stop sends, so the script turns that into a SIGTERM. With `wait_for_debugger` the
|
||||
/// the SIGINT a Stop sends, so the script turns that into a SIGTERM. A SIGTERM the app never acts
|
||||
/// on (a debugger held it) would leave `simctl` waiting for it forever, and the simulator would
|
||||
/// keep the next launch or test waiting too: after 3 s the app is terminated through the
|
||||
/// simulator (in the background: that waits too while a debugger holds the app), and after 5 s
|
||||
/// `simctl` is killed. With `wait_for_debugger` the
|
||||
/// app stays suspended until a debugger attaches; the script prints `<bundle id>: <pid>` for it
|
||||
/// (simctl prints that line too, but holds it back until it exits when its output is a pipe).
|
||||
pub fn launch_script(
|
||||
@@ -364,10 +379,18 @@ pub fn launch_script(
|
||||
set +e\n\
|
||||
xcrun simctl launch --console-pty --terminate-running-process{wait} {udid} {bundle_id} \"$@\" &\n\
|
||||
launch=$!\n\
|
||||
trap 'kill -TERM $launch 2>/dev/null' INT TERM\n\
|
||||
trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\
|
||||
{announce}\
|
||||
wait $launch; status=$?\n\
|
||||
while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\
|
||||
tries=0\n\
|
||||
while kill -0 $launch 2>/dev/null; do\n\
|
||||
if [ -z \"$stopped\" ]; then wait $launch; status=$?; continue; fi\n\
|
||||
tries=$((tries + 1))\n\
|
||||
if [ $tries -eq 15 ]; then xcrun simctl terminate {udid} {bundle_id} >/dev/null 2>&1 & fi\n\
|
||||
if [ $tries -ge 25 ]; then kill -KILL $launch 2>/dev/null; fi\n\
|
||||
sleep 0.2\n\
|
||||
done\n\
|
||||
if [ -n \"$stopped\" ]; then wait $launch 2>/dev/null; s=$?; [ $s -eq 127 ] || status=$s; fi\n\
|
||||
exit $status\n",
|
||||
build.join(" "),
|
||||
wait = if wait_for_debugger { " --wait-for-debugger" } else { "" },
|
||||
@@ -455,42 +478,147 @@ fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
/// Reports a step of [`prepare`] to the run's console while no process is running yet.
|
||||
pub type Progress<'a> = &'a dyn Fn(&str);
|
||||
|
||||
/// Build settings read by [`build_settings`], by working directory and `xcodebuild` arguments,
|
||||
/// with the [`project_stamp`] they were read at.
|
||||
type SettingsCache = HashMap<(PathBuf, Vec<String>), (u64, String)>;
|
||||
static SETTINGS: LazyLock<Mutex<SettingsCache>> = LazyLock::new(Default::default);
|
||||
|
||||
/// `read()` (the settings for `key`), or what it returned before while the project's `stamp` is
|
||||
/// unchanged. Failures are not kept.
|
||||
fn cached_settings(
|
||||
key: (PathBuf, Vec<String>),
|
||||
stamp: u64,
|
||||
read: impl FnOnce() -> IdeResult<String>,
|
||||
) -> IdeResult<String> {
|
||||
if let Some((at, settings)) = SETTINGS.lock().unwrap_or_else(|e| e.into_inner()).get(&key)
|
||||
&& *at == stamp
|
||||
{
|
||||
return Ok(settings.clone());
|
||||
}
|
||||
let settings = read()?;
|
||||
SETTINGS.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (stamp, settings.clone()));
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
/// Folders [`project_stamp`] doesn't look into: dependencies and build output.
|
||||
const UNSTAMPED_DIRS: [&str; 7] =
|
||||
["SourcePackages", "Pods", "Carthage", "DerivedData", "build", "node_modules", "Tuist"];
|
||||
|
||||
/// A hash of the paths and modification times of the files in `dir` that decide build settings:
|
||||
/// `project.pbxproj`, `contents.xcworkspacedata`, `*.xcscheme`, `*.xcconfig` and
|
||||
/// `Package.resolved`, four levels deep, outside hidden and [`UNSTAMPED_DIRS`] folders. A change
|
||||
/// there (Tuist or XcodeGen regenerating the project, an edited xcconfig) reads the settings again.
|
||||
/// An xcconfig deeper than that, or an `#include` from outside `dir`, is missed until the IDE restarts.
|
||||
pub fn project_stamp(dir: &Path) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
fn walk(dir: &Path, depth: u32, hasher: &mut std::collections::hash_map::DefaultHasher) {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
if meta.is_dir() {
|
||||
if depth > 1 && !name.starts_with('.') && !UNSTAMPED_DIRS.contains(&name.as_ref()) {
|
||||
walk(&entry.path(), depth - 1, hasher);
|
||||
}
|
||||
} else if name == "project.pbxproj"
|
||||
|| name == "contents.xcworkspacedata"
|
||||
|| name == "Package.resolved"
|
||||
|| name.ends_with(".xcscheme")
|
||||
|| name.ends_with(".xcconfig")
|
||||
{
|
||||
entry.path().hash(hasher);
|
||||
meta.modified().ok().hash(hasher);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
// `App.xcodeproj/xcshareddata/xcschemes/App.xcscheme` is four levels below `dir`.
|
||||
walk(dir, 4, &mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// `xcodebuild -showBuildSettings -json` of `params` for `destination`, read once while the
|
||||
/// project's files are unchanged ([`project_stamp`]): a large workspace takes 10 s or more for it.
|
||||
fn build_settings(
|
||||
dir: &Path,
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: Option<&str>,
|
||||
progress: Progress,
|
||||
) -> IdeResult<String> {
|
||||
let args = [
|
||||
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
|
||||
build_args(params, destination).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());
|
||||
cached_settings((dir.to_path_buf(), args.clone()), project_stamp(dir), || {
|
||||
let scheme = params.get("scheme").map_or("", |s| s.trim());
|
||||
progress(&format!("Reading the build settings of scheme {scheme}…"));
|
||||
let started = std::time::Instant::now();
|
||||
let settings = output(dir, "xcodebuild", &args)?;
|
||||
progress(&format!("Read the build settings in {:.1} s", started.elapsed().as_secs_f64()));
|
||||
Ok(settings)
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a run of `params` builds and the build settings for it: [`MAC_DESTINATION`] when the
|
||||
/// scheme's app runs on the Mac ([`runs_on_mac`]), else `id=<udid>` of the configured simulator
|
||||
/// or device, or the default simulator. A Clean Build Folder of the configuration uses the same
|
||||
/// destination. The settings are read once for the simulator or device, which also tells whether
|
||||
/// the app runs on the Mac instead; only a Mac app, or a scheme without that destination, reads
|
||||
/// them again.
|
||||
fn run_target(dir: &Path, params: &BTreeMap<String, String>, progress: Progress) -> IdeResult<(String, String)> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
let configured = Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC).map(str::to_owned);
|
||||
let udid = configured.or_else(|| if simulator.trim() == MAC { None } else { default_simulator(dir) });
|
||||
if let Some(udid) = &udid {
|
||||
let device = format!("id={udid}");
|
||||
if let Ok(settings) = build_settings(dir, params, Some(&device), progress)
|
||||
&& !runs_on_mac(&settings, simulator).map_err(IdeError::invalid)?
|
||||
{
|
||||
return Ok((device, settings));
|
||||
}
|
||||
}
|
||||
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator(dir).ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
Ok(format!("id={udid}"))
|
||||
if runs_on_mac(&build_settings(dir, params, None, progress)?, simulator).map_err(IdeError::invalid)? {
|
||||
return Ok((MAC_DESTINATION.to_owned(), build_settings(dir, params, Some(MAC_DESTINATION), progress)?));
|
||||
}
|
||||
let udid = udid
|
||||
.or_else(|| default_simulator(dir))
|
||||
.ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?;
|
||||
let device = format!("id={udid}");
|
||||
Ok((device.clone(), build_settings(dir, params, Some(&device), progress)?))
|
||||
}
|
||||
|
||||
/// Where a run of `params` builds ([`run_target`]).
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<String> {
|
||||
Ok(run_target(dir, params, &|_| {})?.0)
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
/// The steps that take a while before the process starts go to `progress`.
|
||||
pub fn prepare(dir: &Path, config: &mut crate::RunConfig, progress: Progress) -> 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)?;
|
||||
// A physical device that can't take the app says so before the build settings are read.
|
||||
let configured = params.get(SIMULATOR_PARAM).map(|s| s.trim()).filter(|s| !s.is_empty() && *s != MAC);
|
||||
let devices = crate::simulator::devices(dir);
|
||||
if let Some(reason) = configured.and_then(|u| devices.iter().find(|d| d.udid == u)).and_then(device_unready) {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let (destination, settings) = run_target(dir, params, progress)?;
|
||||
if destination == MAC_DESTINATION {
|
||||
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
|
||||
let args = build_args(params, Some(MAC_DESTINATION)).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&settings).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), mac_launch_script(&args, &executable), "xcode-run".to_owned()]
|
||||
@@ -502,12 +630,8 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I
|
||||
return Ok(());
|
||||
}
|
||||
let udid = destination.trim_start_matches("id=").to_owned();
|
||||
let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid);
|
||||
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 settings = show(&args)?;
|
||||
let device = devices.into_iter().find(|d| d.udid == udid);
|
||||
let args = build_args(params, Some(&destination)).map_err(IdeError::invalid)?;
|
||||
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));
|
||||
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
@@ -654,6 +778,56 @@ mod tests {
|
||||
assert_eq!(config.args[3..], ["-resultBundlePath", "/cov/r.xcresult"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_settings_are_read_again_only_when_the_project_changes() {
|
||||
let key = |n: &str| (PathBuf::from("/settings-cache-test"), vec![n.to_owned()]);
|
||||
let reads = std::cell::Cell::new(0);
|
||||
let read = || {
|
||||
reads.set(reads.get() + 1);
|
||||
Ok(format!("settings {}", reads.get()))
|
||||
};
|
||||
assert_eq!(cached_settings(key("a"), 1, read).unwrap(), "settings 1");
|
||||
assert_eq!(cached_settings(key("a"), 1, read).unwrap(), "settings 1");
|
||||
assert_eq!(reads.get(), 1);
|
||||
// Other arguments (scheme, destination) are read on their own.
|
||||
assert_eq!(cached_settings(key("b"), 1, read).unwrap(), "settings 2");
|
||||
// The project changed.
|
||||
assert_eq!(cached_settings(key("a"), 2, read).unwrap(), "settings 3");
|
||||
// A failed read is not kept.
|
||||
assert!(cached_settings(key("c"), 1, || Err(IdeError::invalid("no"))).is_err());
|
||||
assert_eq!(cached_settings(key("c"), 1, read).unwrap(), "settings 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_project_stamp_follows_the_files_that_decide_build_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let schemes = root.join("App.xcodeproj/xcshareddata/xcschemes");
|
||||
fs::create_dir_all(&schemes).unwrap();
|
||||
fs::write(root.join("App.xcodeproj/project.pbxproj"), "a").unwrap();
|
||||
let first = project_stamp(root);
|
||||
assert_eq!(project_stamp(root), first);
|
||||
// Sources and dependencies don't count.
|
||||
fs::create_dir_all(root.join("Sources")).unwrap();
|
||||
fs::write(root.join("Sources/App.swift"), "let a = 1").unwrap();
|
||||
fs::create_dir_all(root.join("SourcePackages/checkouts/Lib/Lib.xcodeproj")).unwrap();
|
||||
fs::write(root.join("SourcePackages/checkouts/Lib/Lib.xcodeproj/project.pbxproj"), "x").unwrap();
|
||||
fs::create_dir_all(root.join(".build")).unwrap();
|
||||
fs::write(root.join(".build/Base.xcconfig"), "x").unwrap();
|
||||
assert_eq!(project_stamp(root), first);
|
||||
// A new shared scheme, an xcconfig, and a regenerated project do.
|
||||
fs::write(schemes.join("App.xcscheme"), "<Scheme/>").unwrap();
|
||||
let with_scheme = project_stamp(root);
|
||||
assert_ne!(with_scheme, first);
|
||||
fs::create_dir_all(root.join("Configs")).unwrap();
|
||||
fs::write(root.join("Configs/Debug.xcconfig"), "A = 1").unwrap();
|
||||
let with_config = project_stamp(root);
|
||||
assert_ne!(with_config, with_scheme);
|
||||
let pbxproj = fs::File::options().write(true).open(root.join("App.xcodeproj/project.pbxproj")).unwrap();
|
||||
pbxproj.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(5)).unwrap();
|
||||
assert_ne!(project_stamp(root), with_config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_without_xcode_projects_has_no_schemes() {
|
||||
assert!(schemes(&fixtures().join("App.xcodeproj")).is_empty());
|
||||
@@ -666,30 +840,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 +952,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
|
||||
@@ -904,6 +1056,56 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A Stop whose SIGTERM `simctl launch` never acts on (the app was held by a debugger) still
|
||||
/// ends the run: the app is terminated through the simulator and `simctl` is killed.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_stop_ends_a_launch_that_ignores_sigterm() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::os::unix::process::CommandExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |tool: &str, then: &str| {
|
||||
let path = dir.path().join(tool);
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(&path, body).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub("xcodebuild", "");
|
||||
stub("open", "");
|
||||
stub("xcrun", "[ \"$2\" = launch ] || exit 0\ntrap '' TERM\nwhile :; do sleep 0.05; done\n");
|
||||
let script = launch_script(&[], "U1", Path::new("/dd/A.app"), "dev.example.App", false);
|
||||
let mut child = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &script, "xcode-run"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]");
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !launched() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
let stopped = std::time::Instant::now();
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
let deadline = stopped + std::time::Duration::from_secs(15);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
// The stub `simctl` ignores SIGTERM: take its whole group down with the script.
|
||||
unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL) };
|
||||
let _ = child.wait();
|
||||
panic!("the run never ended after Stop");
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
assert!(stopped.elapsed() < std::time::Duration::from_secs(8), "ended after {:?}", stopped.elapsed());
|
||||
assert!(fs::read_to_string(&log).unwrap().ends_with("xcrun [simctl] [terminate] [U1] [dev.example.App]\n"));
|
||||
}
|
||||
|
||||
/// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT
|
||||
/// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,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 | — |
|
||||
|
||||
@@ -95,7 +95,7 @@ The same page lists the installed packages of the selected interpreter. You can
|
||||
|
||||
The **Python Packages** tool window (**View | Tool Windows**, or Find Action) manages the same packages next to the code. It lists what is installed and marks what can be upgraded. Type in its search field to filter the list; PyPI projects whose names contain the text and that are not installed appear under **PyPI**, the exact name first, then names that start with the text. Select a package to see its summary and its versions, then **Install** it (the newest release that fits the interpreter, or a version you pick), **Upgrade** or **Uninstall** it. The window manages the interpreter that runs use for the active file (in a workspace, its member's virtualenv) and shows its path. PyPI has no search API, so the search runs on a copy of PyPI's list of project names: the first search downloads it (about 10 MB) into the IDE's cache, and a search a day later refreshes it; searching the copy sends nothing. Until it is there, or when it cannot be downloaded, a project is still found by its exact name. Only pypi.org is searched, not a private index configured for pip, although installing does use pip's configuration. The exact-name lookup sends what you type to pypi.org; the name of an installed package is sent only when you click **Show PyPI Details**. When pip or uv is configured to install from another index, the exact-name lookup and the search results wait until you click **Search PyPI for …**, since a private package may have a public namesake.
|
||||
|
||||
When it has a package's details from PyPI, the pane also lists the project's links (its PyPI page, homepage, documentation, source, …) and its description from PyPI: rendered when it is Markdown, as plain text otherwise. Links open in the browser.
|
||||
When it has a package's details from PyPI, the pane also lists the project's links (its PyPI page, homepage, documentation, source, …) and its description from PyPI: rendered when it is Markdown, as plain text otherwise. Links open in the browser. Images in the description (badges, screenshots) come from other sites such as GitHub, so they load, and those sites see the request, only when you click **Load Images**.
|
||||
|
||||
The **+** button in its toolbar installs a package from elsewhere: **Install from Version Control…** takes a repository URL (`git+https://…`; a plain `https://`, `ssh://` or `git@host:path` URL is installed with Git), **Install from Disk…** a project directory or a wheel or source archive; a relative path is relative to the project, and a name alone is a folder, never a PyPI package. With **Install as editable (-e)**, a project directory is installed in editable mode, so changes to its sources apply without reinstalling. Only a local directory can be editable: to edit a repository's code, clone it and install the clone from disk.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -80,4 +80,4 @@ If a `settings.toml` you edited by hand can't be parsed or has a value of the wr
|
||||
2. Click **Report an Issue** (or go to [GitHub issues](https://github.com/l0ng-ai/openidea/issues/new/choose)) and describe the steps to reproduce.
|
||||
3. Attach the relevant part of the log.
|
||||
|
||||
Questions and feedback are also welcome on [Discord](https://discord.gg/2Zy4yn7gP).
|
||||
Questions and feedback are also welcome on [Discord](https://discord.gg/AsZqMgxZm).
|
||||
@@ -79,26 +79,27 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
|
||||
|
||||
**设置 › 工具 › 终端**:
|
||||
|
||||
| 设置 | 默认值 | 说明 |
|
||||
| ------------------------------ | ---------- | ----------------------------------------------------------------------------- |
|
||||
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
|
||||
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
|
||||
| **Shell 路径** | 登录 Shell | 一条命令行,例如 `/bin/zsh --login`。**已安装的 Shell** 列出找到的 Shell。 |
|
||||
| **默认标签页名称** | `Local` | |
|
||||
| **响铃** | 开 | |
|
||||
| **会话结束时关闭** | 开 | |
|
||||
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
|
||||
| **选择时复制到剪贴板** | 关 | |
|
||||
| **点击鼠标中键时粘贴** | 开 | |
|
||||
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
|
||||
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
|
||||
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
|
||||
| **Shell 集成** | 开 | |
|
||||
| **高亮超链接** | 开 | |
|
||||
| **将 Option 用作 Meta 键** | 关 | 仅 macOS。 |
|
||||
| **光标形状** | 块 | 块、下划线或竖线。 |
|
||||
| **闪烁光标** | 开 | |
|
||||
| **使用编辑器字体** | 开 | 关闭后可设置 **字体**、**大小**(6–72)、**行高**、**备用字体** 和 **列宽**。 |
|
||||
| 设置 | 默认值 | 说明 |
|
||||
| ---------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
|
||||
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
|
||||
| **Shell 路径** | 登录 Shell | 一条命令行,例如 `/bin/zsh --login`。**已安装的 Shell** 列出找到的 Shell。 |
|
||||
| **默认标签页名称** | `Local` | |
|
||||
| **响铃** | 开 | |
|
||||
| **会话结束时关闭** | 开 | |
|
||||
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
|
||||
| **选择时复制到剪贴板** | 关 | |
|
||||
| **允许程序复制到剪贴板(OSC 52)** | 开 | tmux(`set-clipboard on`)、Neovim 等程序可以设置剪贴板,SSH 中也有效。程序无法读取剪贴板;超过 1 MiB 的内容会被忽略。 |
|
||||
| **点击鼠标中键时粘贴** | 开 | |
|
||||
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
|
||||
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
|
||||
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
|
||||
| **Shell 集成** | 开 | |
|
||||
| **高亮超链接** | 开 | |
|
||||
| **将 Option 用作 Meta 键** | 关 | 仅 macOS。 |
|
||||
| **光标形状** | 块 | 块、下划线或竖线。 |
|
||||
| **闪烁光标** | 开 | |
|
||||
| **使用编辑器字体** | 开 | 关闭后可设置 **字体**、**大小**(6–72)、**行高**、**备用字体** 和 **列宽**。 |
|
||||
|
||||
修改会立即应用到已打开的会话。配色跟随 IDE 主题。
|
||||
|
||||
|
||||
@@ -276,7 +276,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **提交** | 非模态提交界面、提交后清空消息、提交消息检查(主题与正文之间空行、主题和正文长度、右边距)、默认提交检查。 |
|
||||
| **确认** | 新建或删除文件时的处理方式、**更新前显示选项**、丢弃提交前确认、在项目视图中高亮包含修改的目录、历史记录行数上限。 |
|
||||
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。 |
|
||||
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。无法访问的已映射仓库会被标记为不可用,其余仓库仍可继续使用。 |
|
||||
| **问题导航** | 把提交消息中的问题编号变成链接的正则规则(内置 JIRA、YouTrack 和 GitHub 预设)。 |
|
||||
| **日志** | 引用和时间的显示方式、显示哪些列。 |
|
||||
| **搁置** | 应用后从搁置中移除文件。 |
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
---
|
||||
title: "C# 与 .NET"
|
||||
description: "使用 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
|
||||
description: "使用 Roslyn 语言服务器或 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
|
||||
---
|
||||
|
||||
OpenIDEA 通过 [csharp-ls](https://github.com/razzmatazz/csharp-language-server) 支持 C#(`.cs`、`.csx`),通过 [FsAutoComplete](https://github.com/ionide/FsAutoComplete) 支持 F#(`.fs`、`.fsi`、`.fsx`)。两者都以 .NET 工具的形式安装,调试都使用 [netcoredbg](https://github.com/Samsung/netcoredbg)。构建、NuGet 包和测试统一走 `dotnet` 命令行。其他语言见[语言支持总览](/zh/languages/index)。
|
||||
OpenIDEA 通过微软的 [Roslyn 语言服务器](https://github.com/dotnet/roslyn)或 [csharp-ls](https://github.com/razzmatazz/csharp-language-server) 支持 C#(`.cs`、`.csx`),通过 [FsAutoComplete](https://github.com/ionide/FsAutoComplete) 支持 F#(`.fs`、`.fsi`、`.fsx`)。它们都以 .NET 工具的形式安装,两种语言的调试都使用 [netcoredbg](https://github.com/Samsung/netcoredbg)。构建、NuGet 包和测试统一走 `dotnet` 命令行。其他语言见[语言支持总览](/zh/languages/index)。
|
||||
|
||||
## 语言服务器
|
||||
|
||||
| 语言 | 服务器 | 工作区根目录标记 |
|
||||
| ---- | -------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` |
|
||||
| 语言 | 服务器 | 工作区根目录标记 |
|
||||
| ---- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | roslyn-language-server 或 csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` |
|
||||
|
||||
C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 VS Code C# 扩展使用的服务器,需要 .NET 10 或更新的 SDK;csharp-ls 在较旧的 SDK 上也能运行。用 Roslyn 时,补全还会列出当前文件尚未导入的命名空间里的类型(附带命名空间),选中后自动加上 `using` 指令。Roslyn 以 `--autoLoadProjects` 启动,会自己找到并打开解决方案或项目。在 macOS 和 Linux 上它只加载 SDK 风格的项目:.NET Framework 项目需要 Mono MSBuild,它不使用。Unity 的 Visual Studio Editor 包生成的就是 SDK 风格的 `.csproj`。
|
||||
|
||||
语言服务器会加载根据这些标记找到的解决方案或项目。FsAutoComplete 启动时开启了 `AutomaticWorkspaceInit`,无需等待编辑器请求就会自动加载项目。
|
||||
|
||||
跳转到类库类型的定义时,csharp-ls 返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
|
||||
跳转到类库类型的定义时,语言服务器返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
|
||||
|
||||
`ProjectSettings/ProjectVersion.txt` 这个标记是为 Unity 项目准备的。把 OpenIDEA 设为 Unity 外部编辑器的方法见 [Unity](/zh/languages/unity)。
|
||||
|
||||
@@ -22,17 +24,18 @@ OpenIDEA 通过 [csharp-ls](https://github.com/razzmatazz/csharp-language-server
|
||||
|
||||
需要安装 [.NET SDK](https://dotnet.microsoft.com/download),并确保 `dotnet` 在 `PATH` 上。IDE 的构建、测试和包管理命令都通过它执行,语言服务器也用它安装。
|
||||
|
||||
缺少语言服务器时,打开 C# 或 F# 文件会弹出“csharp-ls 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
|
||||
没有安装语言服务器时,打开 C# 或 F# 文件会弹出“Roslyn (C#) 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。SDK 低于 .NET 10 时,安装会说明这一点并建议改装 csharp-ls。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
|
||||
|
||||
| 工具 | 安装方式 |
|
||||
| -------------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` 安装到 IDE 自己的工具目录;nuget.org 上只有它的预发布版本 |
|
||||
| csharp-ls | `dotnet tool install --tool-path` 安装到 IDE 自己的工具目录(不是全局工具) |
|
||||
| FsAutoComplete | `dotnet tool install --tool-path` 安装到 IDE 自己的工具目录 |
|
||||
| netcoredbg | 从 `Samsung/netcoredbg` 的 GitHub Release 下载。提供 macOS arm64、Linux x64 与 arm64、Windows x64 的预编译包。 |
|
||||
|
||||
安装 csharp-ls 或 FsAutoComplete 之前,IDE 会把 `dotnet --list-sdks` 中最新的 SDK 与该工具在 nuget.org 上最新版本的目标 .NET 版本进行比较。如果 SDK 较旧,会安装能在它上面运行的最新版本,或者提示需要安装哪个 SDK。
|
||||
|
||||
`PATH` 上已有的 `csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
|
||||
`PATH` 上已有的 `roslyn-language-server`、`csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
|
||||
|
||||
## .NET 工具窗口
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| `go install` | gopls、Delve、sqls。需要 Go。 |
|
||||
| `rustup component add` | rust-analyzer(不可用时改为从 Open VSX 下载)。 |
|
||||
| `gem install` | Solargraph 装到独立的 gem 目录;Ruby LSP 装到项目使用的 Ruby 中。 |
|
||||
| `dotnet tool install` | csharp-ls、FsAutoComplete。需要 .NET SDK。 |
|
||||
| `dotnet tool install` | Roslyn(C#)、csharp-ls、FsAutoComplete。需要 .NET SDK。 |
|
||||
| 下载发布包 | clangd、CodeLLDB、vscode-js-debug、JDT LS、java-debug、Kotlin LSP、Lua、Marksman、Taplo、ZLS、terraform-ls 等,来源包括 GitHub、Open VSX、Maven Central、Eclipse 下载站和 HashiCorp。 |
|
||||
| 内置 | JDT LS 使用的 Lombok agent 随应用一起提供。 |
|
||||
|
||||
@@ -94,7 +94,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — |
|
||||
| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** |
|
||||
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
|
||||
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — |
|
||||
| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — |
|
||||
|
||||
@@ -95,7 +95,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
|
||||
**Python 软件包** 工具窗口(**视图 | 工具窗口**,或通过查找操作打开)可以在代码旁边管理同一批软件包。它会列出已安装的软件包并标出可升级的。在搜索框中输入文本可筛选列表;名称包含该文本且尚未安装的 PyPI 项目会显示在 **PyPI** 分组下,名称完全相同的排在最前,其次是以该文本开头的名称。选中软件包可查看摘要和版本,然后 **安装**(适合该解释器的最新版本,或您选择的版本)、**升级** 或 **卸载**。该窗口管理的是运行当前文件时使用的解释器(在工作区中为其所属成员的虚拟环境),并显示其路径。PyPI 没有搜索接口,因此搜索在 PyPI 项目名称列表的本地副本上进行:第一次搜索时会把它下载到 IDE 的缓存中(约 10 MB),一天之后的搜索会刷新它;在本地副本中搜索不会发送任何内容。在列表下载完成之前,或者无法下载时,仍然可以按精确名称找到项目。只搜索 pypi.org,不会查询为 pip 配置的私有索引,但安装时仍使用 pip 的配置。按精确名称查询时,输入的文本会发送到 pypi.org;已安装软件包的名称只有在点击 **显示 PyPI 详情** 时才会发送。如果 pip 或 uv 配置了从其他索引安装,按精确名称查询和搜索结果都要等到点击 **在 PyPI 中搜索 …** 之后才会出现,因为私有软件包可能在 PyPI 上有同名的公开项目。
|
||||
|
||||
取得 PyPI 上的软件包信息后,详情面板还会列出项目链接(PyPI 页面、主页、文档、源码等)和 PyPI 上的项目说明:Markdown 格式会渲染显示,其他格式按纯文本显示。链接在浏览器中打开。
|
||||
取得 PyPI 上的软件包信息后,详情面板还会列出项目链接(PyPI 页面、主页、文档、源码等)和 PyPI 上的项目说明:Markdown 格式会渲染显示,其他格式按纯文本显示。链接在浏览器中打开。说明中的图片(徽章、截图等)来自 GitHub 等其他网站,只有点击 **加载图片** 后才会加载,这些网站也只有这时才会收到请求。
|
||||
|
||||
工具栏中的 **+** 按钮可以从其他来源安装软件包:**从版本控制安装…** 接受仓库 URL(`git+https://…`;普通的 `https://`、`ssh://` 或 `git@host:path` URL 会按 Git 安装),**从磁盘安装…** 接受项目目录或 wheel、源码归档文件;相对路径相对于项目,只写一个名称时也按文件夹处理,不会当作 PyPI 软件包。勾选 **以可编辑模式安装 (-e)** 后,项目目录以可编辑模式安装,修改源码后无需重新安装即可生效。只有本地目录可以以可编辑模式安装:要修改仓库中的代码,请先克隆仓库,再从磁盘安装克隆的目录。
|
||||
|
||||
|
||||
@@ -76,9 +76,9 @@ description: "把 OpenIDEA 设为 Unity 的外部脚本编辑器,浏览 Unity
|
||||
|
||||
## 代码智能
|
||||
|
||||
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器 csharp-ls,安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
|
||||
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器(Roslyn 或 csharp-ls),安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
|
||||
|
||||
csharp-ls 读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
|
||||
语言服务器读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
|
||||
|
||||
> 缺少 C# 项目文件。请在 Unity 的偏好设置 > 外部工具中选择外部脚本编辑器,然后重新生成项目文件。
|
||||
|
||||
|
||||
@@ -80,4 +80,4 @@ WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
2. 点击 **报告问题**(或直接前往 [GitHub Issues](https://github.com/l0ng-ai/openidea/issues/new/choose)),写明复现步骤。
|
||||
3. 附上日志中相关的部分。
|
||||
|
||||
也欢迎在 [Discord](https://discord.gg/2Zy4yn7gP) 提问和反馈;README 中还有微信群二维码。
|
||||
也欢迎在 [Discord](https://discord.gg/AsZqMgxZm) 提问和反馈;README 中还有微信群二维码。
|
||||
@@ -1,5 +1,7 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import type * as AgentStore from "../src/features/agents/store";
|
||||
import type * as Ipc from "../src/platform/ipc";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "long-chat",
|
||||
@@ -254,3 +256,141 @@ test("paints earlier turns past folded process runs longer than ENTRY_BATCH", as
|
||||
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
|
||||
await expect(stream.getByText("Interim status update")).toBeVisible();
|
||||
});
|
||||
|
||||
test("keeps earlier messages visible and upward wheel scrolling working after a tall row collapses", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 980, height: 640 });
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const themePath = "/src/workbench/theme.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store: typeof AgentStore = await import(storePath);
|
||||
const { previewTheme } = await import(themePath);
|
||||
const { commands }: typeof Ipc = await import(ipcPath);
|
||||
previewTheme("light");
|
||||
const taskId = "collapse-scroll";
|
||||
commands.agentRespond = async (_id: string, permId: number, _answer: string | null) => {
|
||||
const current = store.useAgents.getState().entries.get(taskId) ?? [];
|
||||
store.useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
taskId,
|
||||
[
|
||||
...current.map((entry) =>
|
||||
entry.type === "permission" && entry.id === permId
|
||||
? { ...entry, chosen: "Layered architecture diagram" }
|
||||
: entry,
|
||||
),
|
||||
{ type: "thought", text: "Planning the layered architecture diagram…", startedMs: Date.now() },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
return { status: "ok", data: null };
|
||||
};
|
||||
const priorTurns: AgentEntry[] = Array.from({ length: 8 }, (_, turn): AgentEntry[] => [
|
||||
{ type: "user", text: `Earlier request ${turn}`, attachments: [], steered: false },
|
||||
{ type: "agent", text: `Earlier reply ${turn} with context from the repository.` },
|
||||
]).flat();
|
||||
const history: AgentEntry[] = [
|
||||
...priorTurns,
|
||||
{
|
||||
type: "user",
|
||||
text: "Can you review the architecture design and convert Section 2.1 into a diagram?",
|
||||
attachments: ["architecture_design.md"],
|
||||
sentMs: Date.now() - 180_000,
|
||||
steered: false,
|
||||
},
|
||||
{
|
||||
type: "agent",
|
||||
text: "I reviewed `architecture_design.md` against the codebase. Before generating the diagram, please confirm the layout preferences below.",
|
||||
},
|
||||
{
|
||||
type: "permission",
|
||||
id: 1,
|
||||
title: "Choose diagram options",
|
||||
command: null,
|
||||
options: [
|
||||
{ id: "submit", name: "Submit", kind: "allow_once" },
|
||||
{ id: "cancel", name: "Cancel", kind: "reject_once" },
|
||||
],
|
||||
questions: [
|
||||
{
|
||||
header: "Style",
|
||||
question: "Which visual style should Section 2.1 use?",
|
||||
multiSelect: false,
|
||||
options: Array.from({ length: 8 }, (_, i) => ({
|
||||
label: i === 0 ? "Layered architecture diagram (Recommended)" : `Alternative layout style ${i + 1}`,
|
||||
description:
|
||||
"Horizontal pipeline tiers with a dedicated right-hand artifact rail so connectors never cross.",
|
||||
preview: null,
|
||||
})),
|
||||
},
|
||||
],
|
||||
chosen: null,
|
||||
},
|
||||
];
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([
|
||||
[
|
||||
taskId,
|
||||
{
|
||||
id: taskId,
|
||||
title: "Can you review the architecture design",
|
||||
status: "running",
|
||||
isolation: "local",
|
||||
provider: "copilot",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: Date.now() - 180_000,
|
||||
updatedMs: Date.now(),
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
},
|
||||
],
|
||||
]),
|
||||
entries: new Map([[taskId, history]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
store.openTaskInEditorLocation(taskId);
|
||||
});
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
const card = page.getByRole("form", { name: "Choose diagram options" });
|
||||
await expect(card).toBeVisible();
|
||||
|
||||
// Scroll slightly away so the tall card's header sits above `.stream` while Submit stays in view, then submit.
|
||||
await card.getByRole("radio", { name: /^Layered architecture diagram/ }).check();
|
||||
await stream.hover();
|
||||
await page.mouse.wheel(0, -10);
|
||||
await stream.evaluate((el) => {
|
||||
el.scrollTop = el.scrollHeight - el.clientHeight - 4;
|
||||
el.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
await card.getByRole("button", { name: "Submit", exact: true }).click();
|
||||
await expect(card).toHaveCount(0);
|
||||
|
||||
// Immediately after collapsing, the preceding reply stays visible in the viewport with no blank slack lockup.
|
||||
await expect(stream.getByText("I reviewed")).toBeInViewport();
|
||||
|
||||
// Scrolling upward with the wheel reaches the earliest turns without snapping scrollTop back.
|
||||
await stream.hover();
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await page.mouse.wheel(0, -120);
|
||||
await page.waitForTimeout(20);
|
||||
}
|
||||
await expect(stream.getByText("Earlier reply 0 with context from the repository.")).toBeInViewport();
|
||||
});
|
||||
@@ -68,3 +68,47 @@ for (const [name, options] of [
|
||||
expect(geometry.scrollerBottom).toBeCloseTo(geometry.viewportBottom, 0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const mode of ["split", "unified"] as const) {
|
||||
test(`the end of the longest line clears the overview lane at the full horizontal scroll (${mode})`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const line = (word: string) => `// ${"lorem ipsum dolor sit amet ".repeat(12)}${word} line end`;
|
||||
await page.evaluate(
|
||||
async ({ left, right, mode }) => {
|
||||
localStorage.setItem(
|
||||
"openidea.vcs.diffOptions",
|
||||
JSON.stringify({ mode, alignChanges: false, collapse: false, softWrap: false }),
|
||||
);
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("diff.compareTexts", {
|
||||
path: "src/long.ts",
|
||||
title: "src/long.ts",
|
||||
left: { text: left, label: "HEAD" },
|
||||
right: { text: right, label: "Working tree" },
|
||||
});
|
||||
},
|
||||
// The old line is the longest: in the unified view it decides the width as a deleted chunk.
|
||||
{ left: `a\n${line("old old old")}\nb\n`, right: `a\n${line("new")}\nb\n`, mode },
|
||||
);
|
||||
const editor = page.locator(".cm-editor.cm-merge-b").first();
|
||||
await expect(editor).toContainText("new line end");
|
||||
// How far the end of the longest line reaches past the lane's left edge, scrolled fully right.
|
||||
const overlap = () =>
|
||||
editor.evaluate((ed) => {
|
||||
const scroller = ed.querySelector<HTMLElement>(".cm-scroller")!;
|
||||
scroller.scrollLeft = scroller.scrollWidth;
|
||||
const lane = ed.querySelector(".cm-openidea-overview")!.getBoundingClientRect();
|
||||
const ends = [...ed.querySelectorAll(".cm-line, .cm-deletedLine")]
|
||||
.filter((l) => l.textContent?.endsWith("line end"))
|
||||
.map((l) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(l);
|
||||
return range.getBoundingClientRect().right;
|
||||
});
|
||||
return Math.max(...ends) - lane.left;
|
||||
});
|
||||
await expect.poll(overlap).toBeLessThanOrEqual(0);
|
||||
});
|
||||
}
|
||||
@@ -610,6 +610,8 @@ test("keeps diagrams and their math labels when editing or switching Markdown ta
|
||||
].join("\n\n");
|
||||
await page.keyboard.insertText(source);
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
// Mermaid rendering is deferred while editing the source.
|
||||
await preview.focus();
|
||||
const diagram = preview.locator(".mermaid-output .pan-zoom-content > svg");
|
||||
await expect(diagram.locator("foreignObject math")).toHaveCount(1);
|
||||
const original = await diagram.elementHandle();
|
||||
@@ -623,6 +625,7 @@ test("keeps diagrams and their math labels when editing or switching Markdown ta
|
||||
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText(source.replace("$$x^2$$", () => "$$z^3$$"));
|
||||
await preview.focus();
|
||||
await expect(diagram.locator("foreignObject math mi")).toHaveText("z");
|
||||
const edited = await diagram.elementHandle();
|
||||
expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(false);
|
||||
@@ -673,6 +676,7 @@ test("Markdown preview aligns Mermaid diagrams to their container align attribut
|
||||
);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await preview.focus();
|
||||
const outputs = preview.locator("[data-mermaid-state='ok'] .mermaid-output");
|
||||
await expect(outputs).toHaveCount(4);
|
||||
|
||||
|
||||
@@ -362,6 +362,52 @@ test("long Git Log filter values shorten inside their buttons", async ({ workben
|
||||
await expect(clear).toBeHidden();
|
||||
});
|
||||
|
||||
test("a click in the User filter shows only that user's commits, without check marks", async ({ workbench: page }) => {
|
||||
const alice = "Alice <[email protected]>";
|
||||
const bob = "Bob <[email protected]>";
|
||||
await page.evaluate(
|
||||
async ([alice, bob]) => {
|
||||
const optionsModule = "/src/features/vcs/logOptions.ts";
|
||||
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
|
||||
// Room for the User filter on the bar.
|
||||
setLogOptions({ showBranches: false, showDetails: false });
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_log_users = () => [alice, "Author <[email protected]>", bob];
|
||||
const log = h.vcs_log!;
|
||||
h.vcs_log = (args) => {
|
||||
(window as { logAuthors?: unknown }).logAuthors = (args.query as { authors: string[] }).authors;
|
||||
return log(args);
|
||||
};
|
||||
},
|
||||
[alice, bob],
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
|
||||
const user = toolbar.getByRole("button", { name: /^User/ });
|
||||
const item = (name: string) => page.getByRole("menuitem", { name, exact: true });
|
||||
const logAuthors = () => page.evaluate(() => (window as { logAuthors?: unknown }).logAuthors);
|
||||
|
||||
// The menu opens with the users known so far and fetches the list in the background.
|
||||
await user.click();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(async () => {
|
||||
await user.click();
|
||||
try {
|
||||
await expect(item(alice)).toBeVisible({ timeout: 1000 });
|
||||
} catch (e) {
|
||||
await page.keyboard.press("Escape");
|
||||
throw e;
|
||||
}
|
||||
}).toPass();
|
||||
await item(alice).click();
|
||||
await expect(user).toHaveText(`User: ${alice}`);
|
||||
await expect.poll(logAuthors).toEqual([alice]);
|
||||
await user.click();
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: alice, exact: true })).toHaveCount(0);
|
||||
await item(bob).click();
|
||||
await expect(user).toHaveText(`User: ${bob}`);
|
||||
await expect.poll(logAuthors).toEqual([bob]);
|
||||
});
|
||||
|
||||
test("Git Log puts affected changes on the changed-files toolbar and groups preview options", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -8,7 +8,7 @@ async function openRecent(page: Page, kind: "recentFiles" | "recentLocations") {
|
||||
}, kind);
|
||||
}
|
||||
|
||||
test("Recent Files keeps directories beside names and leaves room for files in a narrow window", async ({
|
||||
test("Recent Files shows only names and keeps the selected path in the footer in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
@@ -20,20 +20,19 @@ test("Recent Files keeps directories beside names and leaves room for files in a
|
||||
const files = dialog.getByRole("listbox", { name: "Recent files" });
|
||||
const row = files.getByRole("option").first();
|
||||
const name = row.getByText("InvoiceService.ts", { exact: true });
|
||||
const directory = row.getByText("src/orders", { exact: true });
|
||||
const footer = dialog.locator("footer");
|
||||
await expect(name).toBeVisible();
|
||||
const nameRight = await name.evaluate((el) => el.getBoundingClientRect().right);
|
||||
const dirLeft = (await directory.boundingBox())!.x;
|
||||
expect(dirLeft - nameRight).toBeLessThanOrEqual(8);
|
||||
await expect(row).not.toContainText("src/orders");
|
||||
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
|
||||
|
||||
await page.setViewportSize({ width: 400, height: 500 });
|
||||
expect((await files.boundingBox())!.width).toBeGreaterThan(200);
|
||||
expect((await dialog.getByRole("textbox", { name: "Filter recent files" }).boundingBox())!.width).toBeGreaterThan(
|
||||
200,
|
||||
);
|
||||
await expect.poll(() => directory.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThan(20);
|
||||
await expect(row).not.toContainText("src/orders");
|
||||
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
|
||||
await expect(dialog.getByRole("button", { name: /Recent Locations/ })).toBeVisible();
|
||||
const footer = dialog.locator("footer");
|
||||
await expect(footer).toBeInViewport({ ratio: 1 });
|
||||
expect(
|
||||
await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollHeight - el.clientHeight),
|
||||
|
||||
@@ -69,6 +69,11 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
|
||||
(path) => path.getAttribute("d"),
|
||||
);
|
||||
}, name);
|
||||
// File-type logos sit as an 8px corner badge on the module folder; dedicated
|
||||
// project glyphs (Flutter, Gradle, Maven, Vite) still replace the folder.
|
||||
const folder = await shape("module");
|
||||
const glyph = async (icon: string) =>
|
||||
icon.startsWith("file-") ? [...folder, ...(await shape(icon))] : await shape(icon);
|
||||
for (const [name, icon] of [
|
||||
["z-web", "file-npm"],
|
||||
["Go2", "file-go"],
|
||||
@@ -83,9 +88,13 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
|
||||
["notes", "module"],
|
||||
]) {
|
||||
const row = tree.locator(`[data-project-path="/work/${name}"]`);
|
||||
const badged = icon!.startsWith("file-");
|
||||
await expect(row).toHaveAttribute("data-project-icon", badged ? "module" : icon!);
|
||||
if (badged) await expect(row).toHaveAttribute("data-project-type-badge", icon!);
|
||||
else await expect(row).not.toHaveAttribute("data-project-type-badge");
|
||||
await expect
|
||||
.poll(() => row.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))))
|
||||
.toEqual(await shape(icon!));
|
||||
.toEqual(await glyph(icon!));
|
||||
await expect(row.locator("[data-project-path]")).toHaveCount(0);
|
||||
}
|
||||
await tree.locator('[data-project-path="/work/z-web"]').click();
|
||||
@@ -113,13 +122,12 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
|
||||
removed: ["/work/z-web/package.json"],
|
||||
});
|
||||
});
|
||||
const zWeb = tree.locator('[data-project-path="/work/z-web"]');
|
||||
await expect(zWeb).toHaveAttribute("data-project-icon", "module");
|
||||
await expect(zWeb).toHaveAttribute("data-project-type-badge", "file-go");
|
||||
await expect
|
||||
.poll(() =>
|
||||
tree
|
||||
.locator('[data-project-path="/work/z-web"] svg path')
|
||||
.evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))),
|
||||
)
|
||||
.toEqual(await shape("file-go"));
|
||||
.poll(() => zWeb.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))))
|
||||
.toEqual(await glyph("file-go"));
|
||||
await expect(tree.locator("[data-project-path]")).toHaveText([
|
||||
"rust/work/rust",
|
||||
"dart/work/dart",
|
||||
|
||||
@@ -7,8 +7,21 @@ indent = { tab-size = 4, insert-spaces = true }
|
||||
ui-mode = "C#"
|
||||
tree-sitter = "csharp"
|
||||
|
||||
[[language-servers]]
|
||||
name = "roslyn-language-server"
|
||||
command = "roslyn-language-server"
|
||||
# --autoLoadProjects: the server finds and opens the solution or projects itself.
|
||||
args = ["--stdio", "--autoLoadProjects", "--telemetryLevel", "off"]
|
||||
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props", "ProjectSettings/ProjectVersion.txt"]
|
||||
install-hint = "Install Roslyn (C#) in Settings › Languages & Frameworks › Language Servers (needs the .NET 10 SDK), or csharp-ls for older SDKs"
|
||||
|
||||
[language-servers.settings."csharp|completion"]
|
||||
dotnet_show_completion_items_from_unimported_namespaces = true
|
||||
|
||||
[[language-servers]]
|
||||
name = "csharp-ls"
|
||||
# Alternative: used only when the server above is not installed.
|
||||
fallback = true
|
||||
command = "csharp-ls"
|
||||
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props", "ProjectSettings/ProjectVersion.txt"]
|
||||
install-hint = "dotnet tool install --global csharp-ls"
|
||||
|
||||
@@ -81,6 +81,11 @@ command = "java-analyzer"
|
||||
root-markers = ["java-analyzer.toml", "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "build.xml", ".project"]
|
||||
install-hint = "Install java-analyzer in Settings › Languages & Frameworks › Language Servers (https://github.com/l0ng-ai/java-analyzer)"
|
||||
|
||||
[language-servers.initialization-options]
|
||||
# OpenIDEA owns New Java Class templates. Do not race the editor by inserting
|
||||
# a second package and class through workspace/applyEdit when it opens an empty file.
|
||||
newFileTemplate = false
|
||||
|
||||
[[language-servers]]
|
||||
name = "kmp-lsp"
|
||||
fallback = true
|
||||
|
||||
@@ -15,6 +15,8 @@ use tracing_subscriber::{EnvFilter, Layer};
|
||||
|
||||
const PREFIX: &str = "openidea";
|
||||
const SUFFIX: &str = "log";
|
||||
/// Lines waiting for the log writer thread before new ones are dropped.
|
||||
const LOG_QUEUE_LINES: usize = 16_384;
|
||||
|
||||
static LOG_DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||
static GUARD: OnceLock<WorkerGuard> = OnceLock::new();
|
||||
@@ -38,7 +40,11 @@ pub fn init(identifier: &str) {
|
||||
.max_log_files(7)
|
||||
.build(&dir)
|
||||
.ok()?;
|
||||
let (writer, guard) = tracing_appender::non_blocking(appender);
|
||||
// The default queue holds 128 000 lines and is filled when it is created: 4 MB of memory for a
|
||||
// backlog the writer thread never builds.
|
||||
let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
|
||||
.buffered_lines_limit(LOG_QUEUE_LINES)
|
||||
.finish(appender);
|
||||
let _ = GUARD.set(guard);
|
||||
log_panics(dir.clone());
|
||||
let _ = LOG_DIR.set(dir);
|
||||
|
||||
@@ -778,6 +778,11 @@ vcs_add_worktree trusted project_host bin
|
||||
vcs_apply_mapped_patch trusted project_host bindings async
|
||||
vcs_apply_patch trusted project_host bindings async
|
||||
vcs_apply_project_patch trusted project_host bindings async
|
||||
vcs_backend_changelist_create trusted project_host bindings async
|
||||
vcs_backend_changelist_delete trusted project_host bindings async
|
||||
vcs_backend_changelist_edit trusted project_host bindings async
|
||||
vcs_backend_changelist_move trusted project_host bindings async
|
||||
vcs_backend_changelists trusted project_host bindings async
|
||||
vcs_blame always project_host bindings async
|
||||
vcs_block_history always project_host bindings async
|
||||
vcs_block_history_revisions always project_host bindings async
|
||||
|
||||
+49
-2
@@ -2330,6 +2330,17 @@ export const commands = {
|
||||
vcsApplyMappedPatch: (repo: string | null, base: string | null, patch: string, paths: string[] | null, mappings: PatchPathMapping[]) => typedError<ProjectPatchOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_mapped_patch", { repo, base, patch, paths, mappings })),
|
||||
vcsApplyPatch: (repo: string | null, patch: string, paths: string[] | null) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch, paths })),
|
||||
vcsApplyProjectPatch: (base: string, patch: string, paths: string[] | null) => typedError<ProjectPatchOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_project_patch", { base, patch, paths })),
|
||||
/** Creates a changelist of the working copy at `repo`; returns its id. */
|
||||
vcsBackendChangelistCreate: (repo: string | null, name: string, comment: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_create", { repo, name, comment })),
|
||||
vcsBackendChangelistDelete: (repo: string | null, id: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_delete", { repo, id })),
|
||||
vcsBackendChangelistEdit: (repo: string | null, id: string, name: string, comment: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_edit", { repo, id, name, comment })),
|
||||
/** Moves `paths` to changelist `id` of the working copy each belongs to. */
|
||||
vcsBackendChangelistMove: (paths: string[], id: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_backend_changelist_move", { paths, id })),
|
||||
/**
|
||||
* 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`]).
|
||||
*/
|
||||
vcsBackendChangelists: (repo: string | null) => typedError<BackendChangelist[] | null, IdeError>(__TAURI_INVOKE("vcs_backend_changelists", { repo })),
|
||||
vcsBlame: (path: string, text: string | null, revision: string | null) => typedError<BlameLine_Serialize[], IdeError>(__TAURI_INVOKE("vcs_blame", { path, text, revision })),
|
||||
/**
|
||||
* History for Selection: commits that changed `lines` (0-based, inclusive) of `path`'s
|
||||
@@ -2819,8 +2830,8 @@ export const commands = {
|
||||
path: string,
|
||||
} | null>("wsl_resolve", { path }),
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
xcodeBspGenerate: (tool: string, container: string) => typedError<null, IdeError>(__TAURI_INVOKE("xcode_bsp_generate", { tool, container })),
|
||||
/**
|
||||
@@ -4604,6 +4615,17 @@ export type AutoUpload = "never" |
|
||||
/** Every save, including autosave and external changes. */
|
||||
"always";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export type BackendChangelist = {
|
||||
id: string,
|
||||
name: string,
|
||||
comment?: string,
|
||||
files: IpcPath[],
|
||||
};
|
||||
|
||||
/** Appearance › Background Image. An empty `path` shows no image. */
|
||||
export type BackgroundImageSettings = {
|
||||
path?: string,
|
||||
@@ -4638,6 +4660,8 @@ export type BlameLine_Deserialize = {
|
||||
summary: string,
|
||||
/** The file blamed for this line when it had another path in the attributed commit. */
|
||||
originPath?: IpcPath | null,
|
||||
/** The line's 0-based number in the attributed commit's version of the file. */
|
||||
originLine?: number | null,
|
||||
};
|
||||
|
||||
export type BlameLine_Serialize = {
|
||||
@@ -4647,6 +4671,8 @@ export type BlameLine_Serialize = {
|
||||
summary: string,
|
||||
/** The file blamed for this line when it had another path in the attributed commit. */
|
||||
originPath?: IpcPath | null,
|
||||
/** The line's 0-based number in the attributed commit's version of the file. */
|
||||
originLine?: number | null,
|
||||
};
|
||||
|
||||
/** History for Selection: the commits that changed a block of lines, newest first. */
|
||||
@@ -5910,6 +5936,12 @@ export type CoverageSuite = {
|
||||
files: FileCoverage[],
|
||||
};
|
||||
|
||||
/** C/C++ debugger executables. Empty paths use automatic discovery. */
|
||||
export type CppDebuggerSettings = {
|
||||
gdbExecutable?: string,
|
||||
lldbDapExecutable?: string,
|
||||
};
|
||||
|
||||
/** Payload for creating a new instruction or rule file. */
|
||||
export type CreateAgentMemoryInput = {
|
||||
scope: McpScope,
|
||||
@@ -6919,6 +6951,7 @@ export type DebuggerSettings = {
|
||||
/** Java: whether to reload changed classes into running debug sessions after compilation. */
|
||||
hotSwapAfterCompile?: HotSwapPolicy,
|
||||
python?: PythonDebuggerSettings,
|
||||
cpp?: CppDebuggerSettings,
|
||||
};
|
||||
|
||||
/** An editor decoration. */
|
||||
@@ -8171,6 +8204,11 @@ export type ExternalSession = {
|
||||
cwd: string | null,
|
||||
/** File modification time, ms since the epoch. */
|
||||
updatedMs: number | null,
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
inUse: boolean,
|
||||
};
|
||||
|
||||
/** Tools › External Tools entry. */
|
||||
@@ -15716,6 +15754,8 @@ export type TerminalSettings = {
|
||||
closeOnExit?: boolean,
|
||||
mouseReporting?: boolean,
|
||||
copyOnSelection?: boolean,
|
||||
/** Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it. */
|
||||
osc52Clipboard?: boolean,
|
||||
pasteOnMiddleClick?: boolean,
|
||||
/** Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it). */
|
||||
rightClickPaste?: boolean,
|
||||
@@ -16276,6 +16316,9 @@ export type VcsConfirmationSettings = {
|
||||
onPatchCreated?: string,
|
||||
};
|
||||
|
||||
/** The version control system holding a root. */
|
||||
export type VcsKind = "git" | "perforce" | "subversion";
|
||||
|
||||
/**
|
||||
* Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
* root (`.` for the root itself) or absolute outside it.
|
||||
@@ -16293,6 +16336,8 @@ export type VcsRoot = {
|
||||
root: IpcPath,
|
||||
/** Root representing all mapped worktrees of the same Git repository in branch lists. */
|
||||
branchRoot: IpcPath,
|
||||
/** The version control system holding it. */
|
||||
kind: VcsKind,
|
||||
/** Merge / rebase / cherry-pick / revert in progress. */
|
||||
operation: string | null,
|
||||
/** The current rebase uses Git's interactive mode. */
|
||||
@@ -16311,6 +16356,8 @@ export type VcsRoot = {
|
||||
hasRemotes?: boolean | null,
|
||||
/** Conflicts staged during the current operation that can be reopened. */
|
||||
resolvedConflicts?: IpcPath[],
|
||||
/** The repository's worktree or git directory is missing or on an unmounted volume. */
|
||||
unavailable?: boolean,
|
||||
};
|
||||
|
||||
/** Version Control (main page) and its sub-pages. */
|
||||
|
||||
@@ -972,6 +972,8 @@ export interface DocumentAttachment {
|
||||
doc: number;
|
||||
/** Current document text; build the view's state from it. */
|
||||
text(): string;
|
||||
/** Current document text as a CodeMirror snapshot, with UTF-16 offsets. */
|
||||
contents(): Text;
|
||||
/** The document's line ending (detected on load, as the status bar shows). */
|
||||
lineEnding(): LineEnding;
|
||||
/** The document's language mode name (backend-assigned, as the editor tabs use). */
|
||||
@@ -985,6 +987,8 @@ export interface DocumentAttachment {
|
||||
subscribeExternalChanges(listener: (changes: ChangeSet) => void): () => void;
|
||||
/** Last view state, kept current while unmounted; use it when remounting this attachment. */
|
||||
editorState(): EditorState | null;
|
||||
/** Formatting state with the document's Code Style and any contributed formatter. */
|
||||
formattingState(): EditorState;
|
||||
/** Dispatch typing through the document history when `sharedHistory` was requested. */
|
||||
dispatchTransactions(transactions: readonly Transaction[], view: EditorView): void;
|
||||
/** Add to the view (one view at a time). */
|
||||
@@ -1007,7 +1011,7 @@ export interface DocumentAttachment {
|
||||
* file, so Undo there reverts it too; else this view's. Before either exists,
|
||||
* applies the edit directly to the document.
|
||||
*/
|
||||
edit(changes: ChangeSpec, userEvent?: string): void;
|
||||
edit(changes: ChangeSpec, userEvent?: string, annotations?: readonly Annotation<unknown>[]): void;
|
||||
/** Detach; the document closes when nothing else shows it. */
|
||||
release(): void;
|
||||
}
|
||||
@@ -1015,6 +1019,8 @@ export interface DocumentAttachment {
|
||||
export interface DocumentAttachmentOptions {
|
||||
/** Record typing in the text tab's history when one exists. Use `dispatchTransactions` on the view. */
|
||||
sharedHistory?: boolean;
|
||||
/** Load the history of an existing text tab that has yet to be shown. */
|
||||
preserveTabHistory?: boolean;
|
||||
}
|
||||
|
||||
let documentAttacher: ((path: string, options?: DocumentAttachmentOptions) => Promise<DocumentAttachment>) | null =
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { joinerKind, zeroWidthJoiners } from "../joiners";
|
||||
|
||||
const code = (s: string) => s.charCodeAt(0);
|
||||
|
||||
describe("zero-width joiners", () => {
|
||||
it("splits a joiner off CJK text, where it joins nothing (#7019)", () => {
|
||||
expect(joinerKind(code("是"), code("全"))).toBe("split");
|
||||
expect(joinerKind(code("同"), code(":"))).toBe("split");
|
||||
expect(joinerKind(undefined, code("位"))).toBe("split");
|
||||
expect(joinerKind(code(";"), undefined)).toBe("split");
|
||||
});
|
||||
|
||||
it("keeps a joiner that shapes its neighbours", () => {
|
||||
// Persian ZWNJ, Devanagari, an emoji ZWJ sequence (high surrogate of 👩).
|
||||
expect(joinerKind(code("ی"), code("ه"))).toBe("keep");
|
||||
expect(joinerKind(code("क"), code("ष"))).toBe("keep");
|
||||
expect(joinerKind(0xd83d, 0xd83d)).toBe("keep");
|
||||
expect(joinerKind(code("a"), code("ی"))).toBe("keep");
|
||||
});
|
||||
|
||||
it("shows a joiner between ASCII characters or alone on a line", () => {
|
||||
expect(joinerKind(code("a"), code("b"))).toBe("show");
|
||||
expect(joinerKind(undefined, undefined)).toBe("show");
|
||||
});
|
||||
|
||||
let view: EditorView | null = null;
|
||||
afterEach(() => view?.destroy());
|
||||
|
||||
it("draws the CJK character apart from the joiner and shows one between ASCII", () => {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ doc: "冒号是全角\nab\nسیهزار", extensions: zeroWidthJoiners }),
|
||||
parent: document.body,
|
||||
});
|
||||
const lines = [...view.contentDOM.querySelectorAll(".cm-line")];
|
||||
expect(lines[0]!.querySelectorAll(".cm-zeroWidthJoiner")).toHaveLength(1);
|
||||
expect(lines[0]!.textContent).toBe("冒号是全角");
|
||||
expect(lines[1]!.querySelector(".cm-specialChar")?.getAttribute("title")).toBe("\\u200c");
|
||||
expect(lines[2]!.textContent).toBe("سیهزار");
|
||||
expect(view.state.doc.line(1).text).toBe("冒号是全角");
|
||||
});
|
||||
});
|
||||
@@ -457,6 +457,27 @@ describe("overwrite mode", () => {
|
||||
type("XYZ");
|
||||
expect(show(v)).toBe("abXYZ|\nx");
|
||||
});
|
||||
|
||||
it("overwrites a whole surrogate pair after the caret", () => {
|
||||
for (const [text, typed, after] of [
|
||||
["|😀b", "A", "A|b"],
|
||||
["|ab😀c", "XYZ", "XYZ|c"],
|
||||
["|是\u200D全角", "非", "非|\u200D全角"],
|
||||
// A DOM change from 😀 to 🨀 arrives as the new high surrogate alone.
|
||||
["|😀b", "\ud83e", "\ud83e|\ude00b"],
|
||||
]) {
|
||||
const v = make(text!, overwriteField);
|
||||
toggleOverwrite(v);
|
||||
v.state.facet(EditorView.inputHandler).some((h) => h(v, 0, 0, typed!, () => v.state.update({})));
|
||||
expect(show(v)).toBe(after);
|
||||
}
|
||||
// A caret between the halves of a pair (Go to Line:Column can put it there) replaces nothing on its own.
|
||||
const v = make("|😀b", overwriteField);
|
||||
toggleOverwrite(v);
|
||||
v.dispatch({ selection: { anchor: 1 } });
|
||||
v.state.facet(EditorView.inputHandler).some((h) => h(v, 1, 1, "", () => v.state.update({})));
|
||||
expect(v.state.doc.toString()).toBe("😀b");
|
||||
});
|
||||
});
|
||||
|
||||
describe("smooth caret", () => {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Zero-width joiners (U+200C ZWNJ, U+200D ZWJ) in text pasted from web pages.
|
||||
*
|
||||
* Next to a CJK character they join nothing, but WebKitGTK looks up a glyph for the
|
||||
* character and the joiner together and draws a box when its fallback font lacks the joiner
|
||||
* (#7019). There the joiner is split off as an empty widget, so the character is drawn on its
|
||||
* own. Between ASCII characters (or at a line edge) it is shown like the other invisible
|
||||
* characters. Next to any other non-ASCII character (Arabic, Indic scripts, emoji sequences)
|
||||
* it shapes its neighbours and stays as it is.
|
||||
*/
|
||||
import {
|
||||
type EditorView,
|
||||
Decoration,
|
||||
type DecorationSet,
|
||||
MatchDecorator,
|
||||
ViewPlugin,
|
||||
type ViewUpdate,
|
||||
WidgetType,
|
||||
} from "@codemirror/view";
|
||||
|
||||
const JOINER = /[]/g;
|
||||
|
||||
/** CJK ideographs, kana, Hangul, CJK and fullwidth punctuation (UTF-16 units; surrogates of the supplementary ideographs too). */
|
||||
function isCjk(code: number): boolean {
|
||||
return (
|
||||
(code >= 0x2e80 && code <= 0x9fff) ||
|
||||
(code >= 0xac00 && code <= 0xd7af) ||
|
||||
(code >= 0xd840 && code <= 0xd87f) ||
|
||||
(code >= 0xdc00 && code <= 0xdfff) ||
|
||||
(code >= 0xf900 && code <= 0xfaff) ||
|
||||
(code >= 0xfe30 && code <= 0xfe4f) ||
|
||||
(code >= 0xff00 && code <= 0xffef)
|
||||
);
|
||||
}
|
||||
|
||||
/** A neighbour the joiner may shape: non-ASCII, not CJK, not another invisible format character. */
|
||||
function shapes(code: number | undefined): boolean {
|
||||
if (code == null || code < 0x80 || isCjk(code)) return false;
|
||||
return !(code >= 0x200b && code <= 0x200f) && code !== 0xfeff;
|
||||
}
|
||||
|
||||
export type JoinerKind = "keep" | "split" | "show";
|
||||
|
||||
/** How the joiner between `before` and `after` (UTF-16 code units; undefined at a line edge) is drawn. */
|
||||
export function joinerKind(before: number | undefined, after: number | undefined): JoinerKind {
|
||||
if (shapes(before) || shapes(after)) return "keep";
|
||||
if ((before != null && isCjk(before)) || (after != null && isCjk(after))) return "split";
|
||||
return "show";
|
||||
}
|
||||
|
||||
class SplitWidget extends WidgetType {
|
||||
override eq() {
|
||||
return true;
|
||||
}
|
||||
toDOM() {
|
||||
const span = document.createElement("span");
|
||||
span.className = "cm-zeroWidthJoiner";
|
||||
return span;
|
||||
}
|
||||
override ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class ShowWidget extends WidgetType {
|
||||
constructor(readonly code: number) {
|
||||
super();
|
||||
}
|
||||
override eq(other: ShowWidget) {
|
||||
return other.code === this.code;
|
||||
}
|
||||
toDOM() {
|
||||
const span = document.createElement("span");
|
||||
span.className = "cm-specialChar";
|
||||
span.textContent = "•";
|
||||
span.title = `\\u${this.code.toString(16)}`;
|
||||
span.setAttribute("aria-label", span.title);
|
||||
return span;
|
||||
}
|
||||
override ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const split = Decoration.replace({ widget: new SplitWidget() });
|
||||
const shown = new Map([0x200c, 0x200d].map((c) => [c, Decoration.replace({ widget: new ShowWidget(c) })]));
|
||||
|
||||
const decorator = new MatchDecorator({
|
||||
regexp: JOINER,
|
||||
decoration: (match, view, pos) => {
|
||||
const line = view.state.doc.lineAt(pos);
|
||||
const at = pos - line.from;
|
||||
const before = at > 0 ? line.text.charCodeAt(at - 1) : undefined;
|
||||
const after = at + 1 < line.length ? line.text.charCodeAt(at + 1) : undefined;
|
||||
const kind = joinerKind(before, after);
|
||||
if (kind === "keep") return null;
|
||||
return kind === "split" ? split : (shown.get(match[0]!.charCodeAt(0)) ?? null);
|
||||
},
|
||||
});
|
||||
|
||||
export const zeroWidthJoiners = ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = decorator.createDeco(view);
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
this.decorations = decorator.updateDeco(update, this.decorations);
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
);
|
||||
@@ -24,6 +24,10 @@ const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => {
|
||||
if (r.empty) {
|
||||
const line = state.doc.lineAt(r.head);
|
||||
to = Math.min(line.to, r.head + text.length);
|
||||
// A range that ends between the halves of a surrogate pair takes the low half too, unless the
|
||||
// typed text ends with a high surrogate that pairs with it.
|
||||
const pair = state.doc.sliceString(to - 1, to + 1);
|
||||
if (to > r.head && /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) && !/[\ud800-\udbff]$/.test(text)) to++;
|
||||
}
|
||||
return { changes: { from: r.from, to, insert: text }, range: EditorSelection.cursor(r.from + text.length) };
|
||||
});
|
||||
|
||||
@@ -71,6 +71,7 @@ import { horizontalScrollHold } from "./horizontalScrollHold";
|
||||
import { relativeLineNumbers } from "./relativeLineNumbers";
|
||||
import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard";
|
||||
import { primarySelectionYield } from "./primarySelection";
|
||||
import { zeroWidthJoiners } from "./joiners";
|
||||
import type { LanguageInfo } from "../backend";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -440,6 +441,7 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
compartments.folding.of(foldingFor(o.settings)),
|
||||
highlightActiveLineGutter(),
|
||||
highlightSpecialChars(),
|
||||
zeroWidthJoiners,
|
||||
history(),
|
||||
compartments.caret.of(caretFor(o.settings)),
|
||||
dropCursor(),
|
||||
|
||||
@@ -98,6 +98,26 @@ describe("string clipboard", () => {
|
||||
expect(view.state.doc.toString()).toBe('value = ""\\\n"');
|
||||
});
|
||||
|
||||
it.each([
|
||||
["JavaScript", "javascript", "https://example.test"],
|
||||
["TypeScript", "typescript", "https://example.test"],
|
||||
["Python", "python", "https:\\/\\/example.test"],
|
||||
])("%s unescapes an escaped slash only where the language does", async (mode, language, expected) => {
|
||||
const view = await make(mode, language, 'value = "«https:\\/\\/example.test»"');
|
||||
expect(copiedText(view.state)).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps an escaped slash in a string of a language embedded in JavaScript", async () => {
|
||||
// The embedded mode loads lazily; load it first so the first parse mounts it.
|
||||
await loadSupport(findLanguageDescription("SQL", "")!);
|
||||
const views = await Promise.all(
|
||||
["", "// filler\n".repeat(400)].map((before) =>
|
||||
make("JavaScript", "javascript", before + "const q = sql`SELECT '«a\\/b»'`;"),
|
||||
),
|
||||
);
|
||||
for (const view of views) expect(copiedText(view.state)).toBe("a\\/b");
|
||||
});
|
||||
|
||||
it("disables both escaping and unescaping with the setting", async () => {
|
||||
const settings = { smartKeys: { escapeOnPaste: false, reformatOnPaste: "none" } };
|
||||
const view = await make("Java", "java", 'value = "«a\\nb»"', settings);
|
||||
|
||||
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача