дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
17
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
eac50e0bfa | ||
|
|
281c2ff1e5 | ||
|
|
4276250056 | ||
|
|
ba04491ace | ||
|
|
660a311f21 | ||
|
|
92bf9354fe | ||
|
|
54da9c2c12 | ||
|
|
9ba3150998 | ||
|
|
190e5639f1 | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 |
No files matched your search
@@ -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() }
|
||||
}
|
||||
|
||||
@@ -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")]
|
||||
@@ -803,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]
|
||||
|
||||
@@ -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,8 +104,6 @@ fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
#[cfg(unix)]
|
||||
use std::path::Path;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
@@ -188,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)]
|
||||
|
||||
@@ -1717,16 +1717,13 @@ impl DbManager {
|
||||
// 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 = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment, ..]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
comment.clone(),
|
||||
),
|
||||
_ => return Err(missing()),
|
||||
let 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" };
|
||||
@@ -1734,31 +1731,43 @@ impl DbManager {
|
||||
let target = sql::qualified(driver, schema, name);
|
||||
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
let partition = match parent {
|
||||
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
|
||||
parent_schema: parent_schema.clone(),
|
||||
parent_table: parent_table.clone(),
|
||||
bound: bound.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let is_partition = partition.is_some();
|
||||
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
|
||||
sql::postgres_ddl_columns(oid),
|
||||
sql::postgres_ddl_constraints(oid),
|
||||
sql::postgres_ddl_columns(oid, is_partition),
|
||||
sql::postgres_ddl_constraints(oid, is_partition),
|
||||
sql::postgres_ddl_grants(oid),
|
||||
sql::postgres_ddl_indexes(oid),
|
||||
sql::postgres_ddl_triggers(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!(
|
||||
pool.rows(&cols_q, MAX_META_ROWS),
|
||||
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),
|
||||
pool.rows(&trigger_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()?,
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten().filter(|c| !c.is_empty()),
|
||||
})
|
||||
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 = key_rows?
|
||||
@@ -1779,8 +1788,13 @@ impl DbManager {
|
||||
.collect::<Vec<_>>();
|
||||
let triggers =
|
||||
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+203
-24
@@ -697,45 +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`.
|
||||
/// 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) -> String {
|
||||
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"
|
||||
)
|
||||
}
|
||||
@@ -754,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"
|
||||
)
|
||||
}
|
||||
@@ -845,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)
|
||||
}
|
||||
@@ -1004,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 {
|
||||
@@ -1026,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
|
||||
@@ -1044,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)));
|
||||
@@ -1429,7 +1534,7 @@ mod tests {
|
||||
// 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);
|
||||
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}");
|
||||
@@ -1440,12 +1545,12 @@ mod tests {
|
||||
#[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,
|
||||
},
|
||||
];
|
||||
@@ -1456,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()),
|
||||
},
|
||||
];
|
||||
@@ -1489,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"
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -386,8 +386,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())));
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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")]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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)]);
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -386,7 +386,18 @@ test("a click in the User filter shows only that user's commits, without check m
|
||||
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]);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -4638,6 +4638,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 +4649,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 +5914,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 +6929,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. */
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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) };
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8,9 +8,11 @@ const JS = new Set(["javascript", "typescript"]);
|
||||
interface PlainString {
|
||||
quote: string;
|
||||
language: string;
|
||||
/** `\/` is an escape: a JavaScript string, not one of a language embedded in a template literal. */
|
||||
slash: boolean;
|
||||
}
|
||||
|
||||
function readEscape(text: string, at: number, language: string): { end: number; value: string } {
|
||||
function readEscape(text: string, at: number, language: string, slash = false): { end: number; value: string } {
|
||||
const rest = text.slice(at + 1);
|
||||
const ch = rest[0];
|
||||
const basic: Record<string, string> = { n: "\n", r: "\r", t: "\t", "\\": "\\", '"': '"', "'": "'" };
|
||||
@@ -18,6 +20,7 @@ function readEscape(text: string, at: number, language: string): { end: number;
|
||||
if (!["kotlin", "rust"].includes(language)) basic.f = "\f";
|
||||
if (["python", "go", "c", "cpp"].includes(language)) basic.a = "\x07";
|
||||
if (!["java", "kotlin", "rust"].includes(language)) basic.v = "\v";
|
||||
if (slash) basic["/"] = "/";
|
||||
if (language === "kotlin") basic.$ = "$";
|
||||
if (language === "java") basic.s = " ";
|
||||
if (language === "c" || language === "cpp") basic["?"] = "?";
|
||||
@@ -85,7 +88,9 @@ function plainStringAt(state: EditorState, from: number, to: number, language: s
|
||||
if ([from, to].some((pos) => pos > node.from + i && pos < node.from + end)) return null;
|
||||
i = end - 1;
|
||||
}
|
||||
return { quote, language };
|
||||
let embedded = false;
|
||||
for (let n = node.parent; n; n = n.parent) if (n.type.isTop && n.parent) embedded = true;
|
||||
return { quote, language, slash: JS.has(language) && !embedded };
|
||||
}
|
||||
if (!node.parent) return null;
|
||||
node = node.parent;
|
||||
@@ -109,12 +114,12 @@ function escapeText(text: string, literal: PlainString): string {
|
||||
});
|
||||
}
|
||||
|
||||
function unescapeText(text: string, language: string): string {
|
||||
function unescapeText(text: string, literal: PlainString): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
if (text[i] !== "\\") out += text[i];
|
||||
else {
|
||||
const escape = readEscape(text, i, language);
|
||||
const escape = readEscape(text, i, literal.language, literal.slash);
|
||||
out += escape.value;
|
||||
i = escape.end - 1;
|
||||
}
|
||||
@@ -151,10 +156,15 @@ export function stringClipboard(language: string | undefined): Extension {
|
||||
),
|
||||
EditorView.clipboardOutputFilter.of((text, state) => {
|
||||
const ranges = state.selection.ranges;
|
||||
if (ranges.some((r) => r.empty || !plainStringAt(state, r.from, r.to, language))) return text;
|
||||
const literals: PlainString[] = [];
|
||||
for (const r of ranges) {
|
||||
const literal = r.empty ? null : plainStringAt(state, r.from, r.to, language);
|
||||
if (!literal) return text;
|
||||
literals.push(literal);
|
||||
}
|
||||
const selected = ranges.map((r) => state.sliceDoc(r.from, r.to));
|
||||
if (text !== selected.join(state.lineBreak)) return text;
|
||||
return selected.map((part) => unescapeText(part, language)).join(state.lineBreak);
|
||||
return selected.map((part, i) => unescapeText(part, literals[i]!)).join(state.lineBreak);
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CodeAction } from "@/bindings";
|
||||
import { unambiguousImport } from "./autoImport";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { CodeAction, WorkspaceEdit } from "@/bindings";
|
||||
import { readyOrganizeImportsAction, unambiguousImport } from "./autoImport";
|
||||
|
||||
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
|
||||
title,
|
||||
@@ -14,6 +14,21 @@ const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
|
||||
...over,
|
||||
});
|
||||
|
||||
const organizeEdit = (): WorkspaceEdit => ({
|
||||
files: [
|
||||
{
|
||||
kind: "edit",
|
||||
path: "/p/Sample.java",
|
||||
edits: [
|
||||
{
|
||||
range: { start: { line: 3, col: 0 }, end: { line: 4, col: 0 } },
|
||||
new_text: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe("unambiguousImport", () => {
|
||||
it("applies the one import fix among other quick fixes", () => {
|
||||
const fix = action("Import 'ArrayList' (java.util)");
|
||||
@@ -43,3 +58,46 @@ describe("unambiguousImport", () => {
|
||||
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readyOrganizeImportsAction", () => {
|
||||
const organize = (over: Partial<CodeAction> = {}) =>
|
||||
action("Organize imports", { kind: "source.organizeImports", ...over });
|
||||
|
||||
it("resolves a lazy organize-imports action that has data but no edit", async () => {
|
||||
const lazy = organize({ data: '{"id":"organize_imports"}' });
|
||||
const resolved = { ...lazy, edit: organizeEdit() };
|
||||
const resolve = vi.fn(async (a: CodeAction) => {
|
||||
expect(a).toBe(lazy);
|
||||
return resolved;
|
||||
});
|
||||
await expect(readyOrganizeImportsAction([lazy], resolve)).resolves.toBe(resolved);
|
||||
expect(resolve).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("uses an action that already has an edit without resolving", async () => {
|
||||
const ready = organize({ edit: organizeEdit() });
|
||||
const resolve = vi.fn(async (a: CodeAction) => a);
|
||||
await expect(readyOrganizeImportsAction([ready], resolve)).resolves.toBe(ready);
|
||||
expect(resolve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips disabled actions and lazy actions that cannot be resolved to an edit", async () => {
|
||||
const resolve = vi.fn(async (a: CodeAction) => a);
|
||||
await expect(
|
||||
readyOrganizeImportsAction(
|
||||
[
|
||||
organize({ disabledReason: "unavailable", edit: organizeEdit() }),
|
||||
organize(),
|
||||
action("Import 'HashMap' (java.util)", { data: "{}" }),
|
||||
],
|
||||
resolve,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
expect(resolve).not.toHaveBeenCalled();
|
||||
|
||||
const lazy = organize({ data: '{"id":"organize_imports"}' });
|
||||
const unresolved = vi.fn(async (a: CodeAction) => a);
|
||||
await expect(readyOrganizeImportsAction([lazy], unresolved)).resolves.toBeUndefined();
|
||||
expect(unresolved).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,25 @@ export function unambiguousImport(actions: readonly CodeAction[]): CodeAction |
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* An organize-imports action the on-the-fly path can inspect.
|
||||
* java-analyzer (and other servers) often return a lazy action with `data` and
|
||||
* no `edit`; the workspace edit is only available after `codeAction/resolve`.
|
||||
* Command-palette and optimize-on-save already resolve through
|
||||
* `runInteractiveCodeAction` / `lspApplyCodeAction`.
|
||||
*/
|
||||
export async function readyOrganizeImportsAction(
|
||||
actions: readonly CodeAction[],
|
||||
resolve: (action: CodeAction) => Promise<CodeAction>,
|
||||
): Promise<CodeAction | undefined> {
|
||||
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason);
|
||||
if (!action) return undefined;
|
||||
if (action.edit) return action;
|
||||
if (action.data == null) return undefined;
|
||||
const resolved = await resolve(action);
|
||||
return resolved.edit && !resolved.disabledReason ? resolved : undefined;
|
||||
}
|
||||
|
||||
/** Whether a workspace edit for `path` touches 0-based `line`. */
|
||||
export function editTouchesLine(action: CodeAction, path: string, line: number): boolean {
|
||||
for (const f of action.edit?.files ?? []) {
|
||||
@@ -116,7 +135,9 @@ const autoImportPlugin = ViewPlugin.fromClass(
|
||||
const doc = docOf(view)!;
|
||||
const range = offsetsToRange(view.state.doc, 0, view.state.doc.length);
|
||||
const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, range, ["source.organizeImports"]));
|
||||
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason && a.edit);
|
||||
const action = await readyOrganizeImportsAction(actions, (a) =>
|
||||
lspRequest(() => commands.lspResolveCodeAction(doc.doc, a)),
|
||||
);
|
||||
if (!action || editTouchesLine(action, doc.path, caretLine)) return;
|
||||
const edits = action.edit!.files.flatMap((f) => (f.kind === "edit" && f.path === doc.path ? f.edits : []));
|
||||
const noop = edits.every((e) => {
|
||||
|
||||
@@ -39,7 +39,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const { lensTargets, usagesLensExtension } = await import("./codeLens");
|
||||
const { lensTargets, skipInheritedLifecycleUsages, usagesLensExtension } = await import("./codeLens");
|
||||
const { foregroundStarted } = await import("./foreground");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
@@ -692,3 +692,151 @@ describe("file changes on disk", () => {
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inherited Dart lifecycle usages", () => {
|
||||
const textOf = (src: string) => EditorState.create({ doc: src }).doc;
|
||||
const src = [
|
||||
"class _PageState extends State<Page> {",
|
||||
" @override",
|
||||
" void initState() { super.initState(); }",
|
||||
"",
|
||||
" @override",
|
||||
" Widget build(BuildContext context) { return const SizedBox(); }",
|
||||
"",
|
||||
" @override",
|
||||
" void dispose() { super.dispose(); }",
|
||||
"",
|
||||
" @override",
|
||||
" void didUpdateWidget(Page oldWidget) { super.didUpdateWidget(oldWidget); }",
|
||||
"",
|
||||
" @override",
|
||||
" void didChangeDependencies() { super.didChangeDependencies(); }",
|
||||
"",
|
||||
" Future<void> loadData() async {}",
|
||||
"",
|
||||
" Widget buildHelper() { return const SizedBox(); }",
|
||||
"",
|
||||
" @override Widget createState() => this;",
|
||||
"",
|
||||
" @override",
|
||||
" String toString() => 'page';",
|
||||
"",
|
||||
" @override",
|
||||
" int get hashCode => 1;",
|
||||
"",
|
||||
" @override",
|
||||
" bool operator ==(Object other) => other is _PageState;",
|
||||
"}",
|
||||
].join("\n");
|
||||
const doc = textOf(src);
|
||||
const lineOf = (snippet: string) => src.split("\n").findIndex((l) => l.includes(snippet));
|
||||
|
||||
it("skips Flutter @override lifecycle methods, not other Dart names", () => {
|
||||
expect(skipInheritedLifecycleUsages("dart", "initState", doc, lineOf("void initState"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "build", doc, lineOf("Widget build(BuildContext"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "dispose", doc, lineOf("void dispose"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "didUpdateWidget", doc, lineOf("void didUpdateWidget"))).toBe(true);
|
||||
expect(
|
||||
skipInheritedLifecycleUsages("dart", "didChangeDependencies", doc, lineOf("void didChangeDependencies")),
|
||||
).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "createState", doc, lineOf("@override Widget createState"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "toString", doc, lineOf("String toString"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "hashCode", doc, lineOf("int get hashCode"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "operator ==", doc, lineOf("bool operator"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "==", doc, lineOf("bool operator"))).toBe(true);
|
||||
expect(skipInheritedLifecycleUsages("dart", "loadData", doc, lineOf("Future<void> loadData"))).toBe(false);
|
||||
expect(skipInheritedLifecycleUsages("dart", "buildHelper", doc, lineOf("Widget buildHelper"))).toBe(false);
|
||||
expect(skipInheritedLifecycleUsages("dart", "_PageState", doc, 0)).toBe(false);
|
||||
expect(skipInheritedLifecycleUsages("rust", "build", doc, lineOf("Widget build(BuildContext"))).toBe(false);
|
||||
});
|
||||
|
||||
it("does not skip a lifecycle name that is not an override", () => {
|
||||
const plain = textOf("void dispose() {}\nWidget build() { return const SizedBox(); }");
|
||||
expect(skipInheritedLifecycleUsages("dart", "dispose", plain, 0)).toBe(false);
|
||||
expect(skipInheritedLifecycleUsages("dart", "build", plain, 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Dart Code Vision references", () => {
|
||||
const dart = { doc: 11, path: "/p/page.dart", language: "dart", uiMode: "Dart", readOnly: false };
|
||||
const src = [
|
||||
"class _PageState extends State<Page> {",
|
||||
" @override",
|
||||
" void initState() {}",
|
||||
" @override",
|
||||
" Widget build(BuildContext context) { return const SizedBox(); }",
|
||||
" Future<void> loadData() async {}",
|
||||
" void refresh() {}",
|
||||
"}",
|
||||
].join("\n");
|
||||
|
||||
it("does not query references for @override lifecycle methods", async () => {
|
||||
ipc.docOutline.mockResolvedValue(
|
||||
ok([
|
||||
item("_PageState", "class", 0, [
|
||||
item("initState", "method", 2),
|
||||
item("build", "method", 4),
|
||||
item("loadData", "method", 5),
|
||||
item("refresh", "method", 6),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: src,
|
||||
extensions: [lspDoc.of(dart), usagesLensExtension()],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await settle();
|
||||
expect(ipc.lspReferences.mock.calls.map((c) => c[2])).toEqual([
|
||||
{ line: 0, col: 0 },
|
||||
{ line: 5, col: 0 },
|
||||
{ line: 6, col: 0 },
|
||||
]);
|
||||
expect(titles(view)).toEqual(["2 usages", "2 usages", "2 usages"]);
|
||||
});
|
||||
|
||||
it("asks Dart references one at a time", async () => {
|
||||
const pending = deferred<ReturnType<typeof refs>>();
|
||||
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
|
||||
ipc.lspReferences.mockReturnValue(pending.promise);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: Array.from({ length: 8 }, (_, i) => `void f${i}() {}`).join("\n"),
|
||||
extensions: [lspDoc.of(dart), usagesLensExtension()],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
|
||||
pending.resolve(refs(1));
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(8);
|
||||
});
|
||||
|
||||
it("does not start a new Dart references wave until a cancelled request has finished", async () => {
|
||||
const first = deferred<ReturnType<typeof refs>>();
|
||||
ipc.lspReferences.mockReturnValueOnce(first.promise).mockResolvedValue(refs(2));
|
||||
ipc.docOutline.mockResolvedValue(ok([item("loadData", "function", 0)]));
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "void loadData() {}",
|
||||
extensions: [lspDoc.of(dart), usagesLensExtension()],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
|
||||
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.dart", baseVersion: 1, version: 2, changes: [] });
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
|
||||
first.resolve(refs(1));
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
|
||||
expect(titles(view)).toEqual(["2 usages"]);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,11 @@
|
||||
* construction: only declarations in (and near) the viewport are counted, one
|
||||
* debounced pass after edits / scrolling, results cached per document text
|
||||
* and symbol until the project's documents change, and at most a few reference
|
||||
* requests in flight. Counts run the same references query the Find Usages
|
||||
* requests in flight. Dart is the exception: inherited Flutter lifecycle methods
|
||||
* (`@override build`, `initState`, …) resolve to the framework and a single
|
||||
* isolate cannot cancel `textDocument/references` promptly, so those methods are
|
||||
* skipped and remaining Dart counts run one at a time, never overlapping a
|
||||
* request that has not finished. Counts run the same references query the Find Usages
|
||||
* panel runs (including the plugin indexers' anchors), scoped to what the
|
||||
* server analyses: opening candidate files or the libraries for every count
|
||||
* would trigger expensive server analysis, so only an explicit Find Usages
|
||||
@@ -54,6 +58,8 @@ const LENS_KINDS = new Set<SymbolKind>([
|
||||
|
||||
const MAX_PER_PASS = 40;
|
||||
const CONCURRENCY = 4;
|
||||
/** The Dart analyzer is a single isolate; overlapping references stall completion. */
|
||||
const DART_CONCURRENCY = 1;
|
||||
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
|
||||
const MARGIN_LINES = 10;
|
||||
/**
|
||||
@@ -132,6 +138,46 @@ export function usagesLabel(n: number): string {
|
||||
return n === 1 ? tx("1 usage") : tx`${n} usages`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flutter / Dart `@override` lifecycle and Object methods. A references query
|
||||
* for any of them walks the framework (and the project) from the superclass.
|
||||
*/
|
||||
const DART_INHERITED_LIFECYCLE = new Set([
|
||||
"build",
|
||||
"createState",
|
||||
"initState",
|
||||
"dispose",
|
||||
"didUpdateWidget",
|
||||
"didChangeDependencies",
|
||||
"deactivate",
|
||||
"activate",
|
||||
"reassemble",
|
||||
"toString",
|
||||
"hashCode",
|
||||
"==",
|
||||
]);
|
||||
|
||||
/** Outline names for `operator ==` (`==`, `operator ==`). */
|
||||
function dartMethodName(name: string): string {
|
||||
return name.replace(/^operator\s+/, "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Code Vision should skip a usages query for this declaration: a Dart
|
||||
* method whose name is a framework lifecycle / Object member, with `@override`
|
||||
* on or just above the name. Exported for tests.
|
||||
*/
|
||||
export function skipInheritedLifecycleUsages(language: string, name: string, text: Text, line: number): boolean {
|
||||
if (language !== "dart") return false;
|
||||
if (!DART_INHERITED_LIFECYCLE.has(dartMethodName(name))) return false;
|
||||
const from = Math.max(1, line + 1 - 4);
|
||||
const to = Math.min(text.lines, line + 1);
|
||||
for (let n = from; n <= to; n++) {
|
||||
if (/@override\b/.test(text.line(n).text)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const setLenses = StateEffect.define<CodeLens[]>();
|
||||
|
||||
const lensField = StateField.define<CodeLens[]>({
|
||||
@@ -186,6 +232,11 @@ class UsagesLensPlugin {
|
||||
private skipped = false;
|
||||
/** A pass was cut short or held back by a foreground request, and runs once it is done. */
|
||||
private yielded = false;
|
||||
/** Reference requests still running on the server, including ones already cancelled. */
|
||||
private inflight = 0;
|
||||
/** A Dart pass is waiting for `inflight` to reach 0 before asking again. */
|
||||
private drain = false;
|
||||
private closed = false;
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
this.refresh();
|
||||
@@ -276,6 +327,11 @@ class UsagesLensPlugin {
|
||||
this.yielded = true;
|
||||
return;
|
||||
}
|
||||
// Dart's analyzer does not cancel promptly; a new wave on top of a cancelled one stalls it.
|
||||
if (doc.language === "dart" && this.inflight > 0) {
|
||||
this.drain = true;
|
||||
return;
|
||||
}
|
||||
const gen = this.generation;
|
||||
const usagesWanted = usagesEnabled() && !isLibrarySource(doc);
|
||||
const usages = usagesWanted && !usagesBackoff.active(doc.doc);
|
||||
@@ -307,20 +363,30 @@ class UsagesLensPlugin {
|
||||
.filter((t) => t.line >= firstLine && t.line <= lastLine)
|
||||
.slice(0, MAX_PER_PASS);
|
||||
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
|
||||
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
|
||||
const todo = usages
|
||||
? visible.filter(
|
||||
(t) =>
|
||||
!this.cache.has(key(t)) &&
|
||||
!this.incomplete.has(key(t)) &&
|
||||
!skipInheritedLifecycleUsages(doc.language, t.name, text, t.line),
|
||||
)
|
||||
: [];
|
||||
let unavailable = false;
|
||||
let retry = false;
|
||||
// A base file is outlined once per pass, however many of its methods are overridden here.
|
||||
const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]);
|
||||
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
|
||||
const concurrency = doc.language === "dart" ? DART_CONCURRENCY : CONCURRENCY;
|
||||
for (let i = 0; i < todo.length && !unavailable; i += concurrency) {
|
||||
if (inForeground()) {
|
||||
this.yielded = true;
|
||||
return;
|
||||
}
|
||||
if (!wanted()) return;
|
||||
// oxlint-disable-next-line no-await-in-loop -- batched in groups of CONCURRENCY; a batch's flags decide whether the next batch runs
|
||||
await Promise.all(
|
||||
todo.slice(i, i + CONCURRENCY).map(async (t) => {
|
||||
todo.slice(i, i + concurrency).map(async (t) => {
|
||||
const request = nextRequestId();
|
||||
this.inflight++;
|
||||
try {
|
||||
// Opening candidate files for each count triggers expensive server analysis.
|
||||
// Only an explicit Find Usages should widen the server's scope.
|
||||
@@ -351,6 +417,11 @@ class UsagesLensPlugin {
|
||||
if (wanted() && isUnavailable(e)) unavailable = true;
|
||||
} finally {
|
||||
this.pending.delete(request);
|
||||
this.inflight--;
|
||||
if (this.inflight === 0 && this.drain && !this.closed) {
|
||||
this.drain = false;
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -425,6 +496,7 @@ class UsagesLensPlugin {
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.closed = true;
|
||||
this.schedule.cancel();
|
||||
this.unsubscribe();
|
||||
this.offReady();
|
||||
|
||||
@@ -91,6 +91,7 @@ import { imageSrc } from "./imageActions";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import styles from "./Composer.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
|
||||
const MAX_ITEMS = 12;
|
||||
const MAX_OPEN_EDITORS = 5;
|
||||
@@ -1063,7 +1064,7 @@ export function Composer(props: ComposerProps) {
|
||||
setFileOver(false);
|
||||
if (p.type !== "drop" || !p.paths.length || !inBox(p.position)) return;
|
||||
const paths: string[] = [];
|
||||
for (const path of p.paths) {
|
||||
for (const path of p.paths.map(ipcPath)) {
|
||||
if (IMAGE_EXTENSIONS.test(path)) {
|
||||
void invokeLocal<string>("fs_read_image", { path }).then(
|
||||
(url) => {
|
||||
|
||||
@@ -20,7 +20,17 @@ import { formatDuration, formatSentAt, userMessageText } from "../conversation";
|
||||
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
|
||||
import { isBusy, recoveryDividerLabel, type ReplyTimes, type ReplyTurn } from "../model";
|
||||
import { useRevealedText } from "../reveal";
|
||||
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
|
||||
import {
|
||||
composerDraft,
|
||||
forkTask,
|
||||
refreshProviders,
|
||||
rerunFrom,
|
||||
resendMessage,
|
||||
retrySubmittedDraft,
|
||||
submittedDraft,
|
||||
updateComposer,
|
||||
useAgents,
|
||||
} from "../store";
|
||||
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
|
||||
import { providerName, samePropsExcept, type UserEntry } from "./shared";
|
||||
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
|
||||
@@ -242,17 +252,68 @@ export const Entry = memo(
|
||||
}),
|
||||
);
|
||||
|
||||
/** Offers recovery for the current writer conflict without replacing the saved conversation. */
|
||||
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const [recovering, setRecovering] = useState(false);
|
||||
const text = useAgentErrorText(message);
|
||||
const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false);
|
||||
const entries = useAgents((s) => s.entries.get(task.id));
|
||||
const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message);
|
||||
const locked =
|
||||
task.provider === "codex" &&
|
||||
task.status === "failed" &&
|
||||
task.error === message &&
|
||||
message.includes("already has an active writer");
|
||||
const lastUser = locked
|
||||
? entries?.findLast((entry): entry is UserEntry => entry.type === "user" && !entry.steered)
|
||||
: undefined;
|
||||
const name = providerName(task.provider);
|
||||
// Restore the unsent message alongside any text typed since the failed attempt.
|
||||
const recover = async (fork: boolean) => {
|
||||
setRecovering(true);
|
||||
try {
|
||||
const original =
|
||||
(lastUser && submittedDraft(task.id, lastUser.text)) ??
|
||||
(lastUser ? { text: lastUser.text, images: lastUser.images ?? [], files: [] } : undefined);
|
||||
if (!fork) {
|
||||
if (original) await retrySubmittedDraft(task.id, original);
|
||||
return;
|
||||
}
|
||||
const target = await forkTask(task.id, null);
|
||||
if (target && original) {
|
||||
const draft = composerDraft(task.id);
|
||||
updateComposer(target, {
|
||||
text: [original.text, draft.text].filter(Boolean).join("\n"),
|
||||
files: [...original.files, ...draft.files],
|
||||
images: [...original.images, ...draft.images],
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: fork ? "Couldn't fork the task" : "Couldn't retry the message",
|
||||
body: String(error),
|
||||
});
|
||||
} finally {
|
||||
setRecovering(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={styles.error} role="alert">
|
||||
<Icon name="error" size={14} />
|
||||
<div className={styles.errorContent}>
|
||||
<span>{text}</span>
|
||||
{locked && (
|
||||
<div>
|
||||
<Button size="small" disabled={recovering || !lastUser} onClick={() => void recover(false)}>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
<Button size="small" disabled={recovering} onClick={() => void recover(true)}>
|
||||
<T>Fork</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{canSignIn && (
|
||||
<div>
|
||||
<Button size="small" onClick={() => setSigningIn(true)}>
|
||||
|
||||
@@ -59,6 +59,8 @@ const backend = vi.hoisted(() => ({
|
||||
}>,
|
||||
imported: [] as Array<[string, string]>,
|
||||
forked: [] as Array<[string, string, string]>,
|
||||
retryPrompt: vi.fn(),
|
||||
forkTask: vi.fn(),
|
||||
importError: null as string | null,
|
||||
importErrors: new Map<string, string>(),
|
||||
importWait: null as Promise<void> | null,
|
||||
@@ -78,6 +80,8 @@ const backend = vi.hoisted(() => ({
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
commands: {
|
||||
agentPrompt: backend.retryPrompt,
|
||||
agentFork: backend.forkTask,
|
||||
fsProbe: async () => ({
|
||||
status: "ok",
|
||||
data: { size: 1, binary: false, tooLarge: false },
|
||||
@@ -284,6 +288,8 @@ beforeEach(() => {
|
||||
useChangesOptions.setState({ groupByCommit: false, scope: "task" });
|
||||
backend.imported = [];
|
||||
backend.forked = [];
|
||||
backend.retryPrompt.mockReset().mockResolvedValue({ status: "ok", data: null });
|
||||
backend.forkTask.mockReset().mockResolvedValue({ status: "ok", data: task("forked") });
|
||||
backend.importError = null;
|
||||
backend.importErrors = new Map();
|
||||
backend.importWait = null;
|
||||
@@ -315,6 +321,25 @@ beforeEach(() => {
|
||||
});
|
||||
});
|
||||
|
||||
it("offers recovery for a Codex writer conflict and keeps the failed message in a fork", async () => {
|
||||
const message = "thread s1 already has an active writer";
|
||||
const failed: AgentTask = { ...task("A"), status: "failed", error: message };
|
||||
const entries: AgentEntry[] = [
|
||||
{ type: "user", text: "Please continue", attachments: [], images: [], steered: false, sentMs: null, doneMs: null },
|
||||
{ type: "error", message },
|
||||
];
|
||||
backend.entries.set("A", entries);
|
||||
useAgents.setState({ tasks: new Map([["A", failed]]), entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
|
||||
await waitFor(() =>
|
||||
expect(backend.retryPrompt).toHaveBeenCalledWith("A", expect.objectContaining({ text: "Please continue" }), false),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Fork" }));
|
||||
await waitFor(() => expect(backend.forkTask).toHaveBeenCalledWith("A", null));
|
||||
await waitFor(() => expect(useAgents.getState().composers.get("forked")?.text).toBe("Please continue"));
|
||||
});
|
||||
|
||||
describe("conversation rows", () => {
|
||||
it("keeps authors above messages and their folded work with matching icon-only actions", async () => {
|
||||
const user = (text: string): AgentEntry => ({
|
||||
|
||||
@@ -1729,6 +1729,21 @@ export function trackNetworkOnline(): () => void {
|
||||
return () => window.removeEventListener("online", onOnline);
|
||||
}
|
||||
|
||||
// A failed session open happens after submission; keep file paths for an explicit recovery.
|
||||
const submittedDrafts = new Map<string, { draft: ComposerDraft; prompt: AgentPrompt }>();
|
||||
|
||||
/** Returns the latest submitted draft while this window is alive, including file paths. */
|
||||
export function submittedDraft(task: string, text: string): ComposerDraft | undefined {
|
||||
const submitted = submittedDrafts.get(task);
|
||||
return submitted?.prompt.text === text ? submitted.draft : undefined;
|
||||
}
|
||||
|
||||
/** Retries the original prompt without consuming a newer composer draft. */
|
||||
export async function retrySubmittedDraft(task: string, draft: ComposerDraft): Promise<void> {
|
||||
const submitted = submittedDrafts.get(task);
|
||||
await call(commands.agentPrompt(task, submitted?.draft === draft ? submitted.prompt : promptOf(task, draft), false));
|
||||
}
|
||||
|
||||
/** Sends the session composer's message: queued while the agent works, or with `now` interrupting it. */
|
||||
export async function sendMessage(task: string, now: boolean): Promise<void> {
|
||||
const composer = composerDraft(task);
|
||||
@@ -1736,7 +1751,9 @@ export async function sendMessage(task: string, now: boolean): Promise<void> {
|
||||
const command = shellCommand(composer);
|
||||
if (command !== null) return runShell(task, composer, command);
|
||||
const started = generation;
|
||||
await call(commands.agentPrompt(task, promptOf(task, composer), now));
|
||||
const prompt = promptOf(task, composer);
|
||||
await call(commands.agentPrompt(task, prompt, now));
|
||||
submittedDrafts.set(task, { draft: composer, prompt });
|
||||
clearSubmittedComposer(task, composer, started);
|
||||
}
|
||||
|
||||
@@ -1752,7 +1769,7 @@ export function quoteInComposer(task: string, text: string) {
|
||||
}
|
||||
|
||||
/** Copies the task's conversation into a new task (up to its first `turns` turns) and opens it. */
|
||||
export async function forkTask(task: string, turns: number | null): Promise<void> {
|
||||
export async function forkTask(task: string, turns: number | null): Promise<string | undefined> {
|
||||
const started = generation;
|
||||
try {
|
||||
const copy = await call(commands.agentFork(task, turns));
|
||||
@@ -1761,6 +1778,7 @@ export async function forkTask(task: string, turns: number | null): Promise<void
|
||||
tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
|
||||
}));
|
||||
openTask(copy.id);
|
||||
return copy.id;
|
||||
} catch (e) {
|
||||
if (generation === started) throw e;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import {
|
||||
connect,
|
||||
disconnect,
|
||||
forkTask,
|
||||
retrySubmittedDraft,
|
||||
sendMessage,
|
||||
startTask,
|
||||
submittedDraft,
|
||||
updateComposer,
|
||||
updateDraft,
|
||||
useAgents,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
const backend = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
fork: vi.fn(),
|
||||
prompt: vi.fn(),
|
||||
subscribe: vi.fn(),
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
@@ -36,6 +40,7 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
commands: {
|
||||
agentCreate: backend.create,
|
||||
agentFork: backend.fork,
|
||||
agentPrompt: backend.prompt,
|
||||
agentSubscribe: backend.subscribe,
|
||||
agentProviders: async () => ({ status: "ok", data: [] }),
|
||||
},
|
||||
@@ -112,6 +117,20 @@ beforeEach(() => {
|
||||
});
|
||||
afterEach(() => disconnect());
|
||||
|
||||
it("retains the submitted file paths for retry without consuming a newer draft", async () => {
|
||||
backend.prompt.mockResolvedValue(ok(null));
|
||||
updateComposer("source", { text: "inspect", files: [{ path: "/project-a/a.txt", rel: "a.txt", attached: true }] });
|
||||
await sendMessage("source", false);
|
||||
const sent = backend.prompt.mock.calls[0]![1];
|
||||
const original = submittedDraft("source", sent.text)!;
|
||||
expect(original.files[0]?.path).toBe("/project-a/a.txt");
|
||||
updateComposer("source", { text: "new draft" });
|
||||
await retrySubmittedDraft("source", original);
|
||||
expect(backend.prompt.mock.calls[1]![1]).toEqual(sent);
|
||||
expect(composerDraft("source").text).toBe("new draft");
|
||||
expect(submittedDraft("source", "a different message")).toBeUndefined();
|
||||
});
|
||||
|
||||
const transitions = [
|
||||
"disconnect",
|
||||
"reconnect",
|
||||
|
||||
@@ -147,6 +147,90 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("ProjectView", () => {
|
||||
describe("Java class names", () => {
|
||||
const source = `${ROOT}/src/main/java`;
|
||||
const testSource = `${ROOT}/src/test/java`;
|
||||
const generated = `${ROOT}/generated`;
|
||||
const resources = `${source}/resources`;
|
||||
const foo = `${source}/Foo.java`;
|
||||
const labels = [
|
||||
[foo, "Foo"],
|
||||
[`${testSource}/FooTest.java`, "FooTest"],
|
||||
[`${generated}/生成$2.java`, "生成$2"],
|
||||
[`${resources}/Foo.java`, "Foo.java"],
|
||||
[`${ROOT}/Foo.java`, "Foo.java"],
|
||||
[`${source}/package-info.java`, "package-info.java"],
|
||||
[`${source}/my-file.java`, "my-file.java"],
|
||||
[`${source}/class.java`, "class.java"],
|
||||
[`${source}/Util.kt`, "Util.kt"],
|
||||
[`${source}/folder.java`, "folder.java"],
|
||||
] as const;
|
||||
|
||||
beforeEach(() => {
|
||||
fs = new MemoryFs(Object.fromEntries(labels.map(([path]) => [path, "x"])), ROOT);
|
||||
fs.nodes.set(`${source}/folder.java`, { kind: "dir" });
|
||||
setProjectFsForTests(fs, ROOT);
|
||||
useProject.setState({
|
||||
settings: {
|
||||
projectStructure: {
|
||||
sourceRoots: ["src/main/java", "generated"],
|
||||
testRoots: ["src/test/java"],
|
||||
resourceRoots: ["src/main/java/resources"],
|
||||
},
|
||||
},
|
||||
});
|
||||
initProjectTree(ROOT, "acme");
|
||||
setViewOption("compact", false);
|
||||
useProjectTree.setState({
|
||||
expanded: new Set([
|
||||
ROOT,
|
||||
`${ROOT}/src`,
|
||||
`${ROOT}/src/main`,
|
||||
`${ROOT}/src/test`,
|
||||
source,
|
||||
testSource,
|
||||
generated,
|
||||
resources,
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
const content = (tree: HTMLElement, path: string) => tree.querySelector(`[data-project-path="${path}"]`);
|
||||
|
||||
it("shortens valid Java filenames in source roots and preserves the other row names", async () => {
|
||||
const { tree } = setup();
|
||||
await waitFor(() => {
|
||||
for (const [path, label] of labels) expect(content(tree, path)?.textContent).toBe(label);
|
||||
});
|
||||
expect(content(tree, foo)).toHaveAttribute("data-project-icon", "file-java");
|
||||
});
|
||||
|
||||
it("uses the displayed names for speed search", async () => {
|
||||
const { tree } = setup();
|
||||
await waitFor(() => expect(content(tree, foo)?.textContent).toBe("Foo"));
|
||||
await waitFor(() => expect(content(tree, `${ROOT}/Foo.java`)?.textContent).toBe("Foo.java"));
|
||||
const sourceRow = content(tree, foo)!.closest('[role="treeitem"]');
|
||||
fireEvent.mouseDown(sourceRow!);
|
||||
act(() => tree.focus());
|
||||
for (const key of "Foo") fireEvent.keyDown(tree, { key });
|
||||
expect(sourceRow).toHaveAttribute("aria-selected", "true");
|
||||
expect(sourceRow?.querySelector("mark")).toHaveTextContent("Foo");
|
||||
for (const key of ".java") fireEvent.keyDown(tree, { key });
|
||||
expect(sourceRow).toHaveAttribute("aria-selected", "false");
|
||||
expect(tree.querySelector('[aria-selected="true"]')).toHaveTextContent("Foo.java");
|
||||
});
|
||||
|
||||
it("starts inline rename with the full filename and selects the stem", async () => {
|
||||
const { tree } = setup();
|
||||
await waitFor(() => expect(content(tree, foo)?.textContent).toBe("Foo"));
|
||||
act(() => beginRename(selectModel(useProjectTree.getState()).byKey.get(foo)!));
|
||||
const name = await screen.findByRole<HTMLInputElement>("textbox", { name: "New name" });
|
||||
expect(name).toHaveValue("Foo.java");
|
||||
expect(name.selectionStart).toBe(0);
|
||||
expect(name.selectionEnd).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles Unity metadata and generated files independently in the rendered tree", async () => {
|
||||
fs = new MemoryFs(
|
||||
{
|
||||
|
||||
@@ -28,8 +28,8 @@ import { tx, useTxTemplate } from "@/platform/i18n";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { canDragOut, dragOut, isDraggingOut } from "@/platform/dragOut";
|
||||
import { nativeDropPoint } from "@/platform/nativeDrop";
|
||||
import { validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
|
||||
import { useDetectedRoots, useEffectiveRoots } from "@/platform/projectRoots";
|
||||
import { rootFor, validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
|
||||
import { useDetectedRoots, useEffectiveRoots, useProjectRoots } from "@/platform/projectRoots";
|
||||
import { macStroke, strokeOf } from "@/platform/keymap";
|
||||
import {
|
||||
OWNS_FILE_DROP,
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
type TreeRowState,
|
||||
} from "@/ui";
|
||||
import { badgeKind } from "@/ui/symbolKind";
|
||||
import { projectScopeForPath } from "@/ui/folderPresentation";
|
||||
import { isConfiguredLibraryDirectory, prepareLibraryTargets } from "./addLibrary";
|
||||
import { contextMenuItems, menuGroupContext, newMenuItems } from "./contextMenu";
|
||||
import { openNewPopup } from "./newPopupModel";
|
||||
@@ -100,7 +101,7 @@ import {
|
||||
targetFolder,
|
||||
undoLastFileOperation,
|
||||
} from "./operations";
|
||||
import { isInside, nameOf, parentOf, splitExtension, tildify } from "./paths";
|
||||
import { isInside, isJavaIdentifier, nameOf, parentOf, relativeTo, splitExtension, tildify } from "./paths";
|
||||
import {
|
||||
VIEW_MODES,
|
||||
autoExpand,
|
||||
@@ -165,8 +166,8 @@ export function showQuickPreview(path?: string): boolean {
|
||||
}
|
||||
|
||||
const getKey = (n: ProjectNode) => n.key;
|
||||
const getLabel = (n: ProjectNode) =>
|
||||
n.placeholder || n.member ? n.label : (getFileDecoration(n.path)?.label ?? n.label);
|
||||
const decoratedLabel = (n: ProjectNode, fallback = n.label) =>
|
||||
n.placeholder || n.member ? n.label : (getFileDecoration(n.path)?.label ?? fallback);
|
||||
|
||||
function iconFor(
|
||||
node: ProjectNode,
|
||||
@@ -318,6 +319,7 @@ export function formatFileDetails(entry: Pick<FileEntry, "size" | "mtimeMs"> | n
|
||||
|
||||
interface RowProps {
|
||||
node: ProjectNode;
|
||||
label: string;
|
||||
matches: number[] | null;
|
||||
editing: Editing | null;
|
||||
cut: boolean;
|
||||
@@ -336,6 +338,7 @@ const holdsOpenFile = (dir: string, files: readonly string[]) =>
|
||||
|
||||
const Row = memo(function Row({
|
||||
node,
|
||||
label,
|
||||
matches,
|
||||
editing,
|
||||
cut,
|
||||
@@ -383,7 +386,6 @@ const Row = memo(function Row({
|
||||
const faded = node.ignored || deco.faded || unavailable;
|
||||
// IDEA dims the icon of excluded folders only; git-ignored ones just get the ignored colour.
|
||||
const dimIcon = node.excluded || unavailable;
|
||||
const label = deco.label ?? node.label;
|
||||
const showUnavailableDetail = unavailable && node.root && !node.icon;
|
||||
const detailTitle = showUnavailableDetail
|
||||
? detail
|
||||
@@ -445,7 +447,7 @@ const Row = memo(function Row({
|
||||
deco.error && styles.error,
|
||||
)}
|
||||
style={!unavailable && deco.color ? { color: deco.color } : undefined}
|
||||
text={label}
|
||||
text={deco.label ?? label}
|
||||
indices={matches}
|
||||
tone="accent"
|
||||
/>
|
||||
@@ -572,9 +574,11 @@ export function ProjectView() {
|
||||
const txTemplate = useTxTemplate();
|
||||
// Rows compute their file icons while rendering: redraw when the icon theme changes.
|
||||
useFileIconRevision();
|
||||
// Display aliases (data source names for console folders) also decide sibling order.
|
||||
// Decoration aliases (data source names for console folders) also decide sibling order.
|
||||
const decorationProviders = useFileDecorations((s) => s.providers);
|
||||
const root = useProjectTree((s) => s.root);
|
||||
const roots = useEffectiveRoots();
|
||||
const attached = useProjectRoots((s) => (s.root === root ? s.attached : undefined));
|
||||
const model = useProjectTree(selectModel);
|
||||
const fileColors = useFileColors("projectView");
|
||||
const expanded = useProjectTree((s) => s.expanded);
|
||||
@@ -591,6 +595,21 @@ export function ProjectView() {
|
||||
const [drag, setDrag] = useState<DragState | null>(null);
|
||||
const revealing = useRef(false);
|
||||
|
||||
const fileLabel = useCallback(
|
||||
(node: ProjectNode) => {
|
||||
if (node.dir || node.group || node.member || node.placeholder || !node.label.endsWith(".java")) return node.label;
|
||||
const [stem] = splitExtension(node.label);
|
||||
if (!isJavaIdentifier(stem)) return node.label;
|
||||
const { ownerRoot, ownerRoots } = projectScopeForPath(node.path, root, roots, undefined, attached);
|
||||
if (!ownerRoot || !isInside(node.path, ownerRoot)) return node.label;
|
||||
const kind = rootFor(ownerRoots, relativeTo(ownerRoot, parentOf(node.path)))?.kind;
|
||||
return kind === "source" || kind === "test" ? stem : node.label;
|
||||
},
|
||||
[root, roots, attached],
|
||||
);
|
||||
|
||||
const getLabel = useCallback((node: ProjectNode) => decoratedLabel(node, fileLabel(node)), [fileLabel]);
|
||||
|
||||
const info = useMemo(() => visibleInfo(model, expanded), [model, expanded]);
|
||||
const mode = useProjectTree((s) => s.mode);
|
||||
const unity = useProjectTree((s) => s.unity);
|
||||
@@ -685,10 +704,10 @@ export function ProjectView() {
|
||||
!children ||
|
||||
!decorationProviders.size ||
|
||||
options.sortBy !== "name" ||
|
||||
!children.some((child) => getLabel(child) !== child.label)
|
||||
!children.some((child) => decoratedLabel(child) !== child.label)
|
||||
)
|
||||
return children;
|
||||
const labels = new Map(children.map((child) => [child, getLabel(child)]));
|
||||
const labels = new Map(children.map((child) => [child, decoratedLabel(child)]));
|
||||
return [...children].sort((a, b) => {
|
||||
if (!!a.placeholder !== !!b.placeholder) return a.placeholder ? -1 : 1;
|
||||
if (options.foldersFirst && a.dir !== b.dir) return a.dir ? -1 : 1;
|
||||
@@ -1044,6 +1063,7 @@ export function ProjectView() {
|
||||
) : (
|
||||
<Row
|
||||
node={node}
|
||||
label={fileLabel(node)}
|
||||
matches={state.matches}
|
||||
editing={editing}
|
||||
cut={cutPaths.has(node.path)}
|
||||
@@ -1061,6 +1081,7 @@ export function ProjectView() {
|
||||
/>
|
||||
),
|
||||
[
|
||||
fileLabel,
|
||||
editing,
|
||||
cutPaths,
|
||||
dropTarget,
|
||||
|
||||
@@ -352,6 +352,16 @@ describe("OS file imports", () => {
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names a file dropped from Windows by its file name, not its whole path", async () => {
|
||||
const imported = vi.spyOn(fs, "importLocal").mockResolvedValueOnce([]);
|
||||
await importExternal(["E:\\Users\\me\\Downloads\\gdb-18.1.tar.gz"], "/p/target");
|
||||
expect(imported).toHaveBeenCalledWith(
|
||||
"E:/Users/me/Downloads/gdb-18.1.tar.gz",
|
||||
"/p/target/gdb-18.1.tar.gz",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports skipped entries while keeping the imported folder", async () => {
|
||||
vi.spyOn(fs, "importLocal").mockResolvedValueOnce(["bundle/pipe: skipped special file"]);
|
||||
expect(await transfer(["/bundle"], "/p/target", "copy", undefined, "local")).toBe("/p/target/bundle");
|
||||
|
||||
@@ -23,6 +23,7 @@ import { renameCopiedJavaType } from "./javaCopy";
|
||||
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
|
||||
import { currentRoots } from "@/platform/projectRoots";
|
||||
import { notifyFileOperation } from "@/platform/fileOps";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { IpcError, isCancelled, isTauri } from "@/platform/ipc";
|
||||
import { MEMBER_PREFIX, type ProjectNode } from "./model";
|
||||
import {
|
||||
@@ -1015,6 +1016,8 @@ export async function dropPaths(paths: string[], target: string, copy: boolean)
|
||||
export async function importExternal(paths: string[], target: string) {
|
||||
const { root } = get();
|
||||
if (!root || !paths.length || isReadOnlyPath(target)) return;
|
||||
// The OS reports Windows paths as `E:\\dir\\file`; entries are named from `/`-separated paths.
|
||||
paths = paths.map(ipcPath);
|
||||
if (isRemoteWindow()) return void (await transfer(paths, target, "copy", undefined, "local"));
|
||||
const inside = paths.filter((p) => isSameOrInside(p, root));
|
||||
const outside = paths.filter((p) => !isSameOrInside(p, root));
|
||||
|
||||
@@ -190,6 +190,14 @@ const JAVA_KEYWORDS = new Set(
|
||||
"true try void volatile while"
|
||||
).split(" "),
|
||||
);
|
||||
|
||||
const JAVA_IDENTIFIER = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
||||
|
||||
/** A name a Java type can take (what IDEA shows as a class node instead of `Name.java`). */
|
||||
export function isJavaIdentifier(name: string): boolean {
|
||||
return name !== "_" && !JAVA_KEYWORDS.has(name) && JAVA_IDENTIFIER.test(name);
|
||||
}
|
||||
|
||||
const PY_KEYWORDS = new Set(
|
||||
(
|
||||
"False None True and as assert async await break class continue def del elif else except finally for from " +
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { formParams, withParams } from "@/features/run/types";
|
||||
import { hostOs } from "@/platform/remote";
|
||||
import { dockerfileType, dockerImageType, typedConfig } from "./runTypes";
|
||||
|
||||
vi.mock("@/platform/remote", async (original) => ({
|
||||
...(await original<typeof import("@/platform/remote")>()),
|
||||
hostOs: vi.fn(),
|
||||
}));
|
||||
|
||||
const dockerfileParams = {
|
||||
dockerfile: "docker files/Dockerfile",
|
||||
tag: "sample/app:latest",
|
||||
target: "production",
|
||||
buildArgs: "MODE=production",
|
||||
buildOptions: "--no-cache",
|
||||
runImage: "true",
|
||||
containerName: "sample-app",
|
||||
ports: "8080:80",
|
||||
volumes: "./app data:/data",
|
||||
containerEnv: "MODE=production",
|
||||
runOptions: "--network bridge",
|
||||
command: 'serve --title "Sample app"',
|
||||
};
|
||||
|
||||
const imageParams = {
|
||||
image: "registry.example.com/team/postgres:16",
|
||||
pull: "true",
|
||||
ports: "5432:5432",
|
||||
containerEnv: "APP_NAME=Local database",
|
||||
};
|
||||
|
||||
const foregroundSettings: Record<string, string>[] = [{}, { detach: "false" }];
|
||||
|
||||
describe.each([
|
||||
{
|
||||
os: "linux" as const,
|
||||
build:
|
||||
"docker build -f 'docker files/Dockerfile' -t sample/app:latest --target production --build-arg MODE=production --no-cache 'docker files'",
|
||||
buildOnly: "docker build -f 'docker files/Dockerfile' -t sample/app:latest 'docker files'",
|
||||
remove: ">/dev/null 2>&1;",
|
||||
appArgs: "-p 8080:80 -v './app data:/data' -e MODE=production --network bridge sample/app:latest",
|
||||
imageArgs: "--pull always -p 5432:5432 -e 'APP_NAME=Local database' registry.example.com/team/postgres:16",
|
||||
},
|
||||
{
|
||||
os: "windows" as const,
|
||||
build:
|
||||
'docker build -f "docker files/Dockerfile" -t sample/app:latest --target production --build-arg MODE=production --no-cache "docker files"',
|
||||
buildOnly: 'docker build -f "docker files/Dockerfile" -t sample/app:latest "docker files"',
|
||||
remove: ">nul 2>&1 &",
|
||||
appArgs: '-p 8080:80 -v "./app data:/data" -e MODE=production --network bridge sample/app:latest',
|
||||
imageArgs: '--pull always -p 5432:5432 -e "APP_NAME=Local database" registry.example.com/team/postgres:16',
|
||||
},
|
||||
])("Docker run command lines on $os", ({ os, build, buildOnly, remove, appArgs, imageArgs }) => {
|
||||
beforeEach(() => vi.mocked(hostOs).mockReturnValue(os));
|
||||
|
||||
it.each(foregroundSettings)("runs a Dockerfile in the foreground with %j", (detach) => {
|
||||
expect(dockerfileType.commandLine({ ...dockerfileParams, ...detach })).toEqual({
|
||||
command: `${build} && (docker rm -f sample-app ${remove} docker run --name sample-app ${appArgs} serve --title "Sample app")`,
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: "docker stop sample-app",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(foregroundSettings)("runs a Docker Image in the foreground with %j", (detach) => {
|
||||
expect(dockerImageType.commandLine({ ...imageParams, ...detach })).toEqual({
|
||||
command: `(docker rm -f postgres ${remove} docker run --name postgres ${imageArgs})`,
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: "docker stop postgres",
|
||||
});
|
||||
});
|
||||
|
||||
it("runs the built image in the background and follows its logs", () => {
|
||||
expect(dockerfileType.commandLine({ ...dockerfileParams, detach: "true" })).toEqual({
|
||||
command: `${build} && (docker rm -f sample-app ${remove} docker run -d --name sample-app ${appArgs} serve --title "Sample app") && docker logs --tail 500 -f sample-app`,
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("runs a Docker Image in the background and follows logs using its derived name", () => {
|
||||
expect(dockerImageType.commandLine({ ...imageParams, containerName: " ", detach: "true" })).toEqual({
|
||||
command: `(docker rm -f postgres ${remove} docker run -d --name postgres ${imageArgs}) && docker logs --tail 500 -f postgres`,
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("builds without starting a container when Run built image is off", () => {
|
||||
expect(
|
||||
dockerfileType.commandLine({
|
||||
dockerfile: dockerfileParams.dockerfile,
|
||||
tag: dockerfileParams.tag,
|
||||
detach: "true",
|
||||
}),
|
||||
).toEqual({ command: buildOnly, args: [], cwd: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Docker detach setting", () => {
|
||||
beforeEach(() => vi.mocked(hostOs).mockReturnValue("linux"));
|
||||
|
||||
it("offers the checkbox only when the configuration starts a container", () => {
|
||||
const dockerfile = dockerfileType.fields.find((field) => field.key === "detach");
|
||||
const image = dockerImageType.fields.find((field) => field.key === "detach");
|
||||
const checkbox = { label: "Run in the background (-d)", control: "checkbox" };
|
||||
expect(dockerfile).toMatchObject(checkbox);
|
||||
expect(dockerfile?.visible?.({ runImage: "true" })).toBe(true);
|
||||
expect(dockerfile?.visible?.({ runImage: "false" })).toBe(false);
|
||||
expect(image).toMatchObject(checkbox);
|
||||
expect(image?.visible).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ type: dockerfileType, params: dockerfileParams, name: "sample-app" },
|
||||
{ type: dockerImageType, params: imageParams, name: "postgres" },
|
||||
])("round-trips detach through saved $type.label params and the run form", ({ type, params, name }) => {
|
||||
const foreground = typedConfig(type, "user:docker", "Docker", params);
|
||||
expect(foreground.stopCommand).toBe(`docker stop ${name}`);
|
||||
|
||||
const detached = withParams(foreground, { ...params, detach: "true" }, type);
|
||||
expect(detached.params?.detach).toBe("true");
|
||||
expect(detached.stopCommand).toBeUndefined();
|
||||
|
||||
const reopened = formParams(detached, type)!;
|
||||
expect(reopened.detach).toBe("true");
|
||||
expect(withParams(detached, reopened, type)).toEqual(detached);
|
||||
expect(withParams(detached, { ...reopened, detach: "false" }, type)).toEqual({
|
||||
...foreground,
|
||||
params: { ...params, detach: "false" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,8 @@
|
||||
* Dockerfile (build the image, then run a container from it), Docker Image (run
|
||||
* a container from an image) and Docker Compose (`up` the selected services).
|
||||
* They launch docker command lines in the Run tool window against the Docker
|
||||
* connection chosen from the Services tool window's connections; Stop stops the
|
||||
* container (`docker stop`) or takes the Compose project down.
|
||||
* connection chosen from the Services tool window's connections. Stop stops the
|
||||
* attached container or takes the Compose project down. Detached containers keep running.
|
||||
*/
|
||||
import { splitCommandLine } from "@/platform/commandLine";
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
@@ -62,21 +62,23 @@ export function containerName(p: Readonly<Record<string, string>>, image: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a previous container of the same name (IDEA redeploys over it), then runs
|
||||
* the new one attached, so its output is the run's output.
|
||||
* Redeploys a container of the same name. Detached runs follow the new container's logs.
|
||||
*/
|
||||
function runContainer(name: string, image: string, p: Readonly<Record<string, string>>, windows: boolean): string {
|
||||
const remove = `${line(["docker", "rm", "-f", name], windows)} ${windows ? ">nul 2>&1 &" : ">/dev/null 2>&1;"}`;
|
||||
const detach = on(p.detach);
|
||||
const run = [
|
||||
"docker",
|
||||
"run",
|
||||
...(detach ? ["-d"] : []),
|
||||
"--name",
|
||||
name,
|
||||
...(on(p.pull) ? ["--pull", "always"] : []),
|
||||
...containerArgs(p),
|
||||
image,
|
||||
];
|
||||
return `${remove} ${line([...run], windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""}`;
|
||||
const redeploy = `(${remove} ${line(run, windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""})`;
|
||||
return detach ? `${redeploy} && ${line(["docker", "logs", "--tail", "500", "-f", name], windows)}` : redeploy;
|
||||
}
|
||||
|
||||
/** The servers the form offers: the saved connections, else the default daemon ("Docker"). */
|
||||
@@ -97,8 +99,11 @@ const connectionField = {
|
||||
},
|
||||
};
|
||||
|
||||
const detachField = { key: "detach", label: "Run in the background (-d)", control: "checkbox" } as const;
|
||||
|
||||
const containerFields: RunConfigTypeContribution["fields"] = [
|
||||
{ key: "containerName", label: "Container name", mono: true, placeholder: "Derived from the image" },
|
||||
detachField,
|
||||
{ key: "ports", label: "Bind ports", mono: true, placeholder: "8080:80, 5005:5005" },
|
||||
{ key: "volumes", label: "Bind mounts", mono: true, placeholder: "./data:/data; cache:/root/.cache" },
|
||||
{ key: "containerEnv", label: "Container environment", mono: true, placeholder: "KEY=value; OTHER=value" },
|
||||
@@ -191,10 +196,10 @@ export const dockerfileType: RunConfigTypeContribution = {
|
||||
if (!on(p.runImage)) return { command: line(build, windows), args: [], cwd: null };
|
||||
const name = containerName(p, tag);
|
||||
return {
|
||||
command: `${line(build, windows)} && (${runContainer(name, tag, p, windows)})`,
|
||||
command: `${line(build, windows)} && ${runContainer(name, tag, p, windows)}`,
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: line(["docker", "stop", name], windows),
|
||||
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
|
||||
};
|
||||
},
|
||||
prepareLaunch: withConnection,
|
||||
@@ -221,10 +226,10 @@ export const dockerImageType: RunConfigTypeContribution = {
|
||||
const image = p.image?.trim() ?? "";
|
||||
const name = containerName(p, image);
|
||||
return {
|
||||
command: `(${runContainer(name, image, p, windows)})`,
|
||||
command: runContainer(name, image, p, windows),
|
||||
args: [],
|
||||
cwd: null,
|
||||
stop: line(["docker", "stop", name], windows),
|
||||
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
|
||||
};
|
||||
},
|
||||
prepareLaunch: withConnection,
|
||||
@@ -249,7 +254,7 @@ export const dockerComposeType: RunConfigTypeContribution = {
|
||||
},
|
||||
{ key: "services", label: "Services", mono: true, placeholder: "All services" },
|
||||
{ key: "project", label: "Project name", mono: true, placeholder: "The folder name" },
|
||||
{ key: "detach", label: "Run in the background (-d)", control: "checkbox" },
|
||||
detachField,
|
||||
{ key: "build", label: "Build images before starting (--build)", control: "checkbox" },
|
||||
{ key: "upOptions", label: "Up options", mono: true, placeholder: "e.g. --force-recreate --remove-orphans" },
|
||||
],
|
||||
|
||||
@@ -15,57 +15,9 @@ import { choosePath } from "@/platform/choosePath";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
import { PathField, PathInput } from "./PathInput";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
interface PathFieldProps {
|
||||
k: string;
|
||||
placeholder: string;
|
||||
title: string;
|
||||
id?: string;
|
||||
"aria-label"?: string;
|
||||
/** Browse for a file instead of a directory. */
|
||||
file?: boolean;
|
||||
}
|
||||
|
||||
function PathField({ k, placeholder, title, id, file, ...aria }: PathFieldProps) {
|
||||
const [value, set] = useSetting<string>(k);
|
||||
return (
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => set(e.target.value.trim())}
|
||||
aria-label={aria["aria-label"]}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: !file, title, defaultPath: value || undefined });
|
||||
if (p) set(p);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function PathInput({
|
||||
label,
|
||||
hint,
|
||||
...field
|
||||
}: Omit<PathFieldProps, "id" | "aria-label"> & { label: string; hint?: string }) {
|
||||
const id = useId();
|
||||
return (
|
||||
<Row label={label} htmlFor={id} hint={hint}>
|
||||
<PathField {...field} id={id} />
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
function SdkRow({
|
||||
k,
|
||||
label,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useId } from "react";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { IconButton, Input } from "@/ui";
|
||||
import { Row } from "../components/Form";
|
||||
import { useSetting } from "../components/context";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
interface PathFieldProps {
|
||||
k: string;
|
||||
placeholder: string;
|
||||
title: string;
|
||||
id?: string;
|
||||
"aria-label"?: string;
|
||||
/** Browse for a file instead of a directory. */
|
||||
file?: boolean;
|
||||
}
|
||||
|
||||
export function PathField({ k, placeholder, title, id, file, ...aria }: PathFieldProps) {
|
||||
const [value, set] = useSetting<string>(k);
|
||||
const tx = useTx();
|
||||
return (
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => set(e.target.value.trim())}
|
||||
aria-label={aria["aria-label"]}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: !file, title: tx(title), defaultPath: value || undefined });
|
||||
if (p) set(p);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function PathInput({
|
||||
label,
|
||||
hint,
|
||||
...field
|
||||
}: Omit<PathFieldProps, "id" | "aria-label"> & { label: string; hint?: string }) {
|
||||
const id = useId();
|
||||
return (
|
||||
<Row label={label} htmlFor={id} hint={hint}>
|
||||
<PathField {...field} id={id} />
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { useProject } from "@/platform/project";
|
||||
import type { SelectOption } from "@/ui";
|
||||
import { ColorSwatches, FormGroup, GlobListEditor, Row, SettingNumber, Toggle } from "../components/Form";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { PathInput } from "../languages/PathInput";
|
||||
import { useSettingsDialog } from "../model/staging";
|
||||
import { lazyPage } from "./lazyPage";
|
||||
import type { PageSpec } from "./spec";
|
||||
@@ -25,6 +26,35 @@ export const BUILD_GROUP = "Build, Execution, Deployment";
|
||||
|
||||
const L = WORKFLOW_LIMITS;
|
||||
|
||||
const gdbLabel = "GDB executable";
|
||||
const lldbDapLabel = "LLDB DAP executable";
|
||||
|
||||
function GdbExecutable() {
|
||||
return (
|
||||
<PathInput
|
||||
k="debugger.cpp.gdbExecutable"
|
||||
label={gdbLabel}
|
||||
title={gdbLabel}
|
||||
placeholder="Auto"
|
||||
hint="Requires GDB 14 or newer. Leave blank for automatic discovery."
|
||||
file
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LldbDapExecutable() {
|
||||
return (
|
||||
<PathInput
|
||||
k="debugger.cpp.lldbDapExecutable"
|
||||
label={lldbDapLabel}
|
||||
title={lldbDapLabel}
|
||||
placeholder="Auto"
|
||||
hint="Leave blank for automatic discovery."
|
||||
file
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const CONSOLE_ENCODINGS: SelectOption[] = [
|
||||
"UTF-8",
|
||||
"UTF-16LE",
|
||||
@@ -382,6 +412,13 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "C/C++",
|
||||
options: [
|
||||
{ kind: "custom", label: gdbLabel, component: GdbExecutable },
|
||||
{ kind: "custom", label: lldbDapLabel, component: LldbDapExecutable },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -186,6 +186,13 @@ describe("show diff from the annotate gutter", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("opens at the clicked line's place in the commit's version of the file", async () => {
|
||||
await showRevisionDiff("/repo/a.py", sha, 100);
|
||||
expect(mocks.openDiff).toHaveBeenCalledWith(expect.objectContaining({ line: 100, lineSide: "right" }), {
|
||||
preview: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the file as added when the commit added it", async () => {
|
||||
mocks.commitFiles.mockResolvedValue({ status: "ok", data: [{ path: "a.py", kind: "added", oldPath: null }] });
|
||||
await showRevisionDiff("/repo/a.py", sha);
|
||||
|
||||
@@ -117,9 +117,10 @@ export async function annotatePreviousRevision(path: string, commit: string): Pr
|
||||
/**
|
||||
* The annotate gutter's Show Diff (IDEA's): what `commit` changed in the file, against its first
|
||||
* parent, so a file the commit added or renamed shows as such. The file's history gives its name
|
||||
* at that commit when it was renamed later.
|
||||
* at that commit when it was renamed later. `line` (0-based, in that commit's version of the file)
|
||||
* is where the diff opens: the change the clicked line came from, as IDEA scrolls to it.
|
||||
*/
|
||||
export async function showRevisionDiff(path: string, commit: string): Promise<void> {
|
||||
export async function showRevisionDiff(path: string, commit: string, line?: number | null): Promise<void> {
|
||||
const repo = repoOf(path) ?? currentRepoRoot();
|
||||
if (!repo) return;
|
||||
const relative = relativePath(ipcPath(repo).replace(/\/$/, ""), ipcPath(path));
|
||||
@@ -142,7 +143,8 @@ export async function showRevisionDiff(path: string, commit: string): Promise<vo
|
||||
if (!found) return;
|
||||
const name = (found === inHistory && found.historyPath) || relative;
|
||||
const changed = files.find((f) => f.path === name) ?? { path: name, kind: "modified", oldPath: null };
|
||||
await openDiff(commitFileDiffData({ ...found, repo }, changed), { preview: false });
|
||||
const data = commitFileDiffData({ ...found, repo }, changed);
|
||||
await openDiff(line == null ? data : { ...data, line, lineSide: "right" }, { preview: false });
|
||||
} catch (e) {
|
||||
notifyFailure(e, tx("Could not show diff"));
|
||||
}
|
||||
|
||||
@@ -665,7 +665,10 @@ function blameExtension(lines: BlameLine[], source: BlameSource): Extension {
|
||||
{
|
||||
label: "Show Diff",
|
||||
icon: "diff",
|
||||
run: () => void import("./annotateRevision").then((m) => m.showRevisionDiff(origin, l.commit)),
|
||||
run: () =>
|
||||
void import("./annotateRevision").then((m) =>
|
||||
m.showRevisionDiff(origin, l.commit, l.originLine),
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Copy Revision Number",
|
||||
|
||||
@@ -16,6 +16,7 @@ import { ProjectsPage } from "./ProjectsPage";
|
||||
import { loadRecent, useRecent } from "./recent";
|
||||
import { cancelReopen, useSession } from "./session";
|
||||
import styles from "./Welcome.module.css";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
|
||||
export type WelcomePage = "projects" | "customize" | "plugins";
|
||||
|
||||
@@ -102,7 +103,7 @@ function useFolderDrop(): boolean {
|
||||
setOver(false);
|
||||
const { project, lightEdit } = useProject.getState();
|
||||
if (p.type === "drop" && p.paths.length && !project && !lightEdit)
|
||||
void executeAction("file.openPaths", p.paths);
|
||||
void executeAction("file.openPaths", p.paths.map(ipcPath));
|
||||
})
|
||||
.then((u) => {
|
||||
if (disposed) u();
|
||||
|
||||
@@ -790,7 +790,7 @@
|
||||
"Add Maven Projects": "新增 Maven 專案",
|
||||
"Choose one or more pom.xml files inside or outside the opened project. The opened folder stays the project root.": "選擇開啟專案之內或之外的一個或多個 pom.xml。開啟的資料夾仍是專案根。",
|
||||
"Import Module from Existing Sources": "匯入已有模組",
|
||||
"Choose a module directory. A pom.xml is linked as a Maven project and a Gradle settings or build script as a Gradle build; a folder with neither is attached as another root. The opened folder stays the project root, and no build file is edited.": "選擇模組目錄。有 pom.xml 時作為 Maven 專案連結,有 Gradle settings 或建置指令碼時作為 Gradle 建置連結;兩者都沒有的資料夾作為另一個根附加。開啟的資料夾仍是專案根目錄,不會修改任何建置檔案。",
|
||||
"Choose a module directory. A pom.xml is linked as a Maven project and a Gradle settings or build script as a Gradle build; a folder with neither is attached as another root. In a window with several projects, the directory is attached as another project. The opened folder stays the project root, and no build file is edited.": "選擇模組目錄。有 pom.xml 時作為 Maven 專案連結,有 Gradle settings 或建置指令碼時作為 Gradle 建置連結;兩者都沒有的資料夾作為另一個根附加。在包含多個專案的視窗中,該目錄會作為另一個專案附加。開啟的資料夾仍是專案根目錄,不會修改任何建置檔案。",
|
||||
"Some Maven projects were not added": "部分 Maven 專案未能新增",
|
||||
"These files are not named pom.xml, so they were not added: {join}{more}": "這些檔案不叫 pom.xml,因此未新增:{join}{more}",
|
||||
"Unlink Maven Projects": "取消連結 Maven 專案",
|
||||
@@ -1344,6 +1344,10 @@
|
||||
"Debug views": "偵錯檢視",
|
||||
"Debuggable configurations": "可偵錯的組態",
|
||||
"Debugger": "偵錯工具",
|
||||
"GDB executable": "GDB 執行檔",
|
||||
"LLDB DAP executable": "LLDB DAP 執行檔",
|
||||
"Requires GDB 14 or newer. Leave blank for automatic discovery.": "需要 GDB 14 或更新版本。留空則自動尋找。",
|
||||
"Leave blank for automatic discovery.": "留空則自動尋找。",
|
||||
"Debugger actions": "偵錯工具操作",
|
||||
"Debugger is not available": "偵錯工具不可用",
|
||||
"Debugging": "正在偵錯",
|
||||
|
||||
@@ -1250,7 +1250,7 @@
|
||||
"Add Maven Projects": "添加 Maven 项目",
|
||||
"Choose one or more pom.xml files inside or outside the opened project. The opened folder stays the project root.": "选择打开项目之内或之外的一个或多个 pom.xml。打开的文件夹仍是项目根。",
|
||||
"Import Module from Existing Sources": "导入已有模块",
|
||||
"Choose a module directory. A pom.xml is linked as a Maven project and a Gradle settings or build script as a Gradle build; a folder with neither is attached as another root. The opened folder stays the project root, and no build file is edited.": "选择模块目录。有 pom.xml 时作为 Maven 项目链接,有 Gradle settings 或构建脚本时作为 Gradle 构建链接;两者都没有的文件夹作为另一个根附加。打开的文件夹仍是项目根目录,不会修改任何构建文件。",
|
||||
"Choose a module directory. A pom.xml is linked as a Maven project and a Gradle settings or build script as a Gradle build; a folder with neither is attached as another root. In a window with several projects, the directory is attached as another project. The opened folder stays the project root, and no build file is edited.": "选择模块目录。有 pom.xml 时作为 Maven 项目链接,有 Gradle settings 或构建脚本时作为 Gradle 构建链接;两者都没有的文件夹作为另一个根附加。在包含多个项目的窗口中,该目录会作为另一个项目附加。打开的文件夹仍是项目根目录,不会修改任何构建文件。",
|
||||
"Some Maven projects were not added": "部分 Maven 项目未能添加",
|
||||
"These files are not named pom.xml, so they were not added: {join}{more}": "这些文件不叫 pom.xml,因此未添加:{join}{more}",
|
||||
"Unlink Maven Projects": "取消链接 Maven 项目",
|
||||
@@ -1849,6 +1849,10 @@
|
||||
"Debug views": "调试视图",
|
||||
"Debuggable configurations": "可调试的配置",
|
||||
"Debugger": "调试器",
|
||||
"GDB executable": "GDB 可执行文件",
|
||||
"LLDB DAP executable": "LLDB DAP 可执行文件",
|
||||
"Requires GDB 14 or newer. Leave blank for automatic discovery.": "需要 GDB 14 或更高版本。留空则自动查找。",
|
||||
"Leave blank for automatic discovery.": "留空则自动查找。",
|
||||
"Debugger actions": "调试器操作",
|
||||
"Debugger is not available": "调试器不可用",
|
||||
"Debugging": "正在调试",
|
||||
|
||||
@@ -130,6 +130,16 @@ describe("validateWorkflow", () => {
|
||||
expect(validateWorkflow({ debugger: { hotSwapAfterCompile: "invalid" } }).debugger.hotSwapAfterCompile).toBe("ask");
|
||||
});
|
||||
|
||||
it("defaults C/C++ debugger paths to empty and accepts absolute and relative paths", () => {
|
||||
const defaults = { gdbExecutable: "", lldbDapExecutable: "" };
|
||||
expect(validateWorkflow({}).debugger.cpp).toEqual(defaults);
|
||||
expect(
|
||||
validateWorkflow({ debugger: { cpp: { gdbExecutable: 14, lldbDapExecutable: null } } }).debugger.cpp,
|
||||
).toEqual(defaults);
|
||||
const cpp = { gdbExecutable: "tools/gdb-16", lldbDapExecutable: "/opt/LLVM Tools/lldb-dap" };
|
||||
expect(validateWorkflow({ debugger: { cpp } }).debugger.cpp).toEqual(cpp);
|
||||
});
|
||||
|
||||
it("falls back to defaults for missing or malformed values", () => {
|
||||
expect(validateWorkflow(undefined)).toEqual(DEFAULT_WORKFLOW);
|
||||
const v = validateWorkflow({
|
||||
|
||||
@@ -161,6 +161,7 @@ export interface DebuggerSettingsValid {
|
||||
flutterHotReloadOnSave: boolean;
|
||||
hotSwapAfterCompile: HotSwapPolicy;
|
||||
python: { attachSubprocess: boolean; gevent: boolean };
|
||||
cpp: { gdbExecutable: string; lldbDapExecutable: string };
|
||||
}
|
||||
|
||||
export interface RunSettingsValid {
|
||||
@@ -424,6 +425,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
|
||||
debugServerPage: false,
|
||||
flutterHotReloadOnSave: true,
|
||||
hotSwapAfterCompile: "ask",
|
||||
cpp: { gdbExecutable: "", lldbDapExecutable: "" },
|
||||
python: { attachSubprocess: true, gevent: false },
|
||||
},
|
||||
run: {
|
||||
@@ -624,6 +626,7 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid {
|
||||
const d = DEFAULT_WORKFLOW.debugger;
|
||||
const v = obj(raw);
|
||||
const py = obj(v.python);
|
||||
const cpp = obj(v.cpp);
|
||||
return {
|
||||
showOnBreakpoint: bool(v.showOnBreakpoint, d.showOnBreakpoint),
|
||||
focusAppOnBreakpoint: bool(v.focusAppOnBreakpoint, d.focusAppOnBreakpoint),
|
||||
@@ -645,6 +648,10 @@ export function validateDebugger(raw: unknown): DebuggerSettingsValid {
|
||||
attachSubprocess: bool(py.attachSubprocess, d.python.attachSubprocess),
|
||||
gevent: bool(py.gevent, d.python.gevent),
|
||||
},
|
||||
cpp: {
|
||||
gdbExecutable: text(cpp.gdbExecutable, d.cpp.gdbExecutable),
|
||||
lldbDapExecutable: text(cpp.lldbDapExecutable, d.cpp.lldbDapExecutable),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача