дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
19
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
0301d2407d | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 | ||
|
|
6d38521498 | ||
|
|
52e6a0f84b | ||
|
|
72873981aa | ||
|
|
d44a104ff8 | ||
|
|
23ea9cf07d | ||
|
|
cea3f4ac9c | ||
|
|
aee715f797 | ||
|
|
711349c6c1 | ||
|
|
9b2d783322 | ||
|
|
72ae354d29 |
No files matched your search
@@ -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"
|
||||
|
||||
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
|
||||
"get_repositories",
|
||||
"Retrieves the list of VCS roots in the project.
|
||||
This is useful to detect all repositories in a multi-repository project.
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
|
||||
rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
|
||||
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
|
||||
|call| async move {
|
||||
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
|
||||
let list: Vec<Value> = roots
|
||||
@@ -117,6 +117,9 @@ rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
if let Some(op) = r.operation {
|
||||
v["operationInProgress"] = op.into();
|
||||
}
|
||||
if r.unavailable {
|
||||
v["unavailable"] = true.into();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -256,10 +259,10 @@ By default all Git repositories are returned.",
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
let host = call.host();
|
||||
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
@@ -271,12 +274,25 @@ By default all Git repositories are returned.",
|
||||
};
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
|
||||
repos
|
||||
.into_iter()
|
||||
.filter(|(_, (_, unavailable))| !unavailable)
|
||||
.map(|(root, (head, _))| (root, head))
|
||||
.collect()
|
||||
} else {
|
||||
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for path in targets {
|
||||
// The innermost repository containing the path.
|
||||
let repo = match innermost_repo(repos.clone(), &path) {
|
||||
Some(repo) => repo,
|
||||
Some((root, (_, true))) => {
|
||||
if wanted.is_some() {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Git repository '{}' is currently unavailable",
|
||||
relative_to_project(&call, &root)
|
||||
)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some((root, (head, false))) => (root, head),
|
||||
None => match find_git_root(call.root(), &path) {
|
||||
Some(root) => {
|
||||
// JetBrains reads the branch of any repository it reports.
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
mod kotlin;
|
||||
#[cfg(test)]
|
||||
mod kotlin_tests;
|
||||
#[cfg(test)]
|
||||
mod native_tests;
|
||||
mod output;
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{DebugSessionId, IdeResult};
|
||||
use ide_dap::*;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
#[command(trust = trusted)]
|
||||
@@ -143,8 +145,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
|
||||
if config.adapter == "lldb-dap" {
|
||||
let (root, settings) = (root.clone(), settings.clone());
|
||||
let project_root = project.root.clone();
|
||||
config = ide_dap::native::choose(config, move |command| {
|
||||
ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
native_debugger_command(&project_root, &settings.debugger.cpp, command)
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
|
||||
})
|
||||
.await?;
|
||||
@@ -161,11 +165,13 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
.await?;
|
||||
}
|
||||
let java_analyzer = java_analyzer_command(host, window, &config)?;
|
||||
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
|
||||
let custom = |command: &str| {
|
||||
if let Some(binary) = java_analyzer {
|
||||
return Some(binary.to_string_lossy().into_owned());
|
||||
}
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
let path = native
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
@@ -197,6 +203,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
result
|
||||
}
|
||||
|
||||
fn native_debugger_command(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::CppDebuggerSettings,
|
||||
adapter: &str,
|
||||
) -> Option<PathBuf> {
|
||||
let path = match adapter {
|
||||
"gdb" => &settings.gdb_executable,
|
||||
"lldb-dap" => &settings.lldb_dap_executable,
|
||||
_ => return None,
|
||||
};
|
||||
ide_sdk::apply::setting_path(root, path)
|
||||
}
|
||||
|
||||
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
|
||||
/// (`projectRoot`, else the working directory), so the session debugs with the server that
|
||||
/// analyzes the code.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::*;
|
||||
use ide_core::IdeError;
|
||||
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
|
||||
use ide_workspace::SettingsScope;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
|
||||
|
||||
impl AdapterLauncher for CaptureAdapter {
|
||||
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
|
||||
*self.0.lock() = Some(spec);
|
||||
Box::pin(async { Err(IdeError::cancelled()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cpp_debugger_paths_override_adapter_commands() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let cwd = root.join("build");
|
||||
std::fs::create_dir_all(&cwd).unwrap();
|
||||
let capture = Arc::new(CaptureAdapter::default());
|
||||
let mut host = Host::new(crate::HostConfig::for_test(&base));
|
||||
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
|
||||
for (adapter, key, configured) in [
|
||||
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
|
||||
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
|
||||
] {
|
||||
let config = LaunchConfig {
|
||||
name: "C++".into(),
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(cwd.clone().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(r#"{"pid":1}"#.into()),
|
||||
};
|
||||
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
|
||||
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
|
||||
|
||||
project
|
||||
.settings
|
||||
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
|
||||
.unwrap();
|
||||
let mut config = config;
|
||||
config.request = "launch".into();
|
||||
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
|
||||
config.extra_json = None;
|
||||
let _ = debug_start(&host, "main", config).await.unwrap_err();
|
||||
let spec = capture.0.lock().take().unwrap();
|
||||
assert_eq!(spec.adapter, adapter);
|
||||
assert_eq!(Path::new(&spec.command), root.join(configured));
|
||||
assert_eq!(spec.cwd, cwd);
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,10 @@ pub struct VcsRoot {
|
||||
/// Conflicts staged during the current operation that can be reopened.
|
||||
#[serde(default)]
|
||||
pub resolved_conflicts: Vec<ide_core::IpcPath>,
|
||||
/// The repository's worktree or git directory is missing or on an unmounted volume.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub unavailable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -531,6 +535,23 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<Path
|
||||
blocking(move || project.detected_repository_roots()).await
|
||||
}
|
||||
|
||||
fn unavailable_vcs_root(root: &Path) -> VcsRoot {
|
||||
VcsRoot {
|
||||
root: root.into(),
|
||||
branch_root: root.into(),
|
||||
operation: None,
|
||||
interactive_rebase: false,
|
||||
head: None,
|
||||
head_commit: None,
|
||||
shallow: false,
|
||||
lfs: false,
|
||||
uninitialized_submodules: Vec::new(),
|
||||
has_remotes: None,
|
||||
resolved_conflicts: Vec::new(),
|
||||
unavailable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
@@ -541,10 +562,17 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
let primary = repos.primary().map(|r| r.root().to_path_buf());
|
||||
let mut all: Vec<_> = repos.all().iter().collect();
|
||||
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
|
||||
let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect();
|
||||
let roots: Vec<_> = all
|
||||
.into_iter()
|
||||
.map(|repo| {
|
||||
let dirs = repo.check_valid().ok().and_then(|()| repo.metadata_dirs().ok());
|
||||
let available = dirs.is_some() && !repo.is_stale();
|
||||
(repo, available, dirs)
|
||||
})
|
||||
.collect();
|
||||
let mut branch_roots = std::collections::HashMap::new();
|
||||
for (repo, dirs) in &roots {
|
||||
if let Some([git_dir, common_dir]) = dirs {
|
||||
for (repo, available, dirs) in &roots {
|
||||
if *available && let Some([git_dir, common_dir]) = dirs {
|
||||
let first = branch_roots.entry(common_dir).or_insert(repo.root());
|
||||
if git_dir == common_dir {
|
||||
*first = repo.root();
|
||||
@@ -553,7 +581,10 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
}
|
||||
Ok(roots
|
||||
.iter()
|
||||
.map(|(r, dirs)| {
|
||||
.map(|(r, available, dirs)| {
|
||||
if !available {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir));
|
||||
let (head, head_commit) = r.head().unwrap_or_default();
|
||||
let operation = r.operation().ok().flatten();
|
||||
@@ -565,6 +596,11 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let has_remotes = trusted.then(|| r.has_remotes().ok()).flatten();
|
||||
let shallow = r.is_shallow().unwrap_or(false);
|
||||
if r.is_stale() {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
VcsRoot {
|
||||
root: r.root().into(),
|
||||
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
|
||||
@@ -572,7 +608,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
interactive_rebase,
|
||||
head,
|
||||
head_commit,
|
||||
shallow: r.is_shallow().unwrap_or(false),
|
||||
shallow,
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
@@ -580,8 +616,9 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.iter()
|
||||
.map(|path| ide_core::ipc_path::to_ipc(path))
|
||||
.collect(),
|
||||
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
|
||||
has_remotes,
|
||||
resolved_conflicts,
|
||||
unavailable: false,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
|
||||
@@ -572,3 +572,60 @@ async fn a_repository_created_in_the_project_is_known_when_init_returns() {
|
||||
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
|
||||
assert_eq!(roots, [project_root]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn vcs_roots_reports_unavailable_root_until_it_returns() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let external_main = base.join("external-main");
|
||||
let wt = project_root.join("wt");
|
||||
let healthy = project_root.join("healthy");
|
||||
for root in [&external_main, &healthy] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("file.txt"), "hello\n").unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
}
|
||||
git(&external_main, &["worktree", "add", "-b", "wt-branch", wt.to_str().unwrap()]);
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
|
||||
// Move the linked worktree's metadata dir (outside project_root) aside so the project FileWatcher never races.
|
||||
let wt_git_dir = external_main.join(".git/worktrees/wt");
|
||||
let parked_git_dir = base.join("parked-wt-git");
|
||||
std::fs::rename(&wt_git_dir, &parked_git_dir).unwrap();
|
||||
|
||||
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_root = roots.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_root = roots.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(wt_root.unavailable);
|
||||
assert!(wt_root.head.is_none());
|
||||
assert!(wt_root.head_commit.is_none());
|
||||
assert!(wt_root.operation.is_none());
|
||||
assert!(wt_root.has_remotes.is_none());
|
||||
assert_eq!(wt_root.branch_root.0, wt);
|
||||
assert!(!healthy_root.unavailable);
|
||||
assert_eq!(healthy_root.head.as_deref(), Some("main"));
|
||||
|
||||
std::fs::rename(&parked_git_dir, &wt_git_dir).unwrap();
|
||||
let restored = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_restored = restored.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_restored = restored.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(!wt_restored.unavailable);
|
||||
assert_eq!(wt_restored.head.as_deref(), Some("wt-branch"));
|
||||
assert!(!healthy_restored.unavailable);
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -105,16 +105,26 @@ fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
|
||||
|
||||
pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
let start = if path.is_file() { path.parent().unwrap_or(path) } else { path };
|
||||
if let Err(e) = gix::discover::upwards(start) {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. } | E::NoGitRepositoryWithinCeiling { .. } | E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
let ts = gix::ThreadSafeRepository::discover(start).map_err(gx)?;
|
||||
let found = match gix::discover::upwards(start) {
|
||||
Ok((found, _trust)) => found,
|
||||
Err(e) => {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. }
|
||||
| E::NoGitRepositoryWithinCeiling { .. }
|
||||
| E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
};
|
||||
// Opened like `gix()` reopens it, not with `ThreadSafeRepository::discover`: that picks the
|
||||
// options for the folder owner's trust, and for a repository another user owns (reduced trust)
|
||||
// they cap the object database at 32 pack indices. A repository with more packs then fails to
|
||||
// read any object, so `HEAD` doesn't resolve (#7138). Trust is still decided per repository.
|
||||
let (git_dir, worktree) = found.into_repository_and_work_tree_directories();
|
||||
let ts = gix::ThreadSafeRepository::open(worktree.unwrap_or(git_dir)).map_err(gx)?;
|
||||
let repo = ts.to_thread_local();
|
||||
let Some(workdir) = repo.workdir() else {
|
||||
// Bare repositories have no worktree to show changes for.
|
||||
@@ -178,7 +188,7 @@ impl Repo {
|
||||
/// Verifies that the worktree root and its git directory exist on disk. A missing one marks
|
||||
/// the repository stale and is logged once; when both are back (a drive reconnected, `git
|
||||
/// worktree repair`), the mark is cleared, so a stale repository costs two `stat`s per check.
|
||||
pub(crate) fn check_valid(&self) -> IdeResult<()> {
|
||||
pub fn check_valid(&self) -> IdeResult<()> {
|
||||
use std::sync::atomic::Ordering;
|
||||
if self.root.is_dir() && self.git_dir.is_dir() {
|
||||
if self.stale.swap(false, Ordering::AcqRel) {
|
||||
@@ -658,6 +668,53 @@ mod tests {
|
||||
assert!(cmd.status().unwrap().success(), "{cmd:?}");
|
||||
}
|
||||
|
||||
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
|
||||
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
|
||||
/// pack directory: objects in every pack stay readable through the cached handle.
|
||||
#[test]
|
||||
fn a_repository_with_many_packs_reads_objects_from_all_of_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("repo");
|
||||
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
|
||||
let git = |args: &[&str]| {
|
||||
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}");
|
||||
String::from_utf8(out.stdout).unwrap().trim().to_owned()
|
||||
};
|
||||
git(&["config", "gc.auto", "0"]);
|
||||
git(&["config", "maintenance.auto", "false"]);
|
||||
let mut oids = Vec::new();
|
||||
for i in 0..40 {
|
||||
std::fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", &format!("c{i}")]);
|
||||
oids.push(git(&["rev-parse", "HEAD"]));
|
||||
let mut pack = Command::new("git")
|
||||
.current_dir(&root)
|
||||
.args(["pack-objects", "-q", "--revs", ".git/objects/pack/pack"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
use std::io::Write;
|
||||
let range = if i == 0 { "HEAD\n" } else { "HEAD\n^HEAD~1\n" };
|
||||
pack.stdin.take().unwrap().write_all(range.as_bytes()).unwrap();
|
||||
assert!(pack.wait().unwrap().success());
|
||||
git(&["prune-packed"]);
|
||||
}
|
||||
let packs = std::fs::read_dir(root.join(".git/objects/pack"))
|
||||
.unwrap()
|
||||
.filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|x| x == "idx"))
|
||||
.count();
|
||||
assert!(packs > 32, "{packs} pack indices");
|
||||
let repo = discover(&root).unwrap().unwrap();
|
||||
let gix = repo.gix().unwrap();
|
||||
assert_eq!(gix.head_id().unwrap().to_string(), *oids.last().unwrap());
|
||||
for oid in &oids {
|
||||
gix.find_commit(gix::ObjectId::from_hex(oid.as_bytes()).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a remounted volume looks like: every path and modification time is the same, but
|
||||
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
|
||||
#[test]
|
||||
|
||||
@@ -287,6 +287,7 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
|
||||
time_ms: now,
|
||||
summary: String::new(),
|
||||
origin_path: None,
|
||||
origin_line: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -278,7 +278,7 @@ Retention is set in the **Local History** section of **Settings › Appearance &
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Commit** | Non-modal commit interface, clearing the message after commit, message inspections (blank line after subject, subject and body length, right margin), default commit checks. |
|
||||
| **Confirmation** | What to do when files are created or deleted, **Show options before Update**, confirm before dropping commits, highlight modified folders in the Project view, history row limit. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. Unreachable mapped repositories are marked unavailable while other repositories keep working. |
|
||||
| **Issue Navigation** | Regex patterns that turn issue IDs in commit messages into links (presets for JIRA, YouTrack and GitHub). |
|
||||
| **Log** | Reference and time display, visible columns. |
|
||||
| **Shelf** | Remove applied files from the shelf. |
|
||||
|
||||
@@ -276,7 +276,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **提交** | 非模态提交界面、提交后清空消息、提交消息检查(主题与正文之间空行、主题和正文长度、右边距)、默认提交检查。 |
|
||||
| **确认** | 新建或删除文件时的处理方式、**更新前显示选项**、丢弃提交前确认、在项目视图中高亮包含修改的目录、历史记录行数上限。 |
|
||||
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。 |
|
||||
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。无法访问的已映射仓库会被标记为不可用,其余仓库仍可继续使用。 |
|
||||
| **问题导航** | 把提交消息中的问题编号变成链接的正则规则(内置 JIRA、YouTrack 和 GitHub 预设)。 |
|
||||
| **日志** | 引用和时间的显示方式、显示哪些列。 |
|
||||
| **搁置** | 应用后从搁置中移除文件。 |
|
||||
|
||||
@@ -362,6 +362,41 @@ test("long Git Log filter values shorten inside their buttons", async ({ workben
|
||||
await expect(clear).toBeHidden();
|
||||
});
|
||||
|
||||
test("a click in the User filter shows only that user's commits, without check marks", async ({ workbench: page }) => {
|
||||
const alice = "Alice <[email protected]>";
|
||||
const bob = "Bob <[email protected]>";
|
||||
await page.evaluate(
|
||||
async ([alice, bob]) => {
|
||||
const optionsModule = "/src/features/vcs/logOptions.ts";
|
||||
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
|
||||
// Room for the User filter on the bar.
|
||||
setLogOptions({ showBranches: false, showDetails: false });
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_log_users = () => [alice, "Author <[email protected]>", bob];
|
||||
const log = h.vcs_log!;
|
||||
h.vcs_log = (args) => {
|
||||
(window as { logAuthors?: unknown }).logAuthors = (args.query as { authors: string[] }).authors;
|
||||
return log(args);
|
||||
};
|
||||
},
|
||||
[alice, bob],
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
|
||||
const user = toolbar.getByRole("button", { name: /^User/ });
|
||||
const item = (name: string) => page.getByRole("menuitem", { name, exact: true });
|
||||
const logAuthors = () => page.evaluate(() => (window as { logAuthors?: unknown }).logAuthors);
|
||||
|
||||
await user.click();
|
||||
await item(alice).click();
|
||||
await expect(user).toHaveText(`User: ${alice}`);
|
||||
await expect.poll(logAuthors).toEqual([alice]);
|
||||
await user.click();
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: alice, exact: true })).toHaveCount(0);
|
||||
await item(bob).click();
|
||||
await expect(user).toHaveText(`User: ${bob}`);
|
||||
await expect.poll(logAuthors).toEqual([bob]);
|
||||
});
|
||||
|
||||
test("Git Log puts affected changes on the changed-files toolbar and groups preview options", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -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. */
|
||||
@@ -16318,6 +16329,8 @@ export type VcsRoot = {
|
||||
hasRemotes?: boolean | null,
|
||||
/** Conflicts staged during the current operation that can be reopened. */
|
||||
resolvedConflicts?: IpcPath[],
|
||||
/** The repository's worktree or git directory is missing or on an unmounted volume. */
|
||||
unavailable?: boolean,
|
||||
};
|
||||
|
||||
/** Version Control (main page) and its sub-pages. */
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -540,6 +540,41 @@ describe("applying completions", () => {
|
||||
expect(a!.apply).not.toBe(b!.apply);
|
||||
});
|
||||
|
||||
it("completes a keyword rather than a declaration snippet with the same name", async () => {
|
||||
const { view } = setup("public interf| Demo {}");
|
||||
setInvokeRoute((cmd) => {
|
||||
if (cmd === "cancel_request") return Promise.resolve(null);
|
||||
if (cmd === "lsp_completion") {
|
||||
return Promise.resolve({
|
||||
isIncomplete: false,
|
||||
items: [
|
||||
item({ label: "interface", kind: "keyword", insertText: "interface" }),
|
||||
item({
|
||||
label: "interface",
|
||||
kind: "snippet",
|
||||
insertText: "public interface ${1:Demo} {\n\t$0\n}",
|
||||
isSnippet: true,
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
try {
|
||||
view.dispatch({
|
||||
effects: StateEffect.appendConfig.of([
|
||||
lspDoc.of({ doc: 7151, path: "/p/Demo.java", language: "java", uiMode: "Java", readOnly: false }),
|
||||
completionExtension(),
|
||||
]),
|
||||
});
|
||||
startCompletion(view);
|
||||
await vi.waitFor(() => expect(currentCompletions(view.state)).toHaveLength(1));
|
||||
expect((currentCompletions(view.state)[0] as unknown as { lsp: CompletionItem }).lsp.kind).toBe("keyword");
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("lists same-name Java imports from different packages", async () => {
|
||||
const { view } = setup("@RequestBod|");
|
||||
const packages = ["org.springframework.web.bind.annotation", "io.swagger.v3.oas.annotations.parameters"];
|
||||
|
||||
@@ -875,6 +875,10 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
|
||||
if (inVarCall(ctx)) items = items.filter((it) => !it.label.startsWith("--"));
|
||||
const pruned = pruneItems(items, typed);
|
||||
items = [...pruned.items];
|
||||
// A server snippet named like a keyword it also lists (jdtls `interface`, `class`, `enum` declaration
|
||||
// skeletons) would replace one word with a whole declaration; IDEA completes the keyword.
|
||||
const keywords = new Set(items.filter((it) => it.kind === "keyword").map((it) => it.label));
|
||||
if (keywords.size) items = items.filter((it) => it.kind !== "snippet" || !keywords.has(it.label));
|
||||
// A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins.
|
||||
if (items.some((it) => it.kind === "snippet")) {
|
||||
const own = await contributedSource(ctx);
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -317,10 +317,10 @@ export function activate(): () => void {
|
||||
id: "maven.importExternal",
|
||||
title: "Import Module from Existing Sources",
|
||||
description:
|
||||
"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.",
|
||||
"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.",
|
||||
category: "Maven",
|
||||
icon: "plus",
|
||||
when: "projectOpen && !workspaceOpen",
|
||||
when: "projectOpen",
|
||||
keywords: ["import", "module", "existing", "sources", "external", "maven", "pom", "gradle"],
|
||||
run: () => importModuleFromExistingSources(),
|
||||
},
|
||||
|
||||
@@ -324,6 +324,38 @@ it("attaches a module directory without a build file outside the project, after
|
||||
expect(mocks.link).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps Import Module from Existing Sources in a window with attached projects and attaches the directory", async () => {
|
||||
const attached = vi.fn();
|
||||
const off = registerAction({ id: "project.attachFolder", title: "Attach", run: ({ arg }) => attached(arg) });
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
project: { root: "/p", workspace: { version: 1, name: "p", projects: ["/p", "/code/web"] } } as ProjectInfo,
|
||||
}),
|
||||
);
|
||||
setContext("workspaceOpen", true);
|
||||
try {
|
||||
expect(isActionEnabled(allActions().find((a) => a.id === "maven.importExternal")!)).toBe(true);
|
||||
mocks.open.mockResolvedValue("/code/admin");
|
||||
await act(async () => {
|
||||
await executeAction("maven.importExternal");
|
||||
});
|
||||
expect(mocks.open).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "/p" }));
|
||||
expect(attached).toHaveBeenCalledWith("/code/admin");
|
||||
expect(mocks.confirm).not.toHaveBeenCalled();
|
||||
expect(mocks.set).not.toHaveBeenCalled();
|
||||
expect(mocks.link).not.toHaveBeenCalled();
|
||||
|
||||
attached.mockClear();
|
||||
mocks.open.mockResolvedValue("/code/web/src");
|
||||
await act(async () => {
|
||||
await executeAction("maven.importExternal");
|
||||
});
|
||||
expect(attached).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
|
||||
it("doesn't offer to attach a folder where another root can't be attached (a remote window)", async () => {
|
||||
const attached = vi.fn();
|
||||
const off = registerAction({
|
||||
|
||||
@@ -489,14 +489,36 @@ export async function moduleImportKind(
|
||||
* inside the project is already part of it.
|
||||
*/
|
||||
export async function importModuleFromExistingSources() {
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root || useProject.getState().project?.workspace || !isTauri()) return;
|
||||
const project = useProject.getState().project;
|
||||
const root = project?.root;
|
||||
if (!root || !isTauri()) return;
|
||||
const path = await choosePath({
|
||||
title: tx`Import Module from Existing Sources`,
|
||||
directory: true,
|
||||
defaultPath: root,
|
||||
defaultPath: project.workspace?.projects[0] ?? root,
|
||||
});
|
||||
if (!path) return;
|
||||
// A window with several projects has no single build to link into: each attached root is a
|
||||
// project with its own build, so the directory joins as another one, as Attach Project does.
|
||||
if (project.workspace) {
|
||||
const dir = lexicalPath(comparablePath(path)).replace(/\/$/, "");
|
||||
const inside = project.workspace.projects
|
||||
.map((p) => lexicalPath(comparablePath(p)).replace(/\/$/, ""))
|
||||
.find((p) => dir === p || isInsideRoot(p, dir));
|
||||
if (inside) {
|
||||
const name = dir.split("/").pop() || dir;
|
||||
notifications().notify({
|
||||
group: "tools",
|
||||
level: "info",
|
||||
title: tx`Already in the project`,
|
||||
body: tx`${name} is inside the opened project, so its sources are already part of it.`,
|
||||
key: "module-import-inside",
|
||||
});
|
||||
return;
|
||||
}
|
||||
await executeAction("project.attachFolder", path);
|
||||
return;
|
||||
}
|
||||
const found = await moduleImportKind(path);
|
||||
if (!found) {
|
||||
notifications().notify({
|
||||
|
||||
@@ -8,7 +8,7 @@ import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Button, Checkbox, Icon, IconButton, Input, Popup, SearchField, Select, Tabs, T, type MenuItem } from "@/ui";
|
||||
import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "./export";
|
||||
import { EXPORT_FORMATS, SQL_FORMATS, exportData, selectionWhere, type ExportData, type ExportFormat } from "./export";
|
||||
import { Grid, type CopyFormat, type GridColumn, type GridProps, type GridRange } from "./Grid";
|
||||
import type { Cell } from "./model";
|
||||
import {
|
||||
@@ -78,6 +78,30 @@ export interface ExtractorMenu {
|
||||
table: () => ExportData | null | Promise<ExportData | null>;
|
||||
}
|
||||
|
||||
async function copyRowsAs(extractor: ExtractorMenu, rows: readonly number[], format: ExportFormat) {
|
||||
const data = await Promise.resolve(extractor.table());
|
||||
if (!data) return;
|
||||
const picked = rows.flatMap((row) => (data.rows[row] ? [data.rows[row]] : []));
|
||||
if (picked.length) await writeClipboardText(exportData(format, { ...data, rows: picked }));
|
||||
}
|
||||
|
||||
async function copySelectionAs(
|
||||
extractor: ExtractorMenu,
|
||||
rows: readonly number[],
|
||||
cols: readonly number[],
|
||||
format: ExportFormat,
|
||||
) {
|
||||
const data = await Promise.resolve(extractor.table());
|
||||
if (!data) return;
|
||||
if (format === "where") {
|
||||
const text = selectionWhere(data, rows, cols);
|
||||
if (text) await writeClipboardText(text);
|
||||
return;
|
||||
}
|
||||
const picked = rows.flatMap((row) => (data.rows[row] ? [data.rows[row]] : []));
|
||||
if (picked.length) await writeClipboardText(exportData(format, { ...data, rows: picked }));
|
||||
}
|
||||
|
||||
const PANEL_ENTRIES: ReadonlyArray<{ panel: DataPanel; label: string }> = [
|
||||
{ panel: "record", label: "Show Record View" },
|
||||
{ panel: "value", label: "Open in Value Editor" },
|
||||
@@ -123,11 +147,7 @@ export function viewMenu(
|
||||
|
||||
/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */
|
||||
function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] {
|
||||
const copy = (format: ExportFormat) => () =>
|
||||
void Promise.resolve(extractor.table()).then((data) => {
|
||||
const picked = data && rows.flatMap((r) => (data.rows[r] ? [data.rows[r]] : []));
|
||||
if (picked?.length) void writeClipboardText(exportData(format, { ...data!, rows: picked }));
|
||||
});
|
||||
const copy = (format: ExportFormat) => () => void copyRowsAs(extractor, rows, format);
|
||||
return [
|
||||
{ label: "SQL INSERT", run: copy("sql") },
|
||||
{ label: "SQL UPDATE", run: copy("sqlUpdates") },
|
||||
@@ -242,6 +262,11 @@ export function DataView(props: DataViewProps) {
|
||||
}, [shaped, test, search.filterRows, rowCount, columns.length, value]);
|
||||
const at = (r: number) => (order ? order[r]! : r);
|
||||
const shown = order ? order.length : rowCount;
|
||||
const extractor = props.extractor;
|
||||
const copySelectedCells =
|
||||
extractor && SQL_FORMATS.has(extractor.value)
|
||||
? (rows: number[], cols: number[]) => void copySelectionAs(extractor, rows.map(at), cols, extractor.value)
|
||||
: undefined;
|
||||
const matches = useMemo(
|
||||
() => (test ? findCells(order ?? Array.from({ length: rowCount }, (_, i) => i), columns.length, value, test) : []),
|
||||
[test, order, rowCount, columns.length, value],
|
||||
@@ -315,7 +340,8 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
copyAs={props.extractor && ((rows) => sqlCopies(rows.map(at), props.extractor!))}
|
||||
copySelectedCells={copySelectedCells}
|
||||
copyAs={extractor && ((rows) => sqlCopies(rows.map(at), extractor))}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
|
||||
@@ -974,7 +974,8 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
height: clamp(320px, 68vh, 560px);
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
.modifyMain {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DatabaseView } from "./DatabaseView";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { registerDatabaseTreeActions } from "./treeActions";
|
||||
import { schemasKey, tablesKey, useDatabase } from "./store";
|
||||
import { databaseKey, schemaNodeKey, treeIdentifier } from "./model";
|
||||
@@ -68,7 +69,10 @@ describe("data source folders", () => {
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => dispose());
|
||||
afterEach(async () => {
|
||||
dispose();
|
||||
await setLocale("en");
|
||||
});
|
||||
|
||||
describe("routine grouping", () => {
|
||||
it("keeps an existing expanded routines folder and both overloads by default", () => {
|
||||
@@ -128,6 +132,37 @@ describe("routine grouping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("localized folders", () => {
|
||||
it("shows schema and table folder labels in Simplified Chinese", async () => {
|
||||
await setLocale("zh");
|
||||
useDatabase.setState({
|
||||
tables: {
|
||||
[tablesKey("pg", "public")]: {
|
||||
status: "ok",
|
||||
value: [
|
||||
{ name: "orders", kind: "table" },
|
||||
{ name: "order_view", kind: "view" },
|
||||
{ name: "order_summary", kind: "materializedView" },
|
||||
],
|
||||
},
|
||||
},
|
||||
objects: {
|
||||
[tablesKey("pg", "public")]: {
|
||||
routines: [{ name: "refresh_data", kind: "procedure", arguments: "", returns: null }],
|
||||
packages: [],
|
||||
sequences: [{ name: "orders_seq", dataType: "bigint" }],
|
||||
},
|
||||
},
|
||||
treeExpanded: new Set(["pg", "pg/public"]),
|
||||
});
|
||||
render(<DatabaseView />);
|
||||
const tree = within(screen.getByRole("tree"));
|
||||
for (const label of ["表", "视图", "物化视图", "例程", "序列"]) {
|
||||
expect(tree.getByText(label)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("table comments", () => {
|
||||
it("shows a table's comment after its name and hides it through the view option", async () => {
|
||||
useDatabase.setState({
|
||||
|
||||
@@ -562,7 +562,7 @@ export function DatabaseView() {
|
||||
case "schema":
|
||||
return n.schema;
|
||||
case "folder":
|
||||
return FOLDER_LABELS[n.folder];
|
||||
return t(FOLDER_LABELS[n.folder]);
|
||||
case "routine":
|
||||
return n.routine.name;
|
||||
case "package":
|
||||
@@ -576,7 +576,7 @@ export function DatabaseView() {
|
||||
case "table":
|
||||
return n.table.name;
|
||||
case "group":
|
||||
return GROUP_LABELS[n.group];
|
||||
return t(GROUP_LABELS[n.group]);
|
||||
case "column":
|
||||
return n.column.name;
|
||||
// Unnamed (SQLite) keys are numbered like IDEA's `key #1` / `foreign-key #1`.
|
||||
|
||||
@@ -1179,4 +1179,63 @@ describe("the data view's context menu (DataGrip)", () => {
|
||||
expect(await copyAs("SQL UPDATE")).toBe("UPDATE cities SET city = 'Beijing' WHERE id = 2;");
|
||||
expect(await copyAs("SQL DELETE")).toBe("DELETE FROM cities WHERE id = 2;");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["sql", "INSERT INTO cities (id, city) VALUES (2, 'Beijing');"],
|
||||
["sqlUpdates", "UPDATE cities SET city = 'Beijing' WHERE id = 2;"],
|
||||
["sqlDeletes", "DELETE FROM cities WHERE id = 2;"],
|
||||
] as const)("copies selected rows with the %s extractor on plain ⌘C", async (format, expected) => {
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!];
|
||||
const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const });
|
||||
render(
|
||||
<DataView
|
||||
columns={keyed}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel={null}
|
||||
onPanelChange={() => {}}
|
||||
extractor={{ value: format, onChange: () => {}, table }}
|
||||
/>,
|
||||
);
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[3]!, { button: 0 });
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true });
|
||||
});
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith(expected);
|
||||
});
|
||||
|
||||
it("writes WHERE from selected column values on plain ⌘C", async () => {
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!];
|
||||
const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const });
|
||||
render(
|
||||
<DataView
|
||||
columns={keyed}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel={null}
|
||||
onPanelChange={() => {}}
|
||||
extractor={{ value: "where", onChange: () => {}, table }}
|
||||
/>,
|
||||
);
|
||||
const cells = screen.getAllByRole("gridcell");
|
||||
fireEvent.mouseDown(cells[1]!, { button: 0 });
|
||||
fireEvent.mouseEnter(cells[3]!);
|
||||
fireEvent.mouseUp(window);
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true });
|
||||
});
|
||||
expect(writeText).toHaveBeenLastCalledWith("WHERE city IN ('Shanghai', 'Beijing')");
|
||||
|
||||
writeText.mockClear();
|
||||
fireEvent.mouseDown(cells[3]!, { button: 0 });
|
||||
fireEvent.mouseUp(window);
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true });
|
||||
});
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith("WHERE city = 'Beijing'");
|
||||
});
|
||||
});
|
||||
@@ -75,6 +75,8 @@ export interface GridProps {
|
||||
loadFull?: (cells: ReadonlyArray<{ row: number; col: number }>) => Promise<Cell[] | null>;
|
||||
/** The format plain ⌘C copies in (the toolbar's extractor; TSV by default). */
|
||||
copyFormat?: CopyFormat;
|
||||
/** Plain ⌘C's replacement for the selected cells (SQL extractors need the rows and columns). */
|
||||
copySelectedCells?: (rows: number[], cols: number[]) => void | Promise<void>;
|
||||
rowState?: (row: number) => "deleted" | "inserted" | null;
|
||||
isModified?: (row: number, col: number) => boolean;
|
||||
editable?: boolean;
|
||||
@@ -320,6 +322,11 @@ export function Grid(props: GridProps) {
|
||||
if (!sel.rows?.length) return block;
|
||||
return [...new Set([...sel.rows, ...block])].sort((a, b) => a - b);
|
||||
};
|
||||
const selectedCols = (): number[] => {
|
||||
if (!sel) return [];
|
||||
const n = norm(sel);
|
||||
return Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i);
|
||||
};
|
||||
/** The selected cells, row by row: the block's columns of every selected row (as the Aggregates panel). */
|
||||
const selectedCells = (): Cell[] => {
|
||||
if (!sel) return [];
|
||||
@@ -520,7 +527,8 @@ export function Grid(props: GridProps) {
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (mod && e.key.toLowerCase() === "c") {
|
||||
e.preventDefault();
|
||||
copy(copyFormat, false);
|
||||
if (props.copySelectedCells && sel) void props.copySelectedCells(selectedRows(), selectedCols());
|
||||
else copy(copyFormat, false);
|
||||
return;
|
||||
}
|
||||
if (mod && e.key.toLowerCase() === "f" && props.onFind) {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { IntrospectionPicker } from "./IntrospectionPicker";
|
||||
|
||||
describe("introspection picker", () => {
|
||||
it("selects only the names matching the filter", async () => {
|
||||
const onApply = vi.fn(async () => {});
|
||||
render(
|
||||
<IntrospectionPicker
|
||||
title="Choose databases"
|
||||
kind="databases"
|
||||
names={{
|
||||
available: ["chekhov_dev", "dickens_dev", "dickens_uat"],
|
||||
visible: ["chekhov_dev"],
|
||||
restore: () => ["chekhov_dev"],
|
||||
}}
|
||||
initial={{ all: false, names: ["chekhov_dev"] }}
|
||||
tabIndex={0}
|
||||
protectedRules={false}
|
||||
editableName={() => true}
|
||||
onLoad={() => {}}
|
||||
onApply={onApply}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Choose databases" }));
|
||||
expect(screen.queryByRole("checkbox", { name: "Select all filtered" })).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText("Filter names"), { target: { value: "dickens" } });
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Select all filtered" }));
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
|
||||
expect(onApply).toHaveBeenCalledWith({
|
||||
all: false,
|
||||
names: ["chekhov_dev", "dickens_dev", "dickens_uat"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -100,6 +100,8 @@ function PickerPopup({
|
||||
if (names?.current) marked.add(names.current);
|
||||
const filter = query.trim().toLocaleLowerCase();
|
||||
const matches = names?.available.filter((name) => name.toLocaleLowerCase().includes(filter));
|
||||
const selectableMatches = matches?.filter((name) => name !== names?.current && editableName(name)) ?? [];
|
||||
const allMatchesSelected = selectableMatches.length > 0 && selectableMatches.every((name) => marked.has(name));
|
||||
const apply = async () => {
|
||||
if (saving) return;
|
||||
if (draft === undefined) {
|
||||
@@ -164,6 +166,21 @@ function PickerPopup({
|
||||
disabled={saving}
|
||||
onChange={(all) => setDraft({ all, names: all ? [] : names.restore() })}
|
||||
/>
|
||||
{filter && matches?.length ? (
|
||||
<Checkbox
|
||||
label={tx("Select all filtered")}
|
||||
checked={allMatchesSelected}
|
||||
disabled={saving || !selectableMatches.length}
|
||||
onChange={(checked) => {
|
||||
const next = new Set(marked);
|
||||
for (const name of selectableMatches) {
|
||||
if (checked) next.add(name);
|
||||
else next.delete(name);
|
||||
}
|
||||
setDraft({ all: false, names: names.available.filter((name) => next.has(name)) });
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={styles.introspectionNames}>
|
||||
{matches?.length ? (
|
||||
|
||||
@@ -830,6 +830,10 @@ function ModifyTableForm({
|
||||
onClose={closeDialog}
|
||||
title={title}
|
||||
width={760}
|
||||
minWidth={560}
|
||||
minHeight={360}
|
||||
initialSize={{ w: 760, h: 700 }}
|
||||
resizable="both"
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{
|
||||
|
||||
@@ -47,6 +47,24 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("new data source", () => {
|
||||
it("starts PostgreSQL with the postgres database", () => {
|
||||
render(<SourceDialog initial={null} />);
|
||||
expect(screen.getByLabelText("Database:")).toHaveValue("postgres");
|
||||
});
|
||||
|
||||
it("drops the PostgreSQL default when another type is chosen", () => {
|
||||
render(<SourceDialog initial={null} />);
|
||||
select("Data source type", "MySQL");
|
||||
expect(screen.getByLabelText("Database:")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("uses ClickHouse's own defaults after starting from PostgreSQL", () => {
|
||||
render(<SourceDialog initial={null} />);
|
||||
select("Data source type", "ClickHouse");
|
||||
expect(screen.getByLabelText("Database:")).toHaveValue("default");
|
||||
expect(screen.getByLabelText("User:")).toHaveValue("default");
|
||||
});
|
||||
|
||||
it("does not save the database password unless asked to", () => {
|
||||
render(<SourceDialog initial={null} />);
|
||||
expect(savePassword().checked).toBe(false);
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
sshTunnelReady,
|
||||
} from "./model";
|
||||
import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store";
|
||||
import { DUCKDB_JDBC_PREFIX, VENDORS, blankSnowflake, sourceUrl, vendorById, vendorOf } from "./vendors";
|
||||
import { DUCKDB_JDBC_PREFIX, VENDORS, blankSnowflake, sourceUrl, vendorById, vendorOf, vendorPreset } from "./vendors";
|
||||
import { JdbcDriverProfiles, jdbcProfileOption, useJdbcDrivers } from "./JdbcDriverProfiles";
|
||||
import styles from "./Database.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
@@ -293,6 +293,11 @@ function blank(): DataSource {
|
||||
};
|
||||
}
|
||||
|
||||
function initialSource(initial: DataSource | null, preset: Partial<DataSource> | undefined): DataSource {
|
||||
const defaults = initial || preset ? {} : vendorPreset(vendorById("postgres")!);
|
||||
return { ...blank(), ...defaults, ...preset, ...initial };
|
||||
}
|
||||
|
||||
async function pickFile(title: string): Promise<string | null> {
|
||||
return choosePath({ directory: false, title });
|
||||
}
|
||||
@@ -504,7 +509,7 @@ export function SourceDialog({
|
||||
const tx = useTx();
|
||||
const txTemplate = useTxTemplate();
|
||||
const [{ source: s, password, reviewedTunnel }, setDraft] = useState(() => ({
|
||||
source: { ...blank(), ...preset, ...initial },
|
||||
source: initialSource(initial, preset),
|
||||
// `undefined`: unchanged (editing keeps the stored password).
|
||||
password: presetPassword ?? undefined,
|
||||
reviewedTunnel: false,
|
||||
@@ -871,11 +876,18 @@ export function SourceDialog({
|
||||
const x = previous;
|
||||
const old = vendorOf(x);
|
||||
const port = x.port == null || x.port === old.port ? v.port : x.port;
|
||||
const database =
|
||||
!initial && v.id === "postgres" && !x.database
|
||||
? "postgres"
|
||||
: !initial && vendor.id === "postgres" && x.database === "postgres" && v.id !== "postgres"
|
||||
? ""
|
||||
: x.database;
|
||||
return {
|
||||
...x,
|
||||
driver: v.driver,
|
||||
vendor: v.id === v.driver ? "" : v.id,
|
||||
port,
|
||||
database,
|
||||
...(v.driver !== "postgres" && x.externalTunnel ? { externalTunnel: null } : {}),
|
||||
ssl: v.ssl ?? (v.driver === "clickhouse" ? "disable" : x.ssl),
|
||||
...(v.driver === "sqlite" && x.driver !== "jdbc" ? { options: { ...x.options, keepAliveSecs: null } } : {}),
|
||||
@@ -885,7 +897,7 @@ export function SourceDialog({
|
||||
...(v.driver === "clickhouse"
|
||||
? {
|
||||
user: x.user || "default",
|
||||
database: x.database || "default",
|
||||
database: database || "default",
|
||||
options: { ...blankOptions(), ...x.options, transaction: "auto" as const },
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -286,7 +286,12 @@ describe("data source types", () => {
|
||||
vendor: "cockroachdb",
|
||||
port: 26257,
|
||||
});
|
||||
expect(vendorPreset(vendorById("postgres")!)).toEqual({ driver: "postgres", vendor: "", port: 5432 });
|
||||
expect(vendorPreset(vendorById("postgres")!)).toEqual({
|
||||
driver: "postgres",
|
||||
vendor: "",
|
||||
port: 5432,
|
||||
database: "postgres",
|
||||
});
|
||||
expect(vendorPreset(vendorById("supabase")!).ssl).toBe("require");
|
||||
expect(vendorPreset(vendorById("oracle")!)).toEqual({ driver: "oracle", vendor: "", port: 1521 });
|
||||
expect(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DbDriver } from "@/platform/ipc";
|
||||
import { exportData, type ExportData, type ExportFormat } from "./export";
|
||||
import { exportData, selectionWhere, type ExportData, type ExportFormat } from "./export";
|
||||
|
||||
const data = (value: string, type = "NUMERIC", driver: DbDriver = "postgres"): ExportData => ({
|
||||
columns: [{ name: "value", type }],
|
||||
@@ -231,6 +231,13 @@ describe("SQL statements of rows (#6143)", () => {
|
||||
expect(exportData("where", { ...rows, rows: rows.rows.slice(1) })).toBe(`WHERE id = 1`);
|
||||
});
|
||||
|
||||
it("writes a selected column as IN and a single value as equality", () => {
|
||||
expect(selectionWhere(rows, [0, 1], [0])).toBe(`WHERE id IN (2, 1)`);
|
||||
expect(selectionWhere(rows, [0], [1])).toBe(`WHERE name = 'O''Hara'`);
|
||||
expect(selectionWhere(rows, [0, 1], [1])).toBe(`WHERE name IN ('O''Hara', 'Ann')`);
|
||||
expect(selectionWhere(rows, [0], [1, 2])).toBe(`WHERE name = 'O''Hara' AND note IS NULL`);
|
||||
});
|
||||
|
||||
it("matches on every column, saying so, when no key is known, and writes IS NULL for a null", () => {
|
||||
const keyless = { ...rows, columns: rows.columns.map((c) => ({ ...c, primaryKey: false })), rows: [rows.rows[0]!] };
|
||||
expect(exportData("sqlDeletes", keyless)).toBe(
|
||||
|
||||
@@ -127,6 +127,42 @@ export function exportData(
|
||||
}
|
||||
}
|
||||
|
||||
/** A WHERE clause of the selected cells: one column uses IN, multiple columns OR their row conditions. */
|
||||
export function selectionWhere(d: ExportData, rows: readonly number[], cols: readonly number[]): string {
|
||||
const picked = rows.flatMap((row) => (d.rows[row] ? [d.rows[row]] : []));
|
||||
const selected = cols.filter((col) => d.columns[col]);
|
||||
if (!picked.length || !selected.length) return "";
|
||||
const numeric = d.columns.map((c, i) =>
|
||||
isNumericColumn(
|
||||
c.type,
|
||||
d.rows.slice(0, 50).map((r) => r[i] ?? null),
|
||||
),
|
||||
);
|
||||
const ident = (col: number) => quoteIdent(d.columns[col]!.name, d.driver);
|
||||
const literal = (value: Cell | undefined, col: number) => sqlLiteral(value ?? null, numeric[col]!, d.driver);
|
||||
const comparison = (row: readonly Cell[], col: number) =>
|
||||
row[col] == null ? `${ident(col)} IS NULL` : `${ident(col)} = ${literal(row[col], col)}`;
|
||||
|
||||
if (selected.length === 1) {
|
||||
const col = selected[0]!;
|
||||
const values = [...new Set(picked.map((row) => row[col] ?? null))];
|
||||
if (values.length === 1) return `WHERE ${comparison(picked[0]!, col)}`;
|
||||
const nonNull = values.filter((value): value is string => value !== null);
|
||||
const parts = [
|
||||
...(nonNull.length === 1
|
||||
? [`${ident(col)} = ${literal(nonNull[0], col)}`]
|
||||
: nonNull.length
|
||||
? [`${ident(col)} IN (${nonNull.map((value) => literal(value, col)).join(", ")})`]
|
||||
: []),
|
||||
...(values.includes(null) ? [`${ident(col)} IS NULL`] : []),
|
||||
];
|
||||
return `WHERE ${parts.join(" OR ")}`;
|
||||
}
|
||||
|
||||
const conditions = picked.map((row) => selected.map((col) => comparison(row, col)).join(" AND "));
|
||||
return conditions.length === 1 ? `WHERE ${conditions[0]}` : `WHERE ${conditions.map((c) => `(${c})`).join(" OR ")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL Inserts, Updates, Deletes and the Where Clause of the rows, one statement per row in
|
||||
* their order. A row is identified by its primary key columns; with none known, by every
|
||||
|
||||
@@ -46,6 +46,12 @@ const rows = (group: string) =>
|
||||
afterEach(() => useDatabase.setState({ dialog: null, details: {}, sources: [] } as never));
|
||||
|
||||
describe("Modify Table's list (DataGrip)", () => {
|
||||
it("can be resized from its window corner", () => {
|
||||
open();
|
||||
expect(screen.getByRole("dialog", { name: "Modify Table orders" })).toBeVisible();
|
||||
expect(screen.getByRole("separator", { name: "Resize" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => {
|
||||
open();
|
||||
expect(rows("Columns")).toEqual(["idinteger", "customer_idinteger", "notetext"]);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { newMenu } from "./treeMenu";
|
||||
import { RECENT_DATABASE_VENDORS_KEY, readRecentVendors, rememberRecentVendor } from "./recentVendors";
|
||||
import { useDatabase } from "./store";
|
||||
|
||||
const recentIds = () => readRecentVendors().map((vendor) => vendor.id);
|
||||
const dataSourceSubmenu = () => {
|
||||
const item = newMenu().find((entry) => "label" in entry && entry.label === "Data Source");
|
||||
if (!item || !("submenu" in item) || !item.submenu) throw new Error("missing Data Source submenu");
|
||||
return item.submenu;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.removeItem(RECENT_DATABASE_VENDORS_KEY);
|
||||
useDatabase.setState({ sources: [] });
|
||||
});
|
||||
|
||||
describe("recent data source types", () => {
|
||||
it("keeps the newest first, drops duplicates and ignores unknown entries", () => {
|
||||
rememberRecentVendor("postgres");
|
||||
rememberRecentVendor("sqlServer");
|
||||
rememberRecentVendor("postgres");
|
||||
localStorage.setItem(
|
||||
RECENT_DATABASE_VENDORS_KEY,
|
||||
JSON.stringify(["postgres", "sqlServer", "postgres", "missing", 7]),
|
||||
);
|
||||
|
||||
expect(recentIds()).toEqual(["postgres", "sqlServer"]);
|
||||
});
|
||||
|
||||
it("shows recent types above the full list and removes their duplicates", () => {
|
||||
rememberRecentVendor("postgres");
|
||||
rememberRecentVendor("sqlServer");
|
||||
const submenu = dataSourceSubmenu();
|
||||
|
||||
expect(submenu[0]).toEqual({ kind: "header", label: "Recent" });
|
||||
expect(submenu.slice(1, 3)).toEqual([
|
||||
expect.objectContaining({ label: "Microsoft SQL Server", icon: "db-sqlserver" }),
|
||||
expect.objectContaining({ label: "PostgreSQL", icon: "db-postgres" }),
|
||||
]);
|
||||
expect(submenu[3]).toEqual({ kind: "separator" });
|
||||
const labels = submenu.flatMap((item) => ("label" in item ? [item.label] : []));
|
||||
expect(labels.filter((label) => label === "PostgreSQL")).toHaveLength(1);
|
||||
expect(labels.filter((label) => label === "Microsoft SQL Server")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("uses existing data sources as recent types on first use", () => {
|
||||
useDatabase.setState({
|
||||
sources: [
|
||||
{ id: "pg", name: "Warehouse", driver: "postgres" },
|
||||
{ id: "mysql", name: "Shop", driver: "mysql" },
|
||||
{ id: "pg-2", name: "Reporting", driver: "postgres" },
|
||||
],
|
||||
});
|
||||
const submenu = dataSourceSubmenu();
|
||||
|
||||
expect(submenu[0]).toEqual({ kind: "header", label: "Recent" });
|
||||
expect(submenu.slice(1, 3)).toEqual([
|
||||
expect.objectContaining({ label: "PostgreSQL" }),
|
||||
expect.objectContaining({ label: "MySQL" }),
|
||||
]);
|
||||
const labels = submenu.flatMap((item) => ("label" in item ? [item.label] : []));
|
||||
expect(labels.filter((label) => label === "PostgreSQL")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("has no recent section while no data source exists", () => {
|
||||
expect(dataSourceSubmenu().some((item) => item.kind === "header")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { vendorById, type DbVendor } from "./vendors";
|
||||
|
||||
export const RECENT_DATABASE_VENDORS_KEY = "openidea.database.recentVendors.v1";
|
||||
|
||||
export const MAX_RECENT_VENDORS = 5;
|
||||
|
||||
/** Recently added data source types, newest first. */
|
||||
export function readRecentVendors(): DbVendor[] {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(RECENT_DATABASE_VENDORS_KEY) ?? "[]");
|
||||
if (!Array.isArray(value)) return [];
|
||||
const seen = new Set<string>();
|
||||
const vendors: DbVendor[] = [];
|
||||
for (const item of value) {
|
||||
if (typeof item !== "string" || seen.has(item)) continue;
|
||||
const vendor = vendorById(item);
|
||||
if (!vendor) continue;
|
||||
seen.add(item);
|
||||
vendors.push(vendor);
|
||||
if (vendors.length >= MAX_RECENT_VENDORS) break;
|
||||
}
|
||||
return vendors;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberRecentVendor(id: string) {
|
||||
if (!vendorById(id)) return;
|
||||
const next = [
|
||||
id,
|
||||
...readRecentVendors()
|
||||
.map((vendor) => vendor.id)
|
||||
.filter((recent) => recent !== id),
|
||||
].slice(0, MAX_RECENT_VENDORS);
|
||||
try {
|
||||
localStorage.setItem(RECENT_DATABASE_VENDORS_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
// Storage can be unavailable in a restricted WebView.
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ import {
|
||||
} from "./store";
|
||||
import { completionSource } from "./console";
|
||||
import { provideToolWindowService } from "@/workbench/contributions";
|
||||
import { RECENT_DATABASE_VENDORS_KEY, readRecentVendors } from "./recentVendors";
|
||||
|
||||
const initial = useDatabase.getState();
|
||||
const initialProject = useProject.getState();
|
||||
@@ -143,6 +144,7 @@ beforeEach(() => {
|
||||
// `showServiceView` reaches the real service, not the mocked accessor above.
|
||||
provideToolWindowService({ show: ui.show } as never);
|
||||
vi.resetAllMocks();
|
||||
localStorage.removeItem(RECENT_DATABASE_VENDORS_KEY);
|
||||
useProject.setState({ project: projectA });
|
||||
savedSources = [pg, other];
|
||||
useDatabase.setState({ ...initial, sources: savedSources, loaded: true, connected: new Set(["pg"]) }, true);
|
||||
@@ -205,6 +207,14 @@ it("loads distinct DuckDB catalog metadata on one source and discards detached e
|
||||
expect([...useDatabase.getState().connected]).toEqual(["duck"]);
|
||||
});
|
||||
|
||||
it("records the type when a data source is added, but not when one is edited", async () => {
|
||||
await saveSource({ id: "new", name: "Warehouse", driver: "postgres", vendor: "redshift" }, undefined);
|
||||
expect(readRecentVendors().map((vendor) => vendor.id)).toEqual(["redshift"]);
|
||||
|
||||
await saveSource({ ...other, host: "changed" }, undefined);
|
||||
expect(readRecentVendors().map((vendor) => vendor.id)).toEqual(["redshift"]);
|
||||
});
|
||||
|
||||
it("completes live DuckDB attachments through the source and refreshes after session commands", async () => {
|
||||
const id = "duck";
|
||||
const path = "console.sql";
|
||||
|
||||
@@ -78,6 +78,8 @@ import type { TableSnapshot } from "./schemaCompare";
|
||||
import { resolutionScopeOf, resolutionScopesOf, type SqlResolutionScope } from "./resolutionScopes";
|
||||
import { databaseRequest, invalidateDatabaseRequests, projectRequest } from "./requests";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { vendorOf } from "./vendors";
|
||||
import { rememberRecentVendor } from "./recentVendors";
|
||||
import { revealDatabaseResults } from "./outputDestination";
|
||||
export { RESULTS_VIEW } from "./outputDestination";
|
||||
|
||||
@@ -714,10 +716,12 @@ export async function saveSource(
|
||||
if (!preserve) forget(id);
|
||||
const current = sourceMutation(id);
|
||||
const sources = useDatabase.getState().sources;
|
||||
const isNew = !sources.some((s) => s.id === source.id);
|
||||
const next = sources.some((s) => s.id === source.id)
|
||||
? sources.map((s) => (s.id === source.id ? source : s))
|
||||
: [...sources, source];
|
||||
await call(commands.dbSaveSources(next));
|
||||
if (isNew) rememberRecentVendor(vendorOf(source).id);
|
||||
if (!current()) return;
|
||||
// `undefined`: keep; `null`: forget; string: store.
|
||||
if (password !== undefined) await call(commands.dbSetPassword(id, password, !!source.savePassword));
|
||||
|
||||
@@ -4,7 +4,8 @@ import { tx } from "@/platform/i18n";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { fileSourceName, parseSourceUrl } from "./model";
|
||||
import { VENDORS, vendorById, vendorPreset } from "./vendors";
|
||||
import { VENDORS, vendorById, vendorOf, vendorPreset, type DbVendor } from "./vendors";
|
||||
import { MAX_RECENT_VENDORS, readRecentVendors } from "./recentVendors";
|
||||
import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes";
|
||||
import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects";
|
||||
import {
|
||||
@@ -41,17 +42,38 @@ async function sourceFromFile() {
|
||||
openSourceDialog(null, { ...preset, file, name: fileSourceName(file) });
|
||||
}
|
||||
|
||||
/** New ▸ Data Source ▸ — built-in and JDBC presets, A–Z. */
|
||||
const vendorItem = (v: (typeof VENDORS)[number]): MenuItem => ({
|
||||
label: v.label,
|
||||
icon: v.icon,
|
||||
run: () => openSourceDialog(null, vendorPreset(v)),
|
||||
});
|
||||
|
||||
/** Explicit history first; existing sources seed it after an upgrade or on first use. */
|
||||
function recentVendors(): DbVendor[] {
|
||||
const seen = new Set<string>();
|
||||
const recent: DbVendor[] = [];
|
||||
const add = (vendor: DbVendor) => {
|
||||
if (seen.has(vendor.id) || recent.length >= MAX_RECENT_VENDORS) return;
|
||||
seen.add(vendor.id);
|
||||
recent.push(vendor);
|
||||
};
|
||||
for (const vendor of readRecentVendors()) add(vendor);
|
||||
for (const source of [...useDatabase.getState().sources].reverse()) add(vendorOf(source));
|
||||
return recent;
|
||||
}
|
||||
|
||||
/** New ▸ Data Source ▸ — recently added types first, then built-in and JDBC presets, A–Z. */
|
||||
function dataSourceItems(): MenuItem[] {
|
||||
const recent = recentVendors();
|
||||
const recentIds = new Set(recent.map((v) => v.id));
|
||||
return [
|
||||
{
|
||||
label: "Data Source",
|
||||
icon: "database",
|
||||
submenu: VENDORS.map((v) => ({
|
||||
label: v.label,
|
||||
icon: v.icon,
|
||||
run: () => openSourceDialog(null, vendorPreset(v)),
|
||||
})),
|
||||
submenu: [
|
||||
...(recent.length ? [{ kind: "header" as const, label: "Recent" }, ...recent.map(vendorItem), sep] : []),
|
||||
...VENDORS.filter((v) => !recentIds.has(v.id)).map(vendorItem),
|
||||
],
|
||||
},
|
||||
{ label: "Data Source from File…", icon: "folder", run: () => void sourceFromFile() },
|
||||
{ label: "Data Source from URL…", icon: "external-link", run: () => openDialog({ kind: "sourceUrl" }) },
|
||||
|
||||
@@ -126,6 +126,7 @@ export const vendorById = (id: string): DbVendor | undefined => BY_ID.get(id);
|
||||
export function vendorPreset(v: DbVendor): Partial<DataSource> {
|
||||
const preset: Partial<DataSource> = { driver: v.driver, vendor: v.id === v.driver ? "" : v.id, port: v.port };
|
||||
if (v.ssl) preset.ssl = v.ssl;
|
||||
if (v.id === "postgres") preset.database = "postgres";
|
||||
if (v.driver === "clickhouse") {
|
||||
preset.user = "default";
|
||||
preset.database = "default";
|
||||
|
||||
@@ -758,8 +758,15 @@ export function handleRuntimeEvent(e: PluginEvent): boolean {
|
||||
}
|
||||
return true;
|
||||
case "openTerminal":
|
||||
// The program was approved (`process:`) and verified by the host.
|
||||
void executeAction("terminal.runCommand", { program: e.program, args: e.args, name: e.title, cwd: e.cwd });
|
||||
// The program was approved (`process:`) and verified by the host. Its tab stays when it
|
||||
// ends: a program that prints and exits would otherwise take its output with it.
|
||||
void executeAction("terminal.runCommand", {
|
||||
program: e.program,
|
||||
args: e.args,
|
||||
name: e.title,
|
||||
cwd: e.cwd,
|
||||
keepOpen: true,
|
||||
});
|
||||
return true;
|
||||
case "outputChanged":
|
||||
setPluginOutput(e.pluginId, e.channel, e.text);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
.view {
|
||||
/* A tree row's detail gives way before its label: the label is what the row is. The
|
||||
factor is this large so the label's share of the shrinking stays under a layout unit:
|
||||
losing a fraction of a pixel is enough to end a label that fits with an ellipsis. */
|
||||
--tree-detail-flex-shrink: 1000000000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
|
||||
@@ -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,
|
||||
@@ -59,11 +59,13 @@ import {
|
||||
themedFolderIconName,
|
||||
showContextMenu,
|
||||
SymbolBadge,
|
||||
T,
|
||||
type DragSession,
|
||||
type TreeHandle,
|
||||
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";
|
||||
@@ -99,12 +101,15 @@ 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,
|
||||
clearRevealRequest,
|
||||
explainHiddenPath,
|
||||
isPathUnavailable,
|
||||
isReadOnlyPath,
|
||||
isUnavailablePath,
|
||||
loadDir,
|
||||
loadVisibleDirs,
|
||||
loadOutline,
|
||||
@@ -161,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,
|
||||
@@ -314,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;
|
||||
@@ -332,6 +338,7 @@ const holdsOpenFile = (dir: string, files: readonly string[]) =>
|
||||
|
||||
const Row = memo(function Row({
|
||||
node,
|
||||
label,
|
||||
matches,
|
||||
editing,
|
||||
cut,
|
||||
@@ -373,10 +380,18 @@ const Row = memo(function Row({
|
||||
node.dir && !node.placeholder && !!root && isModuleFolder(relativePath(root, node.path), node.root, build.modules);
|
||||
const isEditing =
|
||||
!!editing && (node.placeholder ? editing.kind === "new" : editing.kind === "rename" && editing.key === node.key);
|
||||
const faded = node.ignored || deco.faded;
|
||||
const unavailable = useProjectTree(
|
||||
(s) => !node.placeholder && s.unavailableRoots.size > 0 && isPathUnavailable(node.path, s.unavailableRoots),
|
||||
);
|
||||
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;
|
||||
const label = deco.label ?? node.label;
|
||||
const dimIcon = node.excluded || unavailable;
|
||||
const showUnavailableDetail = unavailable && node.root && !node.icon;
|
||||
const detailTitle = showUnavailableDetail
|
||||
? detail
|
||||
? `${detail} · ${tx("unavailable")}`
|
||||
: tx("unavailable")
|
||||
: (detail ?? undefined);
|
||||
return (
|
||||
<span
|
||||
className={clsx(styles.content, cut && styles.cut, dropTarget && styles.dropTarget)}
|
||||
@@ -385,6 +400,7 @@ const Row = memo(function Row({
|
||||
data-project-icon={icon}
|
||||
data-project-type-badge={typeBadge}
|
||||
data-dir={node.dir || undefined}
|
||||
data-unavailable={unavailable || undefined}
|
||||
title={deco.tooltip ?? hint ?? undefined}
|
||||
onClick={(e) => onClick(node, e)}
|
||||
onDoubleClick={(e) => onDoubleClick(node, e)}
|
||||
@@ -426,19 +442,21 @@ const Row = memo(function Row({
|
||||
// Project and module roots use semibold labels.
|
||||
node.root && !node.icon && styles.rootLabel,
|
||||
moduleFolder && styles.moduleLabel,
|
||||
faded && !deco.color && styles.excluded,
|
||||
(unavailable || (faded && !deco.color)) && styles.excluded,
|
||||
file?.deprecated && styles.deprecated,
|
||||
deco.error && styles.error,
|
||||
)}
|
||||
style={deco.color ? { color: deco.color } : undefined}
|
||||
text={label}
|
||||
style={!unavailable && deco.color ? { color: deco.color } : undefined}
|
||||
text={deco.label ?? label}
|
||||
indices={matches}
|
||||
tone="accent"
|
||||
/>
|
||||
{deco.suffix && <DecorationSuffix segments={deco.suffix} color={deco.suffixColor} />}
|
||||
{detail && (
|
||||
<span className={styles.detail} title={detail}>
|
||||
{(detail || showUnavailableDetail) && (
|
||||
<span className={styles.detail} title={detailTitle}>
|
||||
{detail}
|
||||
{detail && showUnavailableDetail ? " · " : null}
|
||||
{showUnavailableDetail && <T>unavailable</T>}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -556,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);
|
||||
@@ -575,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);
|
||||
@@ -669,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;
|
||||
@@ -753,7 +788,15 @@ export function ProjectView() {
|
||||
|
||||
const onRowPointerDown = useCallback((node: ProjectNode, e: ReactPointerEvent) => {
|
||||
if (e.button === 0) dragged.current = false;
|
||||
if (e.button !== 0 || node.member || node.placeholder || node.readOnly || useProjectTree.getState().editing) return;
|
||||
if (
|
||||
e.button !== 0 ||
|
||||
node.member ||
|
||||
node.placeholder ||
|
||||
node.readOnly ||
|
||||
isUnavailablePath(node.path) ||
|
||||
useProjectTree.getState().editing
|
||||
)
|
||||
return;
|
||||
const before = useProjectTree.getState().selected;
|
||||
const lead = useProjectTree.getState().lead;
|
||||
const startX = e.clientX,
|
||||
@@ -808,7 +851,10 @@ export function ProjectView() {
|
||||
if (held !== before) {
|
||||
const target = folderAt(containerRef.current, pointer.x, pointer.y);
|
||||
setDropTarget(
|
||||
paths.length && target && !paths.some((p) => target.path === p || isInside(target.path, p))
|
||||
paths.length &&
|
||||
target &&
|
||||
!isReadOnlyPath(target.path) &&
|
||||
!paths.some((p) => target.path === p || isInside(target.path, p))
|
||||
? target.key
|
||||
: null,
|
||||
);
|
||||
@@ -860,7 +906,11 @@ export function ProjectView() {
|
||||
keep();
|
||||
if (!frame) frame = requestAnimationFrame(edgeScroll);
|
||||
const target = folderAt(containerRef.current, ev.clientX, ev.clientY);
|
||||
const valid = paths.length > 0 && target && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
const valid =
|
||||
paths.length > 0 &&
|
||||
target &&
|
||||
!isReadOnlyPath(target.path) &&
|
||||
!paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
setDropTarget(valid ? target.key : null);
|
||||
if (target) files?.cancel();
|
||||
else files?.move(ev.clientX, ev.clientY);
|
||||
@@ -874,7 +924,8 @@ export function ProjectView() {
|
||||
};
|
||||
const up = (ev: PointerEvent) => {
|
||||
const target = active ? folderAt(containerRef.current, ev.clientX, ev.clientY) : null;
|
||||
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
const valid =
|
||||
target && !isReadOnlyPath(target.path) && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
const session = files;
|
||||
files = null;
|
||||
cleanup();
|
||||
@@ -927,9 +978,9 @@ export function ProjectView() {
|
||||
const target = folderAt(containerRef.current, x, y);
|
||||
if (p.type === "drop") {
|
||||
setDropTarget(null);
|
||||
if (target && p.paths.length) void importExternal(p.paths, target.path);
|
||||
if (target && !isReadOnlyPath(target.path) && p.paths.length) void importExternal(p.paths, target.path);
|
||||
} else {
|
||||
setDropTarget(target?.key ?? null);
|
||||
setDropTarget(target && !isReadOnlyPath(target.path) ? target.key : null);
|
||||
}
|
||||
})
|
||||
.then((u) => {
|
||||
@@ -949,12 +1000,15 @@ export function ProjectView() {
|
||||
if (!el) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type) => type === REMOTE_FILES_DRAG,
|
||||
over: (_, x, y) => setDropTarget(folderAt(el, x, y)?.key ?? null),
|
||||
over: (_, x, y) => {
|
||||
const target = folderAt(el, x, y);
|
||||
setDropTarget(target && !isReadOnlyPath(target.path) ? target.key : null);
|
||||
},
|
||||
leave: () => setDropTarget(null),
|
||||
drop: (data, x, y) => {
|
||||
setDropTarget(null);
|
||||
const target = folderAt(el, x, y);
|
||||
if (!target) return;
|
||||
if (!target || isReadOnlyPath(target.path)) return;
|
||||
const { server, paths } = JSON.parse(data.payload) as { server: string; paths: string[] };
|
||||
void executeAction("deployment.downloadRemoteInto", { server, paths, target: target.path });
|
||||
},
|
||||
@@ -1009,6 +1063,7 @@ export function ProjectView() {
|
||||
) : (
|
||||
<Row
|
||||
node={node}
|
||||
label={fileLabel(node)}
|
||||
matches={state.matches}
|
||||
editing={editing}
|
||||
cut={cutPaths.has(node.path)}
|
||||
@@ -1026,6 +1081,7 @@ export function ProjectView() {
|
||||
/>
|
||||
),
|
||||
[
|
||||
fileLabel,
|
||||
editing,
|
||||
cutPaths,
|
||||
dropTarget,
|
||||
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
} from "./operations";
|
||||
import { canDownload } from "./download";
|
||||
import { isSameOrInside } from "./paths";
|
||||
import { useProjectTree } from "./store";
|
||||
import { isUnavailablePath, useProjectTree } from "./store";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { gitEnabled } from "@/platform/gitEnabled";
|
||||
|
||||
@@ -196,6 +196,22 @@ export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center")
|
||||
nodes.filter((n) => !n.group),
|
||||
at,
|
||||
);
|
||||
if (nodes.some((n) => isUnavailablePath(n.path))) {
|
||||
const real = nodes.filter((n) => !n.group && !n.placeholder);
|
||||
if (!real.length) return [];
|
||||
const items: Entry[] = [
|
||||
copyPathItem(real, at, false),
|
||||
{ kind: "separator" },
|
||||
{
|
||||
id: "reload",
|
||||
label: "Reload from Disk",
|
||||
icon: "refresh",
|
||||
shortcut: keyLabel("project.reloadFromDisk"),
|
||||
run: () => void reloadFromDisk(real),
|
||||
},
|
||||
];
|
||||
return items.filter((i): i is MenuItem => !!i);
|
||||
}
|
||||
const lead = nodes[0] ?? null;
|
||||
const single = nodes.length === 1 ? lead : null;
|
||||
const nonRoot = nodes.filter((n) => !n.root);
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
reloadAll,
|
||||
reloadArchiveDirs,
|
||||
reloadLoadedDirs,
|
||||
reloadUnavailableRoots,
|
||||
setChangedFiles,
|
||||
setOpenFiles,
|
||||
setScopeFiles,
|
||||
@@ -278,7 +279,15 @@ export function activate(): () => void {
|
||||
if (s.selected !== prev.selected || s.lead !== prev.lead) publishLead();
|
||||
});
|
||||
|
||||
const onWindowFocus = () => {
|
||||
if (useProjectTree.getState().unavailableRoots.size > 0) void reloadUnavailableRoots();
|
||||
};
|
||||
if (typeof window !== "undefined") window.addEventListener("focus", onWindowFocus);
|
||||
|
||||
const disposers = [
|
||||
() => {
|
||||
if (typeof window !== "undefined") window.removeEventListener("focus", onWindowFocus);
|
||||
},
|
||||
() => {
|
||||
clearTimeout(unityTimer);
|
||||
unityGeneration++;
|
||||
|
||||
@@ -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 {
|
||||
@@ -42,7 +43,9 @@ import {
|
||||
type Editing,
|
||||
isFilteredMode,
|
||||
isReadOnlyPath,
|
||||
isUnavailablePath,
|
||||
loadDir,
|
||||
reloadLoadedDirs,
|
||||
revealPath,
|
||||
setClipboard,
|
||||
setExpanded,
|
||||
@@ -57,8 +60,8 @@ import { pathToCopy, type PathKind } from "@/platform/copyPath";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
export type { PathKind } from "@/platform/copyPath";
|
||||
|
||||
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
|
||||
const mutable = (n: ProjectNode) => !n.root && !n.placeholder && !n.readOnly;
|
||||
/** Nodes that may be renamed, moved or deleted (not roots, groups, library sources or unavailable paths). */
|
||||
const mutable = (n: ProjectNode) => !n.root && !n.placeholder && !n.readOnly && !isUnavailablePath(n.path);
|
||||
|
||||
const get = () => useProjectTree.getState();
|
||||
const caseInsensitiveOs = (os: string) => os === "windows" || os === "macos";
|
||||
@@ -141,6 +144,15 @@ export async function openFile(
|
||||
path: string,
|
||||
opts: { preview?: boolean; focus?: boolean; external?: boolean; side?: boolean } = {},
|
||||
) {
|
||||
if (isUnavailablePath(path) && !get().openFiles.includes(path)) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: tx`Cannot open ${nameOf(path)}`,
|
||||
body: tx("The project directory is currently unavailable."),
|
||||
key: "project.unavailable",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const editor = maybeEditorService();
|
||||
if (!editor) {
|
||||
notifications().notify({ level: "warning", title: "No editor available", body: path, key: "project.noEditor" });
|
||||
@@ -225,7 +237,7 @@ export function openMoveDialog(nodes: ProjectNode[] = selectedNodes(), target?:
|
||||
|
||||
/** Copy… (F5): IDEA's Copy dialog for the selection, into the folder it is in. */
|
||||
export function openCopyDialog(nodes: ProjectNode[] = selectedNodes(), options: { forceOpenInEditor?: boolean } = {}) {
|
||||
const copyable = nodes.filter((n) => !n.root && !n.group);
|
||||
const copyable = nodes.filter((n) => !n.root && !n.group && !isUnavailablePath(n.path));
|
||||
const paths = topLevelPaths(copyable);
|
||||
if (!paths.length) return;
|
||||
const single = paths.length === 1 && copyable.some((n) => n.path === paths[0] && n.dir);
|
||||
@@ -457,10 +469,16 @@ export function findFileUsages(path: string) {
|
||||
export async function reloadFromDisk(nodes: ProjectNode[] = selectedNodes()) {
|
||||
const targets = nodes.filter((n) => !n.placeholder);
|
||||
if (!targets.length) return;
|
||||
const { listings, unavailableRoots } = get();
|
||||
const dirs = new Set(targets.map((n) => (n.dir ? n.path : parentOf(n.path))));
|
||||
const loaded = [...get().listings.keys()].filter((p) => [...dirs].some((d) => isSameOrInside(p, d)));
|
||||
await Promise.all(loaded.map((p) => loadDir(p, true)));
|
||||
const files = targets.filter((n) => !n.dir).map((n) => n.path);
|
||||
const loaded = [...listings.keys()].filter((p) => [...dirs].some((d) => isSameOrInside(p, d)));
|
||||
const missingRoots =
|
||||
unavailableRoots.size > 0
|
||||
? [...unavailableRoots].filter((r) => [...dirs].some((d) => isSameOrInside(d, r)) && !listings.has(r))
|
||||
: [];
|
||||
if (missingRoots.length) await Promise.all(missingRoots.map((r) => loadDir(r, true)));
|
||||
await reloadLoadedDirs([...loaded, ...dirs]);
|
||||
const files = targets.filter((n) => !n.dir && !isUnavailablePath(n.path)).map((n) => n.path);
|
||||
if (files.length) delegate("file.reloadFromDisk", files);
|
||||
}
|
||||
|
||||
@@ -574,7 +592,9 @@ export async function undoDelete(): Promise<boolean> {
|
||||
// Clipboard / move / copy
|
||||
|
||||
export function copySelection(cut: boolean) {
|
||||
const paths = topLevelPaths(selectedNodes().filter((n) => (cut ? mutable(n) : !n.root && !n.group)));
|
||||
const paths = topLevelPaths(
|
||||
selectedNodes().filter((n) => (cut ? mutable(n) : !n.root && !n.group && !isUnavailablePath(n.path))),
|
||||
);
|
||||
if (!paths.length) return;
|
||||
// Remote paths are useful as text, but do not name files on the client.
|
||||
const remote = isRemoteWindow();
|
||||
@@ -978,7 +998,7 @@ export async function dropPaths(paths: string[], target: string, copy: boolean)
|
||||
const movable = topLevelPaths(
|
||||
paths
|
||||
.map((p) => currentModel().byKey.get(currentModel().keyOfPath.get(p) ?? p))
|
||||
.filter((n): n is ProjectNode => !!n && (copy || !n.readOnly)),
|
||||
.filter((n): n is ProjectNode => !!n && !isUnavailablePath(n.path) && (copy || !n.readOnly)),
|
||||
).filter((p) => copy || parentOf(p) !== target);
|
||||
if (!movable.length) return;
|
||||
// IDEA opens the Move refactoring dialog for drops inside the project.
|
||||
@@ -996,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));
|
||||
@@ -1104,7 +1126,7 @@ export function delegate(id: string, arg: unknown): boolean {
|
||||
* a directory or several nodes open the Reformat Code dialog. False when nothing applies.
|
||||
*/
|
||||
export function reformatNodes(nodes: readonly ProjectNode[]): boolean {
|
||||
const targets = nodes.filter((n) => !n.group && !n.readOnly);
|
||||
const targets = nodes.filter((n) => !n.group && !n.readOnly && !isUnavailablePath(n.path));
|
||||
if (!targets.length) return false;
|
||||
if (targets.length === 1 && !targets[0]!.dir) return delegate("code.reformatFile", { path: targets[0]!.path });
|
||||
return delegate("code.reformatFiles", {
|
||||
|
||||
@@ -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 " +
|
||||
|
||||
@@ -164,8 +164,12 @@ interface ProjectTreeState {
|
||||
scopeFiles: readonly string[];
|
||||
/** Loaded document outlines per file path, for the "Show Members" rows (empty for unsupported files). */
|
||||
outlines: ReadonlyMap<string, readonly OutlineItem[]>;
|
||||
/** Project/workspace roots whose directory cannot currently be read (unmounted volume, etc.). */
|
||||
unavailableRoots: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const EMPTY_UNAVAILABLE: ReadonlySet<string> = new Set();
|
||||
|
||||
const OPTIONS_KEY = "openidea.projectTree.options";
|
||||
const MODE_KEY = "openidea.projectTree.mode";
|
||||
const SCOPE_KEY = "openidea.projectTree.scope";
|
||||
@@ -211,6 +215,7 @@ export const useProjectTree = create<ProjectTreeState>(() => ({
|
||||
scope: readJson<string>(SCOPE_KEY),
|
||||
scopeFiles: [],
|
||||
outlines: new Map(),
|
||||
unavailableRoots: EMPTY_UNAVAILABLE,
|
||||
}));
|
||||
|
||||
function readMode(): ViewMode {
|
||||
@@ -379,11 +384,51 @@ type ListingBatch = "reload" | "visible";
|
||||
/** Listings read by a batch and not applied yet; `reload` marks folders that were loaded when read. */
|
||||
const pending = new Map<
|
||||
string,
|
||||
{ entries: readonly FileEntry[]; reload: boolean; batch: ListingBatch; expansion?: Expansion }
|
||||
{ entries: readonly FileEntry[]; reload: boolean; batch: ListingBatch; expansion?: Expansion; recovered?: boolean }
|
||||
>();
|
||||
let persistTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let visibleFlush: number | undefined;
|
||||
|
||||
function projectRootsOf(s: Pick<ProjectTreeState, "root" | "members">): readonly string[] {
|
||||
return s.members?.length ? s.members : s.root ? [s.root] : [];
|
||||
}
|
||||
|
||||
function isProjectRoot(path: string, s: Pick<ProjectTreeState, "root" | "members">): boolean {
|
||||
return projectRootsOf(s).includes(path);
|
||||
}
|
||||
|
||||
/** Whether `path` is an unavailable root or lies inside one. O(1) fast path when all roots are available. */
|
||||
export function isPathUnavailable(path: string, unavailable: ReadonlySet<string>): boolean {
|
||||
if (unavailable.size === 0) return false;
|
||||
for (const root of unavailable) if (isSameOrInside(path, root)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether `path` lies inside a currently unavailable project root. */
|
||||
export function isUnavailablePath(path: string): boolean {
|
||||
return isPathUnavailable(path, get().unavailableRoots);
|
||||
}
|
||||
|
||||
function markRootUnavailable(root: string) {
|
||||
const { unavailableRoots } = get();
|
||||
if (unavailableRoots.has(root)) return;
|
||||
const next = new Set(unavailableRoots);
|
||||
next.add(root);
|
||||
set({ unavailableRoots: next });
|
||||
}
|
||||
|
||||
function clearRootUnavailable(root: string) {
|
||||
const { unavailableRoots } = get();
|
||||
if (!unavailableRoots.has(root)) return;
|
||||
if (unavailableRoots.size === 1) {
|
||||
set({ unavailableRoots: EMPTY_UNAVAILABLE });
|
||||
return;
|
||||
}
|
||||
const next = new Set(unavailableRoots);
|
||||
next.delete(root);
|
||||
set({ unavailableRoots: next });
|
||||
}
|
||||
|
||||
/** Resets the view for a newly opened project, restoring its expansion state. */
|
||||
export function initProjectTree(
|
||||
root: string | null,
|
||||
@@ -436,6 +481,7 @@ export function initProjectTree(
|
||||
revealRequest: null,
|
||||
dropTarget: null,
|
||||
outlines: new Map(),
|
||||
unavailableRoots: EMPTY_UNAVAILABLE,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -618,6 +664,7 @@ async function withReadSlot<T>(read: () => Promise<T>): Promise<T> {
|
||||
function flushPending(batch: ListingBatch) {
|
||||
const { listings, expanded } = get();
|
||||
let next: Map<string, readonly FileEntry[]> | undefined;
|
||||
let recovered: string[] | undefined;
|
||||
for (const [path, result] of pending) {
|
||||
if (result.batch !== batch) continue;
|
||||
pending.delete(path);
|
||||
@@ -626,6 +673,7 @@ function flushPending(batch: ListingBatch) {
|
||||
if (result.reload && !listings.has(path)) continue;
|
||||
const merged = mergeListing(listings.get(path), result.entries);
|
||||
if (merged !== listings.get(path)) (next ??= new Map(listings)).set(path, merged);
|
||||
if (result.recovered) (recovered ??= []).push(path);
|
||||
}
|
||||
let opened: Set<string> | undefined;
|
||||
if (batch === "visible" && activeExpansion) {
|
||||
@@ -637,6 +685,7 @@ function flushPending(batch: ListingBatch) {
|
||||
}
|
||||
if (next || opened) set({ listings: next ?? listings, expanded: opened ?? expanded });
|
||||
if (opened) persistExpanded();
|
||||
if (recovered) for (const root of recovered) void reloadLoadedUnder(root);
|
||||
}
|
||||
|
||||
function scheduleVisibleListings() {
|
||||
@@ -662,8 +711,11 @@ export function loadVisibleDirs(paths: readonly string[]) {
|
||||
}
|
||||
|
||||
function load(path: string, force: boolean, batch?: ListingBatch, expansion?: Expansion): Promise<void> {
|
||||
const { root, listings } = get();
|
||||
const s = get();
|
||||
const { root, listings, unavailableRoots } = s;
|
||||
if (!root || isGroupKey(path)) return Promise.resolve();
|
||||
if (!force && unavailableRoots.size > 0 && !isProjectRoot(path, s) && isPathUnavailable(path, unavailableRoots))
|
||||
return Promise.resolve();
|
||||
if (!force && listings.has(path)) return Promise.resolve();
|
||||
const gen = generation;
|
||||
const running = inflight.get(path);
|
||||
@@ -694,13 +746,16 @@ function load(path: string, force: boolean, batch?: ListingBatch, expansion?: Ex
|
||||
const read = () => (isCurrent() ? projectFs(root).readDir(path) : Promise.resolve(null));
|
||||
const entries = await (batch === "reload" || expansion ? withReadSlot(read) : read());
|
||||
if (!entries || !isCurrent()) return;
|
||||
const recovered = get().unavailableRoots.has(path);
|
||||
if (recovered) clearRootUnavailable(path);
|
||||
if (request.batch) {
|
||||
pending.set(path, { entries, reload, batch: request.batch, expansion: request.expansion });
|
||||
pending.set(path, { entries, reload, batch: request.batch, expansion: request.expansion, recovered });
|
||||
// Restoring many expanded folders yields several replies in one frame
|
||||
if (request.batch === "visible") scheduleVisibleListings();
|
||||
} else {
|
||||
pending.delete(path);
|
||||
putListing(path, entries);
|
||||
if (recovered) void reloadLoadedUnder(path);
|
||||
}
|
||||
// Compact Middle Packages needs to look one level down a single-folder chain.
|
||||
const s = get();
|
||||
@@ -717,6 +772,12 @@ function load(path: string, force: boolean, batch?: ListingBatch, expansion?: Ex
|
||||
pending.delete(path);
|
||||
const s = get();
|
||||
if (e instanceof IpcError && (e.kind === "notFound" || e.kind === "invalidInput")) {
|
||||
if (isProjectRoot(path, s)) {
|
||||
markRootUnavailable(path);
|
||||
if (!s.listings.has(path)) set({ listings: new Map(s.listings).set(path, []) });
|
||||
return;
|
||||
}
|
||||
if (isPathUnavailable(path, s.unavailableRoots)) return;
|
||||
const listings = new Map(s.listings);
|
||||
dropListings(listings, [path]);
|
||||
const expanded = new Set([...s.expanded].filter((k) => !isSameOrInside(pathOfKey(k), path) || k === s.root));
|
||||
@@ -738,10 +799,24 @@ function isRecursiveFolder(entry: FileEntry): boolean {
|
||||
return entry.kind === "dir" && !entry.ignored && !entry.excluded;
|
||||
}
|
||||
|
||||
/** Re-reads `paths` as one batch: bounded concurrent reads, one update of the listings. */
|
||||
/** Re-reads `paths` as one batch: project roots first so unavailable roots protect cached children, then readable subfolders. */
|
||||
async function reloadDirs(paths: readonly string[]) {
|
||||
if (!paths.length) return;
|
||||
const gen = generation;
|
||||
await Promise.all(paths.map((p) => load(p, true, "reload")));
|
||||
const projectRoots = projectRootsOf(get());
|
||||
const roots: string[] = [];
|
||||
const children: string[] = [];
|
||||
for (const p of paths) {
|
||||
if (projectRoots.includes(p)) roots.push(p);
|
||||
else children.push(p);
|
||||
}
|
||||
if (roots.length) {
|
||||
await Promise.all(roots.map((p) => load(p, true, "reload")));
|
||||
if (gen !== generation) return;
|
||||
}
|
||||
const unavailable = get().unavailableRoots;
|
||||
const readable = unavailable.size > 0 ? children.filter((p) => !isPathUnavailable(p, unavailable)) : children;
|
||||
if (readable.length) await Promise.all(readable.map((p) => load(p, true, "reload")));
|
||||
if (gen === generation) flushPending("reload");
|
||||
}
|
||||
|
||||
@@ -756,10 +831,55 @@ export async function applyFsChange(event: {
|
||||
const s = get();
|
||||
if (!s.root) return;
|
||||
const plan = planRefresh(event, new Set(s.listings.keys()));
|
||||
if (plan.drop.length) {
|
||||
let drop = plan.drop;
|
||||
let reload = plan.reload;
|
||||
let removedEvents = event.removed;
|
||||
let savedDropped: Map<string, readonly FileEntry[]> | undefined;
|
||||
let prevSelected: ReadonlySet<string> | undefined;
|
||||
let prevLead: string | null | undefined;
|
||||
|
||||
if (s.unavailableRoots.size > 0 || plan.drop.length > 0) {
|
||||
let recheck: Set<string> | undefined;
|
||||
if (s.unavailableRoots.size > 0) {
|
||||
for (const r of s.unavailableRoots) {
|
||||
if (event.created.some((p) => isSameOrInside(p, r)) || event.modified.some((p) => isSameOrInside(p, r))) {
|
||||
(recheck ??= new Set()).add(r);
|
||||
if (!reload.includes(r)) reload = reload === plan.reload ? [...reload, r] : (reload.push(r), reload);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (plan.drop.length > 0) {
|
||||
const dropSet = new Set(plan.drop);
|
||||
let nextUnavailable: Set<string> | undefined;
|
||||
for (const r of projectRootsOf(s)) {
|
||||
if (dropSet.has(r) && !s.unavailableRoots.has(r)) {
|
||||
(nextUnavailable ??= new Set(s.unavailableRoots)).add(r);
|
||||
}
|
||||
}
|
||||
if (nextUnavailable) set({ unavailableRoots: nextUnavailable });
|
||||
}
|
||||
const unavailable = get().unavailableRoots;
|
||||
if (unavailable.size > 0) {
|
||||
drop = plan.drop.filter((p) => !isPathUnavailable(p, unavailable));
|
||||
reload = reload.filter((p) => recheck?.has(p) || !isPathUnavailable(p, unavailable));
|
||||
removedEvents = event.removed.filter((p) => !isPathUnavailable(p, unavailable));
|
||||
}
|
||||
const roots = projectRootsOf(s);
|
||||
if (drop.length > 0 && reload.some((p) => roots.includes(p) && !unavailable.has(p))) {
|
||||
savedDropped = new Map();
|
||||
for (const k of drop) {
|
||||
const entries = s.listings.get(k);
|
||||
if (entries) savedDropped.set(k, entries);
|
||||
}
|
||||
prevSelected = s.selected;
|
||||
prevLead = s.lead;
|
||||
}
|
||||
}
|
||||
|
||||
if (drop.length) {
|
||||
const listings = new Map(s.listings);
|
||||
dropListings(listings, plan.drop);
|
||||
const dropped = insideAnyOf(plan.drop);
|
||||
dropListings(listings, drop);
|
||||
const dropped = insideAnyOf(drop);
|
||||
const gone = (k: string) => dropped(pathOfKey(k));
|
||||
const selected = [...s.selected].filter((k) => !gone(k));
|
||||
set({
|
||||
@@ -769,9 +889,9 @@ export async function applyFsChange(event: {
|
||||
});
|
||||
}
|
||||
// Removed files: drop them from the selection too.
|
||||
if (event.removed.length) {
|
||||
if (removedEvents.length) {
|
||||
const cur = get();
|
||||
const removed = new Set(event.removed);
|
||||
const removed = new Set(removedEvents);
|
||||
const isRemoved = (k: string) => removed.has(pathOfKey(k));
|
||||
if ([...cur.selected].some(isRemoved)) {
|
||||
set({
|
||||
@@ -780,12 +900,41 @@ export async function applyFsChange(event: {
|
||||
});
|
||||
}
|
||||
}
|
||||
await reloadDirs(plan.reload);
|
||||
await reloadDirs(reload);
|
||||
const nowUnavailable = get().unavailableRoots;
|
||||
if (savedDropped && savedDropped.size > 0 && nowUnavailable.size > 0) {
|
||||
const cur = get();
|
||||
let restored: Map<string, readonly FileEntry[]> | undefined;
|
||||
for (const [k, entries] of savedDropped) {
|
||||
if (isPathUnavailable(k, nowUnavailable) && !cur.listings.has(k)) {
|
||||
(restored ??= new Map(cur.listings)).set(k, entries);
|
||||
}
|
||||
}
|
||||
let restoredSelected: Set<string> | undefined;
|
||||
if (prevSelected) {
|
||||
for (const k of prevSelected) {
|
||||
if (!cur.selected.has(k) && isPathUnavailable(pathOfKey(k), nowUnavailable)) {
|
||||
(restoredSelected ??= new Set(cur.selected)).add(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
const restoredLead =
|
||||
!cur.lead && prevLead && isPathUnavailable(pathOfKey(prevLead), nowUnavailable) ? prevLead : cur.lead;
|
||||
if (restored || restoredSelected || restoredLead !== cur.lead) {
|
||||
set({
|
||||
...(restored && { listings: restored }),
|
||||
...(restoredSelected && { selected: restoredSelected }),
|
||||
...(restoredLead !== cur.lead && { lead: restoredLead }),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Member rows go stale when the file changes on disk: drop and refetch.
|
||||
if (event.modified.length) dropOutlines(event.modified);
|
||||
if (event.removed.length) {
|
||||
const outlineRemoved =
|
||||
nowUnavailable.size > 0 ? removedEvents.filter((p) => !isPathUnavailable(p, nowUnavailable)) : removedEvents;
|
||||
if (outlineRemoved.length) {
|
||||
const outlines = new Map(get().outlines);
|
||||
const inRemoved = insideAnyOf(event.removed);
|
||||
const inRemoved = insideAnyOf(outlineRemoved);
|
||||
let changed = false;
|
||||
for (const key of [...outlines.keys()])
|
||||
if (inRemoved(key)) {
|
||||
@@ -796,11 +945,36 @@ export async function applyFsChange(event: {
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadLoadedUnder(root: string) {
|
||||
flushVisibleListings();
|
||||
const { listings } = get();
|
||||
const children = [...listings.keys()].filter((p) => p !== root && isInside(p, root));
|
||||
if (children.length) await reloadDirs(children);
|
||||
}
|
||||
|
||||
/** Re-reads any currently unavailable roots so a reconnected volume recovers cleanly. */
|
||||
export async function reloadUnavailableRoots() {
|
||||
flushVisibleListings();
|
||||
const roots = [...get().unavailableRoots];
|
||||
if (roots.length) await reloadDirs(roots);
|
||||
}
|
||||
|
||||
/** Re-reads the folders among `dirs` the tree has loaded; the rest stay unread. */
|
||||
export async function reloadLoadedDirs(dirs: readonly string[]) {
|
||||
flushVisibleListings();
|
||||
const { listings } = get();
|
||||
await reloadDirs(dirs.filter((p) => listings.has(p)));
|
||||
const { listings, unavailableRoots } = get();
|
||||
const targets = new Set<string>();
|
||||
for (const p of dirs) {
|
||||
if (listings.has(p) && (unavailableRoots.has(p) || !isPathUnavailable(p, unavailableRoots))) {
|
||||
targets.add(p);
|
||||
}
|
||||
if (unavailableRoots.size > 0) {
|
||||
for (const r of unavailableRoots) {
|
||||
if (isSameOrInside(p, r) && listings.has(r)) targets.add(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
await reloadDirs([...targets]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -817,8 +991,14 @@ export async function reloadArchiveDirs() {
|
||||
/** Re-reads every loaded folder (View › Reload from Disk). */
|
||||
export async function reloadAll() {
|
||||
flushVisibleListings();
|
||||
const { listings } = get();
|
||||
await reloadDirs([...listings.keys()]);
|
||||
const { listings, unavailableRoots } = get();
|
||||
if (unavailableRoots.size === 0) {
|
||||
await reloadDirs([...listings.keys()]);
|
||||
return;
|
||||
}
|
||||
await reloadDirs(
|
||||
[...listings.keys()].filter((p) => unavailableRoots.has(p) || !isPathUnavailable(p, unavailableRoots)),
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -831,6 +1011,7 @@ const outlineInflight = new Map<string, { promise: Promise<void> }>();
|
||||
* support, binary, …) cache an empty list so the chevron collapses away.
|
||||
*/
|
||||
export function loadOutline(path: string, force = false): Promise<void> {
|
||||
if (isUnavailablePath(path)) return Promise.resolve();
|
||||
const { outlines } = get();
|
||||
if (!force && outlines.has(path)) return Promise.resolve();
|
||||
const running = outlineInflight.get(path);
|
||||
@@ -977,9 +1158,10 @@ export function modeShows(path: string, mode = get().mode): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether `path` lies in read-only library sources. */
|
||||
/** Whether `path` lies in read-only library sources or an unavailable root. */
|
||||
export function isReadOnlyPath(path: string): boolean {
|
||||
if (isGroupKey(path) || isLibKey(path)) return true;
|
||||
if (isPathUnavailable(path, get().unavailableRoots)) return true;
|
||||
return extraFolders(projectViewRoots(useProjectViewRoots.getState().roots)).some(
|
||||
(r) => r.readOnly && r.path !== undefined && isSameOrInside(path, r.path),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, render, screen } from "@testing-library/react";
|
||||
import type { FileEntry } from "@/bindings";
|
||||
import { IpcError } from "@/platform/ipc";
|
||||
import { contextMenuItems } from "./contextMenu";
|
||||
import { MemoryFs, setProjectFsForTests, type ProjectFs } from "./fs";
|
||||
import { ProjectView } from "./ProjectView";
|
||||
import {
|
||||
applyFsChange,
|
||||
initProjectTree,
|
||||
isReadOnlyPath,
|
||||
loadDir,
|
||||
reloadAll,
|
||||
reloadUnavailableRoots,
|
||||
setExpanded,
|
||||
useProjectTree,
|
||||
} from "./store";
|
||||
|
||||
const ROOT = "/vol/demo-repo";
|
||||
|
||||
function wrapFs(base: MemoryFs, isMissing: () => boolean): ProjectFs {
|
||||
return {
|
||||
readDir: (path) => {
|
||||
if (isMissing()) return Promise.reject(new IpcError({ kind: "notFound", message: `missing: ${path}` }));
|
||||
return base.readDir(path);
|
||||
},
|
||||
createFile: (p) => base.createFile(p),
|
||||
createFileBytes: (p, d) => base.createFileBytes(p, d),
|
||||
createDir: (p) => base.createDir(p),
|
||||
rename: (a, b) => base.rename(a, b),
|
||||
delete: (p) => base.delete(p),
|
||||
copy: (a, b) => base.copy(a, b),
|
||||
importLocal: (a, b) => base.importLocal(a, b),
|
||||
};
|
||||
}
|
||||
|
||||
let mem: MemoryFs;
|
||||
let missing = false;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
missing = false;
|
||||
mem = new MemoryFs(
|
||||
{
|
||||
[`${ROOT}/src/main.ts`]: "export const a = 1;",
|
||||
[`${ROOT}/docs/guide.md`]: "# guide",
|
||||
[`${ROOT}/README.md`]: "# demo",
|
||||
},
|
||||
ROOT,
|
||||
);
|
||||
setProjectFsForTests(
|
||||
wrapFs(mem, () => missing),
|
||||
ROOT,
|
||||
);
|
||||
initProjectTree(ROOT, "demo-repo");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
setProjectFsForTests(null);
|
||||
initProjectTree(null);
|
||||
});
|
||||
|
||||
describe("unavailable project roots", () => {
|
||||
it("keeps cached listings and expanded folders when readDir(root) fails with notFound, then recovers", async () => {
|
||||
await loadDir(ROOT);
|
||||
await loadDir(`${ROOT}/src`);
|
||||
setExpanded(new Set([ROOT, `${ROOT}/src`]));
|
||||
expect(useProjectTree.getState().listings.has(`${ROOT}/src`)).toBe(true);
|
||||
|
||||
missing = true;
|
||||
await reloadAll();
|
||||
|
||||
const state = useProjectTree.getState();
|
||||
expect(state.unavailableRoots.has(ROOT)).toBe(true);
|
||||
expect(state.listings.get(ROOT)?.map((e) => e.name)).toEqual(["docs", "src", "README.md"]);
|
||||
expect(state.listings.get(`${ROOT}/src`)?.map((e) => e.name)).toEqual(["main.ts"]);
|
||||
expect(state.expanded.has(`${ROOT}/src`)).toBe(true);
|
||||
expect(isReadOnlyPath(`${ROOT}/src/main.ts`)).toBe(true);
|
||||
|
||||
missing = false;
|
||||
mem.nodes.set(`${ROOT}/src/added.ts`, { kind: "file", size: 5 });
|
||||
await reloadUnavailableRoots();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const recovered = useProjectTree.getState();
|
||||
expect(recovered.unavailableRoots.size).toBe(0);
|
||||
expect(recovered.listings.get(`${ROOT}/src`)?.map((e) => e.name)).toEqual(["added.ts", "main.ts"]);
|
||||
});
|
||||
expect(isReadOnlyPath(`${ROOT}/src/main.ts`)).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves cached listings on fsChanged root removal or child removals preceding root failure", async () => {
|
||||
await loadDir(ROOT);
|
||||
await loadDir(`${ROOT}/src`);
|
||||
await loadDir(`${ROOT}/docs`);
|
||||
|
||||
// Case 1: fsChanged directly removes the root.
|
||||
missing = true;
|
||||
await applyFsChange({ created: [], modified: [], removed: [ROOT] });
|
||||
expect(useProjectTree.getState().unavailableRoots.has(ROOT)).toBe(true);
|
||||
expect(useProjectTree.getState().listings.has(`${ROOT}/src`)).toBe(true);
|
||||
|
||||
// Recover and reload.
|
||||
missing = false;
|
||||
await reloadUnavailableRoots();
|
||||
expect(useProjectTree.getState().unavailableRoots.size).toBe(0);
|
||||
|
||||
// Case 2: child folder removal arrives in the same batch that causes root reload to fail.
|
||||
missing = true;
|
||||
await applyFsChange({ created: [], modified: [], removed: [`${ROOT}/src`] });
|
||||
expect(useProjectTree.getState().unavailableRoots.has(ROOT)).toBe(true);
|
||||
expect(useProjectTree.getState().listings.has(`${ROOT}/src`)).toBe(true);
|
||||
|
||||
// Case 3: normal subfolder deletion under a healthy root still drops that subfolder.
|
||||
missing = false;
|
||||
await reloadUnavailableRoots();
|
||||
mem.nodes.delete(`${ROOT}/docs/guide.md`);
|
||||
mem.nodes.delete(`${ROOT}/docs`);
|
||||
await applyFsChange({ created: [], modified: [], removed: [`${ROOT}/docs`] });
|
||||
expect(useProjectTree.getState().unavailableRoots.size).toBe(0);
|
||||
expect(useProjectTree.getState().listings.has(`${ROOT}/docs`)).toBe(false);
|
||||
});
|
||||
|
||||
it("renders cached root and children greyed out in ProjectView while unavailable, and clears on recovery", async () => {
|
||||
const entries: FileEntry[] = [
|
||||
{
|
||||
name: "src",
|
||||
path: `${ROOT}/src`,
|
||||
kind: "dir",
|
||||
size: 0,
|
||||
mtimeMs: 0,
|
||||
hidden: false,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
},
|
||||
{
|
||||
name: "README.md",
|
||||
path: `${ROOT}/README.md`,
|
||||
kind: "file",
|
||||
size: 6,
|
||||
mtimeMs: 0,
|
||||
hidden: false,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
},
|
||||
];
|
||||
useProjectTree.setState({
|
||||
listings: new Map<string, readonly FileEntry[]>([
|
||||
[ROOT, entries],
|
||||
[
|
||||
`${ROOT}/src`,
|
||||
[
|
||||
{
|
||||
name: "main.ts",
|
||||
path: `${ROOT}/src/main.ts`,
|
||||
kind: "file",
|
||||
size: 1,
|
||||
mtimeMs: 0,
|
||||
hidden: false,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
expanded: new Set([ROOT, `${ROOT}/src`]),
|
||||
});
|
||||
|
||||
const { container } = render(<ProjectView />);
|
||||
await screen.findByText("README.md");
|
||||
|
||||
act(() => {
|
||||
useProjectTree.setState({ unavailableRoots: new Set([ROOT]) });
|
||||
});
|
||||
|
||||
const rootRow = container.querySelector(`[data-project-path="${ROOT}"]`);
|
||||
const fileRow = container.querySelector(`[data-project-path="${ROOT}/README.md"]`);
|
||||
const childRow = container.querySelector(`[data-project-path="${ROOT}/src/main.ts"]`);
|
||||
expect(rootRow?.getAttribute("data-unavailable")).toBe("true");
|
||||
expect(fileRow?.getAttribute("data-unavailable")).toBe("true");
|
||||
expect(childRow?.getAttribute("data-unavailable")).toBe("true");
|
||||
expect(rootRow?.textContent).toContain("unavailable");
|
||||
|
||||
act(() => {
|
||||
useProjectTree.setState({ unavailableRoots: new Set() });
|
||||
});
|
||||
expect(rootRow?.getAttribute("data-unavailable")).toBeNull();
|
||||
expect(fileRow?.getAttribute("data-unavailable")).toBeNull();
|
||||
});
|
||||
|
||||
it("loads project roots before children in reloadAll so delayed root failure preserves cached children", async () => {
|
||||
await loadDir(ROOT);
|
||||
await loadDir(`${ROOT}/src`);
|
||||
setExpanded(new Set([ROOT, `${ROOT}/src`]));
|
||||
|
||||
const readOrder: string[] = [];
|
||||
setProjectFsForTests(
|
||||
{
|
||||
...wrapFs(mem, () => missing),
|
||||
readDir: async (path) => {
|
||||
readOrder.push(path);
|
||||
if (path === ROOT) await new Promise((r) => setTimeout(r, 15));
|
||||
if (missing) throw new IpcError({ kind: "notFound", message: `missing: ${path}` });
|
||||
return mem.readDir(path);
|
||||
},
|
||||
},
|
||||
ROOT,
|
||||
);
|
||||
|
||||
missing = true;
|
||||
await reloadAll();
|
||||
|
||||
expect(readOrder).toEqual([ROOT]);
|
||||
expect(useProjectTree.getState().unavailableRoots.has(ROOT)).toBe(true);
|
||||
expect(useProjectTree.getState().listings.has(`${ROOT}/src`)).toBe(true);
|
||||
expect(useProjectTree.getState().expanded.has(`${ROOT}/src`)).toBe(true);
|
||||
});
|
||||
|
||||
it("recovers unavailable root and reloads cached subdirectories when fsChanged reports created or modified", async () => {
|
||||
await loadDir(ROOT);
|
||||
await loadDir(`${ROOT}/src`);
|
||||
missing = true;
|
||||
await reloadAll();
|
||||
expect(useProjectTree.getState().unavailableRoots.has(ROOT)).toBe(true);
|
||||
|
||||
missing = false;
|
||||
mem.nodes.set(`${ROOT}/src/recovered.ts`, { kind: "file", size: 8 });
|
||||
await applyFsChange({ created: [`${ROOT}/src/recovered.ts`], modified: [], removed: [] });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const state = useProjectTree.getState();
|
||||
expect(state.unavailableRoots.size).toBe(0);
|
||||
expect(state.listings.get(`${ROOT}/src`)?.map((e) => e.name)).toEqual(["main.ts", "recovered.ts"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts context menu to Copy Path/Reference and Reload from Disk for unavailable nodes", () => {
|
||||
useProjectTree.setState({ unavailableRoots: new Set([ROOT]) });
|
||||
const items = contextMenuItems([
|
||||
{
|
||||
key: `${ROOT}/README.md`,
|
||||
path: `${ROOT}/README.md`,
|
||||
chain: [`${ROOT}/README.md`],
|
||||
label: "README.md",
|
||||
dir: false,
|
||||
root: false,
|
||||
entry: null,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
symlink: false,
|
||||
},
|
||||
]);
|
||||
expect(items.map((item) => ("id" in item ? item.id : item.kind))).toEqual(["copyPath", "separator", "reload"]);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ allprojects { p ->
|
||||
p.plugins.withId('java') {
|
||||
def json = new JsonSlurper()
|
||||
def list = { String key -> (List) json.parseText(System.getProperty(key, '[]')) }
|
||||
def map = { String key -> (Map) json.parseText(System.getProperty(key, '{}')) }
|
||||
def configure = { JavaExec t ->
|
||||
t.description = 'Runs a main class for OpenIDEA.'
|
||||
t.classpath = p.sourceSets.getByName(System.getProperty('openidea.run.sourceSet', 'main')).runtimeClasspath
|
||||
@@ -28,6 +29,11 @@ allprojects { p ->
|
||||
}
|
||||
t.args(list('openidea.run.args'))
|
||||
t.jvmArgs(list('openidea.run.jvmArgs'))
|
||||
// Overlay the run configuration's env on the forked JVM. A reused Gradle
|
||||
// daemon keeps the environment it started with, so the Gradle process env
|
||||
// alone would drop variables added after that daemon was launched.
|
||||
def env = map('openidea.run.env')
|
||||
if (env) t.environment(env)
|
||||
def token = System.getProperty('openidea.run.token')
|
||||
if (token) t.jvmArgs('-Dopenidea.run.token=' + token)
|
||||
// The IDE attaches to this JVM, not to the Gradle daemon; port 0 prints the one picked.
|
||||
|
||||
@@ -86,6 +86,7 @@ describe("Build and run using: Gradle", () => {
|
||||
"-Dopenidea.run.sourceSet=main",
|
||||
'-Dopenidea.run.args=["--port","8081 x"]',
|
||||
'-Dopenidea.run.jvmArgs=["-Xmx1g"]',
|
||||
'-Dopenidea.run.env={"SPRING_PROFILES_ACTIVE":"dev"}',
|
||||
`-Dopenidea.run.workingDir=${CORE}`,
|
||||
`${DELEGATED_TOKEN}${runJvmToken(app, ROOT)}`,
|
||||
":billing:core:openideaRun",
|
||||
@@ -100,6 +101,36 @@ describe("Build and run using: Gradle", () => {
|
||||
expect(run.args.slice(-2)).toEqual(["--offline", ":app:openideaRun"]);
|
||||
});
|
||||
|
||||
it("forwards the run configuration's environment to the JavaExec task", () => {
|
||||
const app: RunConfig = {
|
||||
...applicationConfig(
|
||||
{ className: "com.example.Application", spring: true },
|
||||
`${CORE}/src/main/java/com/example/Application.java`,
|
||||
[],
|
||||
),
|
||||
env: { JASYPT_PASSWORD: "secret", SPRING_PROFILES_ACTIVE: "dev" },
|
||||
};
|
||||
const run = delegatedGradleConfig(app, CORE, ctx)!;
|
||||
// The Gradle client still receives the merged environment...
|
||||
expect(run.env).toEqual({
|
||||
JAVA_HOME: "/jdk21",
|
||||
JASYPT_PASSWORD: "secret",
|
||||
SPRING_PROFILES_ACTIVE: "dev",
|
||||
});
|
||||
// ...and the init script applies it on the forked JVM, so a reused daemon cannot drop it.
|
||||
expect(run.args).toContain(
|
||||
`-Dopenidea.run.env=${JSON.stringify({ JASYPT_PASSWORD: "secret", SPRING_PROFILES_ACTIVE: "dev" })}`,
|
||||
);
|
||||
expect(RUN_SCRIPT).toContain("map('openidea.run.env')");
|
||||
expect(RUN_SCRIPT).toContain("t.environment(env)");
|
||||
const empty = delegatedGradleConfig(
|
||||
applicationConfig({ className: "a.Main" }, "app/src/main/java/a/Main.java", []),
|
||||
"app",
|
||||
ctx,
|
||||
)!;
|
||||
expect(empty.args).toContain("-Dopenidea.run.env={}");
|
||||
});
|
||||
|
||||
it("delegated run passes a stable token", () => {
|
||||
const app = applicationConfig({ className: "a.Main" }, "app/src/main/java/a/Main.java", []);
|
||||
const token = (c: RunConfig) => c.args.filter((a) => a.startsWith(DELEGATED_TOKEN));
|
||||
|
||||
@@ -94,6 +94,7 @@ export function delegatedGradleConfig(config: RunConfig, module: string, ctx: De
|
||||
`-Dopenidea.run.sourceSet=${parsed.classpath === "test" ? "test" : "main"}`,
|
||||
`-Dopenidea.run.args=${JSON.stringify(parsed.programArgs)}`,
|
||||
`-Dopenidea.run.jvmArgs=${JSON.stringify(parsed.vmArgs)}`,
|
||||
`-Dopenidea.run.env=${JSON.stringify(config.env ?? {})}`,
|
||||
`-Dopenidea.run.workingDir=${config.cwd ? absolute(ctx.root, config.cwd) : dir}`,
|
||||
`${DELEGATED_TOKEN}${runJvmToken(config, ctx.root)}`,
|
||||
...(ctx.offline ? ["--offline"] : []),
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -40,6 +40,7 @@ export function GitSigningRow() {
|
||||
|
||||
function SigningDialog({ projectRoot, onClose }: { projectRoot: string; onClose: () => void }) {
|
||||
const [roots, setRoots] = useState<VcsRoot[]>();
|
||||
const [hasUnavailable, setHasUnavailable] = useState(false);
|
||||
const [repo, setRepo] = useState<string>();
|
||||
const [error, setError] = useState<string>();
|
||||
useEffect(() => {
|
||||
@@ -47,8 +48,10 @@ function SigningDialog({ projectRoot, onClose }: { projectRoot: string; onClose:
|
||||
void call(commands.vcsRoots()).then(
|
||||
(roots) => {
|
||||
if (!live) return;
|
||||
setRoots(roots);
|
||||
setRepo(roots.find((root) => root.root === projectRoot)?.root ?? roots[0]?.root);
|
||||
const available = roots.filter((root) => !root.unavailable);
|
||||
setHasUnavailable(roots.length > 0 && available.length === 0);
|
||||
setRoots(available);
|
||||
setRepo(available.find((root) => root.root === projectRoot)?.root ?? available[0]?.root);
|
||||
},
|
||||
(error: unknown) => live && setError(message(error)),
|
||||
);
|
||||
@@ -73,7 +76,11 @@ function SigningDialog({ projectRoot, onClose }: { projectRoot: string; onClose:
|
||||
{error}
|
||||
</div>
|
||||
) : roots ? (
|
||||
<T>No Git repositories are configured for this project.</T>
|
||||
<T>
|
||||
{hasUnavailable
|
||||
? "Configured Git repositories are currently unavailable."
|
||||
: "No Git repositories are configured for this project."}
|
||||
</T>
|
||||
) : (
|
||||
<span role="status">
|
||||
<T>Loading…</T>
|
||||
|
||||
@@ -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 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -58,6 +58,21 @@ describe("shell exit closes the last tab", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a program whose tab is kept", () => {
|
||||
it("leaves its tab when it ends, so its output can be read", () => {
|
||||
const tab = newTab("/repo", "artisan about", { program: "php", args: ["artisan", "about"], keepOpen: true });
|
||||
shellExit(tab.session);
|
||||
expect(useTerminals.getState().tabs.map((t) => t.id)).toEqual([tab.id]);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes like any other tab without the flag", () => {
|
||||
const tab = newTab("/repo", "sh", { program: "docker", args: ["exec", "-it", "c", "sh"] });
|
||||
shellExit(tab.session);
|
||||
expect(useTerminals.getState().tabs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shell exit with sessions left", () => {
|
||||
/** Puts the caret in `key`'s terminal, as typing into it would. */
|
||||
function typeInto(key: string) {
|
||||
|
||||
@@ -293,14 +293,16 @@ export function activate(): () => void {
|
||||
{
|
||||
id: "terminal.runCommand",
|
||||
title: "Run Command in Terminal",
|
||||
description: "Opens a terminal tab running `{ program, args, name?, cwd? }` instead of the shell.",
|
||||
description:
|
||||
"Opens a terminal tab running `{ program, args, name?, cwd?, keepOpen? }` instead of the shell. " +
|
||||
"`keepOpen`: the tab stays when the program ends.",
|
||||
category: "Terminal",
|
||||
icon: "terminal",
|
||||
when: "projectOpen",
|
||||
hidden: true,
|
||||
run: async ({ arg }) => {
|
||||
const a = arg as
|
||||
| { program?: unknown; args?: unknown; name?: unknown; cwd?: unknown; spawn?: unknown }
|
||||
| { program?: unknown; args?: unknown; name?: unknown; cwd?: unknown; spawn?: unknown; keepOpen?: unknown }
|
||||
| undefined;
|
||||
const spawn =
|
||||
typeof a?.spawn === "function" ? (a.spawn as NonNullable<SessionOptions["command"]>["spawn"]) : undefined;
|
||||
@@ -310,7 +312,12 @@ export function activate(): () => void {
|
||||
if (!cwd) return;
|
||||
const rt = await loadTerminalRuntime();
|
||||
const program = typeof a.program === "string" ? a.program : "";
|
||||
rt.newTab(cwd, typeof a.name === "string" && a.name ? a.name : undefined, { program, args, spawn });
|
||||
rt.newTab(cwd, typeof a.name === "string" && a.name ? a.name : undefined, {
|
||||
program,
|
||||
args,
|
||||
spawn,
|
||||
keepOpen: a.keepOpen === true,
|
||||
});
|
||||
toolWindowService().show(WINDOW, true);
|
||||
focusActiveSoon();
|
||||
},
|
||||
|
||||
@@ -132,6 +132,11 @@ export interface SessionOptions {
|
||||
program: string;
|
||||
args: string[];
|
||||
shell?: boolean;
|
||||
/**
|
||||
* The tab stays when the program ends, whatever "Close session when it ends" says: a
|
||||
* program that prints and exits (`php artisan about`) would otherwise take its output with it.
|
||||
*/
|
||||
keepOpen?: boolean;
|
||||
env?: Record<string, string>;
|
||||
spawn?: (cols: number, rows: number, output: Channel<string>) => Promise<import("@/bindings").TerminalInfo>;
|
||||
onExit?: (status: number | null, closed: boolean) => void;
|
||||
|
||||
@@ -68,6 +68,8 @@ export const useTerminals = create<TerminalState>(() => ({
|
||||
}));
|
||||
|
||||
const sessions = new Map<string, TerminalSession>();
|
||||
/** Sessions whose tab stays when their program ends (`command.keepOpen`). */
|
||||
const keptOpen = new Set<string>();
|
||||
let seq = 0;
|
||||
|
||||
export function getSession(key: string): TerminalSession | undefined {
|
||||
@@ -125,7 +127,7 @@ function sessionOwner(): Pick<SessionOptions, "onChange" | "onFocus" | "onComple
|
||||
onCompletion: notifyCompletion,
|
||||
onExit: (k) => {
|
||||
const tab = tabOfSession(k);
|
||||
if (!tab || !workflowSettings().terminal.closeOnExit) return;
|
||||
if (!tab || keptOpen.has(k) || !workflowSettings().terminal.closeOnExit) return;
|
||||
// A session ending on its own only takes the caret back when the terminal had it: a
|
||||
// background shell exiting must not pull focus out of the editor.
|
||||
const focus = document.activeElement;
|
||||
@@ -154,6 +156,7 @@ function createSession(
|
||||
...sessionOwner(),
|
||||
});
|
||||
sessions.set(key, session);
|
||||
if (command?.keepOpen) keptOpen.add(key);
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -165,6 +168,7 @@ function disposeSession(key: string, kill = true) {
|
||||
if (focus && session?.host?.contains(focus)) publishFocus(false);
|
||||
session?.dispose(kill);
|
||||
sessions.delete(key);
|
||||
keptOpen.delete(key);
|
||||
}
|
||||
|
||||
/** Next free default name: "Local", "Local (2)", … */
|
||||
|
||||
@@ -177,8 +177,9 @@ export function BranchWidget({ place = "toolbar" }: { place?: BranchWidgetPlace
|
||||
|
||||
export function BranchesPopupHost() {
|
||||
const open = useBranchesPopup((s) => s.open);
|
||||
const allUnavailable = useVcs((s) => s.roots.length === 0 && s.unavailableRoots.length > 0);
|
||||
const from = useBranchesPopup((s) => s.from);
|
||||
if (!open) return null;
|
||||
if (!open || allUnavailable) return null;
|
||||
const anchor = branchWidgetAnchor(from) ?? { x: window.innerWidth / 2 - 160, y: 60 };
|
||||
return <BranchesPopup anchor={anchor} onClose={() => useBranchesPopup.setState({ open: false })} />;
|
||||
}
|
||||
|
||||
@@ -142,6 +142,7 @@ import { KIND_COLOR, KIND_LABEL, fileCount, stripSlash } from "./model";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { OperationBanner } from "./operations";
|
||||
import { UnavailableReposBanner } from "./UnavailableReposBanner";
|
||||
import { runOp } from "./ops";
|
||||
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
|
||||
import { existsOnDisk, refreshNow, useVcs } from "./store";
|
||||
@@ -838,6 +839,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
|
||||
}, [dialogMode]);
|
||||
|
||||
const repos = useVcs((s) => s.roots);
|
||||
const unavailableRoots = useVcs((s) => s.unavailableRoots);
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const projectRoot = useProject((s) => s.project?.root ?? null);
|
||||
const projectRoots = useEffectiveRoots();
|
||||
@@ -1085,6 +1087,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
|
||||
</div>
|
||||
</div>
|
||||
{mode !== "dialog" && <OperationBanner />}
|
||||
{mode !== "dialog" && <UnavailableReposBanner />}
|
||||
{ignored?.failed && (
|
||||
<span role="status" className={styles.empty}>
|
||||
<T>Could not load ignored files</T>
|
||||
@@ -1207,7 +1210,13 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
|
||||
aria-label="Changes"
|
||||
empty={
|
||||
<span className={styles.empty}>
|
||||
<T>No local changes</T>
|
||||
<T>
|
||||
{repos.length === 0 && unavailableRoots.length > 0
|
||||
? unavailableRoots.length > 1
|
||||
? "Repositories are unavailable"
|
||||
: "Repository is unavailable"
|
||||
: "No local changes"}
|
||||
</T>
|
||||
</span>
|
||||
}
|
||||
renderNode={(n, st) => {
|
||||
@@ -1422,8 +1431,9 @@ export function useCommitRunner(included: number, onCommitted?: () => void): Com
|
||||
const scope = useStagedRepositoryScope();
|
||||
const excluded = useCommit((s) => s.excludedStagedRepos);
|
||||
const hasRepository = !scope || [...scope].some((repo) => !excluded.has(repo));
|
||||
const hasAvailableRepo = useVcs((s) => s.roots.length > 0 || s.unavailableRoots.length === 0);
|
||||
const run = async (push: boolean, rebaseFixup = false) => {
|
||||
if (useCommit.getState().operation) return;
|
||||
if (!hasAvailableRepo || useCommit.getState().operation) return;
|
||||
const fixup = rebaseFixup ? pendingFixup(useCommit.getState().message, useCommit.getState().fixupTarget) : null;
|
||||
const committed = await commitChanges(() => setEmptyError(true), { requireSyncChecks: push || rebaseFixup });
|
||||
if (!committed) return;
|
||||
@@ -1434,7 +1444,7 @@ export function useCommitRunner(included: number, onCommitted?: () => void): Com
|
||||
return {
|
||||
emptyError,
|
||||
clearEmptyError: () => setEmptyError(false),
|
||||
canCommit: hasRepository && (included > 0 || amend || merging) && !busy && !loadingAmend,
|
||||
canCommit: hasAvailableRepo && hasRepository && (included > 0 || amend || merging) && !busy && !loadingAmend,
|
||||
run,
|
||||
};
|
||||
}
|
||||
@@ -1457,6 +1467,7 @@ export function CommitMessageField({
|
||||
const historyTick = useCommit((s) => s.historyTick);
|
||||
const { emptyError } = runner;
|
||||
const amendRoot = useVcs((s) => (s.roots.length === 1 ? s.roots[0] : null));
|
||||
const hasAvailableRepo = useVcs((s) => s.roots.length > 0 || s.unavailableRoots.length === 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (focusTick) ref.current?.focus();
|
||||
@@ -1486,7 +1497,7 @@ export function CommitMessageField({
|
||||
return (
|
||||
<>
|
||||
<div className={styles.commitBar}>
|
||||
<Checkbox checked={amend} onChange={(v) => void setAmend(v)} label="Amend" />
|
||||
<Checkbox checked={amend} disabled={!hasAvailableRepo} onChange={(v) => void setAmend(v)} label="Amend" />
|
||||
{chooseAmendTarget && amendRoot && <AmendTargetMenu root={amendRoot} />}
|
||||
<IconButton
|
||||
icon="history"
|
||||
@@ -1556,7 +1567,7 @@ export function CommitMessageField({
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
void runner.run(e.altKey);
|
||||
if (runner.canCommit) void runner.run(e.altKey);
|
||||
} else if (e.key === "Escape") {
|
||||
e.currentTarget.blur();
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ import {
|
||||
import { branchesByRepo } from "./multiRoot";
|
||||
import { stripSlash } from "./model";
|
||||
import { clearConsole, useVcsConsole } from "./ops";
|
||||
import { loadBranches, useVcs } from "./store";
|
||||
import { loadBranches, refreshNow, useVcs } from "./store";
|
||||
import { UnavailableReposBanner } from "./UnavailableReposBanner";
|
||||
|
||||
/** The Git window's tabs (they depend on the commit interface) and the one shown. */
|
||||
function useGitTabs() {
|
||||
@@ -145,6 +146,8 @@ export function LogView() {
|
||||
const repo = useLogRepositories();
|
||||
const readOnly = useReadOnlyLog();
|
||||
const shallowRepo = useVcs((s) => (repo.length === 1 && s.heads[repo[0]!]?.shallow ? repo[0] : undefined));
|
||||
const unavailableRoots = useVcs((s) => s.unavailableRoots);
|
||||
const vcsLoading = useVcs((s) => s.unavailableRoots.length > 0 && s.loading);
|
||||
const remoteBusy = useVcs((s) => !!s.remoteBusy);
|
||||
const comparison = useGitLog((s) => !!s.logTabs.find((t) => t.id === (scope ?? s.shownLog))?.comparison);
|
||||
const showBranches = useLogOptions((s) => s.showBranches) && !comparison;
|
||||
@@ -295,6 +298,7 @@ export function LogView() {
|
||||
<SplitPanel id="commits" style={PANE_STYLE} defaultSize="54%" minSize="25%">
|
||||
<div className={styles.log}>
|
||||
<FilterBar />
|
||||
{!readOnly && repo.length > 0 && <UnavailableReposBanner />}
|
||||
{!readOnly && shallowRepo && (
|
||||
<div className={styles.shallowHistory}>
|
||||
<T>This repository is a shallow clone.</T>
|
||||
@@ -307,7 +311,36 @@ export function LogView() {
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<CommitList />
|
||||
{!readOnly && repo.length === 0 && unavailableRoots.length > 0 ? (
|
||||
<EmptyState
|
||||
icon="warning"
|
||||
title={unavailableRoots.length > 1 ? "Repositories are unavailable" : "Repository is unavailable"}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
disabled={vcsLoading}
|
||||
onClick={() => {
|
||||
void refreshNow();
|
||||
void executeAction("project.refresh");
|
||||
}}
|
||||
>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => void executeAction("file.settings", "vcs.mappings")}>
|
||||
<T>Directory Mappings…</T>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>
|
||||
{unavailableRoots.length > 1
|
||||
? "Make sure the repository directories are accessible and retry."
|
||||
: "Make sure the repository directory is accessible and retry."}
|
||||
</T>
|
||||
</EmptyState>
|
||||
) : (
|
||||
<CommitList />
|
||||
)}
|
||||
</div>
|
||||
</SplitPanel>
|
||||
{showDetails && (
|
||||
|
||||
@@ -27,17 +27,22 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
|
||||
const rowHeight = useRowHeight(22);
|
||||
const project = useVcs((s) => s.root);
|
||||
const repos = useVcs((s) => s.roots);
|
||||
const unavailableRoots = useVcs((s) => s.unavailableRoots);
|
||||
const allUnavailable = repos.length === 0 && unavailableRoots.length > 0;
|
||||
const repo = useVcs((s) => s.repo);
|
||||
const version = useVcs((s) => s.version);
|
||||
const [tick, setTick] = useState(0);
|
||||
const [selection, setSelection] = useState<StashNode | null>(null);
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
|
||||
const request = useMemo(() => ({ project, repos, repo, version, tick }), [project, repos, repo, version, tick]);
|
||||
const request = useMemo(
|
||||
() => ({ project, repos, repo, version, tick, allUnavailable }),
|
||||
[project, repos, repo, version, tick, allUnavailable],
|
||||
);
|
||||
const [result, setResult] = useState<{ request: typeof request; stashes: StashEntry[]; error: string | null }>();
|
||||
const loaded = result?.request === request;
|
||||
const loaded = allUnavailable || result?.request === request;
|
||||
const sameProject =
|
||||
result?.request.project === project && result?.request.repos === repos && result?.request.repo === repo;
|
||||
const stashes = sameProject ? result!.stashes : EMPTY_STASHES;
|
||||
const stashes = !allUnavailable && sameProject ? result!.stashes : EMPTY_STASHES;
|
||||
const groups = useMemo(() => {
|
||||
const byRepo = new Map<string, StashGroup>();
|
||||
if (repos.length > 1) {
|
||||
@@ -67,6 +72,7 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
|
||||
const selected = useMemo(() => new Set(selectedNode ? [nodeKey(selectedNode)] : []), [selectedNode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (request.allUnavailable) return;
|
||||
let live = true;
|
||||
void Promise.all(
|
||||
(request.repos.length ? request.repos : [request.repo]).map(async (root) =>
|
||||
@@ -109,7 +115,15 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
|
||||
rowHeight={rowHeight}
|
||||
aria-label="Stashes"
|
||||
className={styles.stashList}
|
||||
empty={<span className={styles.empty}>{loaded ? (result.error ?? tx("No stashes")) : tx("Loading…")}</span>}
|
||||
empty={
|
||||
<span className={styles.empty}>
|
||||
{allUnavailable
|
||||
? tx(unavailableRoots.length > 1 ? "Repositories are unavailable" : "Repository is unavailable")
|
||||
: loaded
|
||||
? (result?.error ?? tx("No stashes"))
|
||||
: tx("Loading…")}
|
||||
</span>
|
||||
}
|
||||
onSelectionChange={(_keys, lead) => setSelection(lead)}
|
||||
onContextMenu={(s, _keys, e) => {
|
||||
if (!s || isGroup(s) || !loaded) return;
|
||||
@@ -162,7 +176,13 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
|
||||
/>
|
||||
)}
|
||||
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => setTick((n) => n + 1)} />
|
||||
<IconButton icon="plus" title="Stash Changes…" size="small" onClick={() => void stashChanges()} />
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Stash Changes…"
|
||||
size="small"
|
||||
disabled={allUnavailable}
|
||||
onClick={() => void stashChanges()}
|
||||
/>
|
||||
<span className={styles.sep} />
|
||||
<IconButton
|
||||
icon="check"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Icon, T } from "@/ui";
|
||||
import { refreshNow, repoName, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
|
||||
/** Banner shown in Commit and Git Log views while one or more mapped repositories are unreachable. */
|
||||
export function UnavailableReposBanner() {
|
||||
const unavailableRoots = useVcs((s) => s.unavailableRoots);
|
||||
const loading = useVcs((s) => s.unavailableRoots.length > 0 && s.loading);
|
||||
const tx = useTx();
|
||||
if (!unavailableRoots.length) return null;
|
||||
const name = repoName(unavailableRoots[0]!);
|
||||
const count = unavailableRoots.length;
|
||||
const label = count === 1 ? tx`Repository ${name} is unavailable` : tx`${count} repositories are unavailable`;
|
||||
return (
|
||||
<div className={styles.banner} role="status" aria-label={label}>
|
||||
<Icon name="warning" size={14} />
|
||||
<span className={styles.bannerText} title={unavailableRoots.join("\n")}>
|
||||
{label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.linkButton}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
void refreshNow();
|
||||
void executeAction("project.refresh");
|
||||
}}
|
||||
>
|
||||
<T>Retry</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.linkButton}
|
||||
onClick={() => void executeAction("file.settings", "vcs.mappings")}
|
||||
>
|
||||
<T>Directory Mappings…</T>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -213,4 +213,17 @@ describe("installIncomingCheck", () => {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("skips incoming checks and does not fall back to s.root when all repositories are unavailable", async () => {
|
||||
vi.useFakeTimers();
|
||||
useVcs.setState({ roots: [], unavailableRoots: ["/ws"] });
|
||||
useProject.setState({ settings: { vcs: { git: { incomingCheck: "always" } } } } as never);
|
||||
const dispose = installIncomingCheck();
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(calls).toEqual([]);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
executeAction: vi.fn(),
|
||||
refreshNow: vi.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
executeAction: mocks.executeAction,
|
||||
}));
|
||||
|
||||
vi.mock("../store", async (original) => ({
|
||||
...(await original<typeof import("../store")>()),
|
||||
refreshNow: mocks.refreshNow,
|
||||
}));
|
||||
|
||||
import { installUnavailableReposNotice } from "../index";
|
||||
import { UnavailableReposBanner } from "../UnavailableReposBanner";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const initial = useVcs.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.executeAction.mockReset();
|
||||
mocks.refreshNow.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
useVcs.setState(initial, true);
|
||||
provideNotificationService({ notify: () => undefined, expire: () => undefined });
|
||||
});
|
||||
|
||||
describe("UnavailableReposBanner", () => {
|
||||
it("renders nothing when all repositories are available", () => {
|
||||
useVcs.setState({ root: "/ws", roots: ["/ws"], unavailableRoots: [] });
|
||||
const { container } = render(<UnavailableReposBanner />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("shows single unavailable repository banner with Retry and Directory Mappings actions", () => {
|
||||
useVcs.setState({ root: "/ws", roots: [], unavailableRoots: ["/ws/external"] });
|
||||
render(<UnavailableReposBanner />);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Repository external is unavailable");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
|
||||
expect(mocks.refreshNow).toHaveBeenCalledOnce();
|
||||
expect(mocks.executeAction).toHaveBeenCalledWith("project.refresh");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Directory Mappings…" }));
|
||||
expect(mocks.executeAction).toHaveBeenCalledWith("file.settings", "vcs.mappings");
|
||||
});
|
||||
|
||||
it("shows count when multiple repositories are unavailable", () => {
|
||||
useVcs.setState({ root: "/ws", roots: [], unavailableRoots: ["/ws/a", "/ws/b"] });
|
||||
render(<UnavailableReposBanner />);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("2 repositories are unavailable");
|
||||
});
|
||||
});
|
||||
|
||||
describe("installUnavailableReposNotice", () => {
|
||||
it("notifies when a repository becomes unavailable and expires when it recovers", () => {
|
||||
const notify = vi.fn<Parameters<typeof provideNotificationService>[0]["notify"]>();
|
||||
const expire = vi.fn<(key: string) => void>();
|
||||
provideNotificationService({ notify, expire });
|
||||
|
||||
const dispose = installUnavailableReposNotice();
|
||||
try {
|
||||
act(() => {
|
||||
useVcs.setState({ root: "/ws", unavailableRoots: ["/ws/a"] });
|
||||
});
|
||||
expect(notify).toHaveBeenCalledOnce();
|
||||
expect(notify.mock.calls[0]![0]).toMatchObject({
|
||||
group: "vcs",
|
||||
level: "warning",
|
||||
key: "vcs.unavailable:/ws/a",
|
||||
sticky: true,
|
||||
title: "Repository a is unavailable",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
useVcs.setState({ unavailableRoots: [] });
|
||||
});
|
||||
expect(expire).toHaveBeenCalledWith("vcs.unavailable:/ws/a");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -146,7 +146,7 @@ interface PlannedCommit extends CommitPlan {
|
||||
|
||||
/** The included changes and their target repositories from a single status snapshot. */
|
||||
export function currentPlan(): PlannedCommit {
|
||||
const { status, root, roots } = useVcs.getState();
|
||||
const { status, root, roots, unavailableRoots } = useVcs.getState();
|
||||
const { checks: overrides, groupByRepo, excludedStagedRepos } = useCommit.getState();
|
||||
const staging = stagingAreaOn();
|
||||
const scope = stagedRepositoryScope(status, roots, staging && groupByRepo);
|
||||
@@ -155,7 +155,10 @@ export function currentPlan(): PlannedCommit {
|
||||
const plan = planCommit(files, checks, workflowSettings().vcs.commit.includeChangesByDefault);
|
||||
return {
|
||||
...plan,
|
||||
repositories: scope && !plan.included.length ? [] : commitRepos(plan.included, roots, currentRepo()),
|
||||
repositories:
|
||||
(scope && !plan.included.length) || (roots.length === 0 && unavailableRoots.length > 0)
|
||||
? []
|
||||
: commitRepos(plan.included, roots, currentRepo()),
|
||||
stagedRepositorySelection: scope !== null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -635,7 +635,7 @@ function includedChangelist(checks = useCommit.getState().checks): string {
|
||||
/** Prefills and restores Git's messages around operations while preserving the draft. */
|
||||
export function installCommitMessages(): () => void {
|
||||
const repoFor = (s: ReturnType<typeof useVcs.getState>) =>
|
||||
s.root ? (s.repo ?? s.roots[0] ?? (s.available ? s.root : null)) : null;
|
||||
s.root ? (s.repo ?? s.roots[0] ?? (s.available && s.unavailableRoots.length === 0 ? s.root : null)) : null;
|
||||
let stopMessages: (() => void) | undefined;
|
||||
const syncAppliedCommit = () => {
|
||||
const { prepared, pendingApply } = latestMessages;
|
||||
|
||||
@@ -97,8 +97,15 @@ export function installIncomingCheck(): () => void {
|
||||
|
||||
const schedule = (delay: number) => {
|
||||
clearTimeout(timer);
|
||||
const { available, hasRemotes } = useVcs.getState();
|
||||
if (!disposed && available && hasRemotes !== false && workflowSettings().vcs.git.incomingCheck !== "never") {
|
||||
const { available, hasRemotes, roots, unavailableRoots } = useVcs.getState();
|
||||
const hasActiveRoots = roots.length > 0 || unavailableRoots.length === 0;
|
||||
if (
|
||||
!disposed &&
|
||||
available &&
|
||||
hasActiveRoots &&
|
||||
hasRemotes !== false &&
|
||||
workflowSettings().vcs.git.incomingCheck !== "never"
|
||||
) {
|
||||
timer = setTimeout(() => void check(), delay);
|
||||
}
|
||||
};
|
||||
@@ -112,7 +119,8 @@ export function installIncomingCheck(): () => void {
|
||||
const s = useVcs.getState();
|
||||
if (!s.available) return;
|
||||
const mode = workflowSettings().vcs.git.incomingCheck;
|
||||
const roots = s.roots.length ? s.roots : s.root ? [s.root] : [];
|
||||
const roots = s.roots.length ? s.roots : s.unavailableRoots.length ? [] : s.root ? [s.root] : [];
|
||||
if (!roots.length) return;
|
||||
if (mode === "check") await checkIncoming(roots, stale);
|
||||
else if ((await fetchIncoming(roots, mode === "always" ? new Map() : deferred, stale)) && !stale())
|
||||
await refreshNow();
|
||||
@@ -131,7 +139,13 @@ export function installIncomingCheck(): () => void {
|
||||
};
|
||||
|
||||
const unsubVcs = useVcs.subscribe((s, prev) => {
|
||||
if (s.root !== prev.root || s.roots !== prev.roots || s.available !== prev.available) restart();
|
||||
if (
|
||||
s.root !== prev.root ||
|
||||
s.roots !== prev.roots ||
|
||||
s.unavailableRoots !== prev.unavailableRoots ||
|
||||
s.available !== prev.available
|
||||
)
|
||||
restart();
|
||||
else if (s.hasRemotes !== prev.hasRemotes && (s.hasRemotes === false || prev.hasRemotes === false)) restart();
|
||||
});
|
||||
const unsubMode = onWorkflowSettingsChange((w) => w.vcs.git.incomingCheck, restart);
|
||||
|
||||
@@ -75,6 +75,7 @@ import {
|
||||
installVcsStore,
|
||||
onConflictsChanged,
|
||||
onConflictsCleared,
|
||||
refreshNow,
|
||||
repoName,
|
||||
repoOf,
|
||||
selectRepo,
|
||||
@@ -304,6 +305,51 @@ function installSubmoduleNotice(): () => void {
|
||||
});
|
||||
}
|
||||
|
||||
/** Shows a sticky warning notification while any mapped repository is unreachable and expires it on recovery. */
|
||||
export function installUnavailableReposNotice(): () => void {
|
||||
const notified = new Set<string>();
|
||||
const sync = (unavailableRoots: readonly string[]) => {
|
||||
const current = new Set(unavailableRoots);
|
||||
for (const root of [...notified]) {
|
||||
if (current.has(root)) continue;
|
||||
notifications().expire?.(`vcs.unavailable:${root}`);
|
||||
notified.delete(root);
|
||||
}
|
||||
for (const root of unavailableRoots) {
|
||||
if (notified.has(root)) continue;
|
||||
notified.add(root);
|
||||
const name = repoName(root);
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "warning",
|
||||
key: `vcs.unavailable:${root}`,
|
||||
title: tx`Repository ${name} is unavailable`,
|
||||
body: tx`The directory ${root} cannot be reached. Make sure it is accessible or update Directory Mappings.`,
|
||||
sticky: true,
|
||||
actions: [
|
||||
{
|
||||
label: tx("Retry"),
|
||||
run: () => {
|
||||
void refreshNow();
|
||||
void executeAction("project.refresh");
|
||||
},
|
||||
},
|
||||
{ label: tx("Directory Mappings…"), run: () => void executeAction("file.settings", "vcs.mappings") },
|
||||
],
|
||||
});
|
||||
}
|
||||
};
|
||||
sync(useVcs.getState().unavailableRoots);
|
||||
const unsub = useVcs.subscribe((s, prev) => {
|
||||
if (s.unavailableRoots !== prev.unavailableRoots) sync(s.unavailableRoots);
|
||||
});
|
||||
return () => {
|
||||
unsub();
|
||||
for (const root of notified) notifications().expire?.(`vcs.unavailable:${root}`);
|
||||
notified.clear();
|
||||
};
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
let resolvedNoticeRepo: string | null = null;
|
||||
onConflictsChanged((files) => {
|
||||
@@ -350,6 +396,7 @@ export function activate(): () => void {
|
||||
installVcsStore(),
|
||||
installLfsNotice(),
|
||||
installSubmoduleNotice(),
|
||||
installUnavailableReposNotice(),
|
||||
clearUnstashConflictNotices,
|
||||
installOperationNoticeExpiry(() => resolvedNoticeRepo),
|
||||
installRootSync(),
|
||||
|
||||
@@ -135,6 +135,8 @@ export function BranchesPanel() {
|
||||
[listedRepo, allBranches, selectedBranches],
|
||||
);
|
||||
const root = useVcs((s) => s.root);
|
||||
const unavailableRoots = useVcs((s) => s.unavailableRoots);
|
||||
const allUnavailable = !availableRepositories.length && unavailableRoots.length > 0;
|
||||
const branchesLoaded = useVcs((s) => s.branchesLoaded);
|
||||
const remoteBusy = useVcs((s) => s.remoteBusy);
|
||||
const current = useVcs((s) => s.branch?.head ?? null);
|
||||
@@ -144,6 +146,7 @@ export function BranchesPanel() {
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
// Branches reload when refs move (fetch, new tag…): the tags are re-read with them.
|
||||
useEffect(() => {
|
||||
if (allUnavailable) return;
|
||||
let live = true;
|
||||
call(commands.vcsTags(availableRepositories[0] ?? currentRepo())).then(
|
||||
(t) => live && setTags(t),
|
||||
@@ -152,7 +155,7 @@ export function BranchesPanel() {
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [root, selectedBranches, availableRepositories]);
|
||||
}, [root, selectedBranches, availableRepositories, allUnavailable]);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
void branchesByRepo(queriedRepositories)
|
||||
@@ -167,9 +170,9 @@ export function BranchesPanel() {
|
||||
}, [queriedRepositories, version, logGeneration]);
|
||||
const merged = repositories.length > 1 && !grouped;
|
||||
const allRoots = useMemo(() => {
|
||||
if (!repositories.length && availableRepositories.length) return [];
|
||||
if (repositories.length < 2)
|
||||
return buildBranchTree(branches, favoritesOf(listedRepo), scopedRepo ? (allTags[scopedRepo] ?? []) : tags);
|
||||
if (allUnavailable || (!repositories.length && availableRepositories.length)) return [];
|
||||
const shownTags = scopedRepo ? (allTags[scopedRepo] ?? []) : tags;
|
||||
if (repositories.length < 2) return buildBranchTree(branches, favoritesOf(listedRepo), shownTags);
|
||||
const list = repositories.map((repo) => ({
|
||||
root: repo,
|
||||
name: repoName(branchRoots[repo] ?? repo),
|
||||
@@ -184,6 +187,7 @@ export function BranchesPanel() {
|
||||
currentRepository,
|
||||
);
|
||||
}, [
|
||||
allUnavailable,
|
||||
repositories,
|
||||
availableRepositories,
|
||||
branchRoots,
|
||||
|
||||
@@ -218,12 +218,13 @@ export function FilterBar({ fileHistory = false }: { fileHistory?: boolean }) {
|
||||
label: authors.join(", "),
|
||||
run: () => setLogFilters({ authors }),
|
||||
})),
|
||||
{ label: ME, checked: filters.authors.includes(ME), run: () => setLogFilters({ authors: [ME] }) },
|
||||
// A click sets the filter to that user alone, as IDEA does (several users go through Select…), so the
|
||||
// rows carry no check marks that would read as a multi-select.
|
||||
{ label: ME, run: () => setLogFilters({ authors: [ME] }) },
|
||||
...(authors.length ? [{ kind: "separator" as const }] : []),
|
||||
...authors.slice(0, 30).map((a) => ({
|
||||
verbatim: true,
|
||||
label: a,
|
||||
checked: filters.authors.includes(a),
|
||||
run: () => setLogFilters({ authors: [a] }),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -916,14 +916,19 @@ function logRepositoryScope(state: LogState) {
|
||||
const f = state.filters;
|
||||
const tab = state.logTabs.find((t) => t.id === state.shownLog);
|
||||
const tabRoots = tab?.repositories?.length ? tab.repositories : tab?.repo ? [tab.repo] : [];
|
||||
const { roots: registeredRoots } = useVcs.getState();
|
||||
const { roots: registeredRoots, unavailableRoots } = useVcs.getState();
|
||||
if (!tabRoots.length && !registeredRoots.length && unavailableRoots.length > 0) {
|
||||
return { repositories: [], ownerRoots: [] };
|
||||
}
|
||||
const projectRepo = currentRepoRoot();
|
||||
const projectRoots = registeredRoots.length ? registeredRoots : projectRepo ? [projectRepo] : [];
|
||||
const ownerRoots = tabRoots.length ? tabRoots : projectRoots;
|
||||
const candidates = tabRoots.length
|
||||
? tabRoots
|
||||
: f.repositories?.length
|
||||
? f.repositories
|
||||
? unavailableRoots.length
|
||||
? f.repositories.filter((r) => !unavailableRoots.includes(r))
|
||||
: f.repositories
|
||||
: registeredRoots.length
|
||||
? registeredRoots
|
||||
: [f.path || f.paths?.length ? projectRepo : currentRepo()];
|
||||
@@ -1080,6 +1085,10 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> {
|
||||
// oxlint-disable-next-line no-await-in-loop -- external log windows open in repository order, one at a time
|
||||
await call(commands.vcsOpenExternalLog(repo));
|
||||
const { repositories: roots, ownerRoots } = logRepositoryScope(s);
|
||||
if (!roots.length) {
|
||||
setViewState(id, { commits: [], done: true, loading: false, error: null });
|
||||
return;
|
||||
}
|
||||
const limit = Math.min(replace ? Math.max(PAGE, s.commits.length) : PAGE, cap - loaded);
|
||||
const refs = await branchesByRepo(roots.filter((r): r is string => !!r));
|
||||
const knownRefs = new Set(
|
||||
|
||||
@@ -304,4 +304,194 @@ describe("VCS status ownership", () => {
|
||||
expect(getFileDecoration(modified.path)).toBeUndefined();
|
||||
expect(getFileDecoration(remainingStatus.path)?.color).toBe("var(--vcs-modified)");
|
||||
});
|
||||
|
||||
it("marks a single unavailable repository without dropping VCS availability and recovers when it returns", async () => {
|
||||
useProject.setState({ project: git });
|
||||
await refreshNow();
|
||||
expect(useVcs.getState()).toMatchObject({
|
||||
available: true,
|
||||
roots: [git.root],
|
||||
unavailableRoots: [],
|
||||
status,
|
||||
branch,
|
||||
});
|
||||
expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)");
|
||||
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
|
||||
ok([{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true }]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockRejectedValueOnce(new Error("git repository is no longer valid: /a"));
|
||||
vi.mocked(commands.vcsBranchInfo).mockRejectedValueOnce(new Error("git repository is no longer valid: /a"));
|
||||
|
||||
await refreshNow();
|
||||
|
||||
expect(useVcs.getState()).toMatchObject({
|
||||
available: true,
|
||||
root: git.root,
|
||||
roots: [],
|
||||
unavailableRoots: [git.root],
|
||||
repo: null,
|
||||
status: [],
|
||||
statusLoaded: true,
|
||||
branch: null,
|
||||
branchRoot: null,
|
||||
branches: [],
|
||||
stashes: [],
|
||||
heads: {},
|
||||
operations: {},
|
||||
error: null,
|
||||
});
|
||||
expect(getFileDecoration(modified.path)).toBeUndefined();
|
||||
expect(getFileDecoration(conflicted.path)).toBeUndefined();
|
||||
expect(cleared).toHaveBeenCalledOnce();
|
||||
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(ok(roots));
|
||||
vi.mocked(commands.vcsStatus).mockResolvedValueOnce(ok([modified]));
|
||||
vi.mocked(commands.vcsBranchInfo).mockResolvedValueOnce(ok(branch));
|
||||
|
||||
await refreshNow();
|
||||
|
||||
expect(useVcs.getState()).toMatchObject({
|
||||
available: true,
|
||||
roots: [git.root],
|
||||
unavailableRoots: [],
|
||||
repo: git.root,
|
||||
status: [modified],
|
||||
branch,
|
||||
error: null,
|
||||
});
|
||||
expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)");
|
||||
});
|
||||
|
||||
it("switches to a healthy sibling repository when the primary or selected repository becomes unavailable", async () => {
|
||||
const healthy = "/a/healthy";
|
||||
const healthyBranch: Branch = {
|
||||
name: "main",
|
||||
remote: false,
|
||||
current: true,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
commit: "def1234",
|
||||
};
|
||||
const healthyInfo: BranchInfo = { ...branch, head: "main", headCommit: "def1234", operation: null };
|
||||
const healthyStatus: FileStatus = { ...modified, path: `${healthy}/src/edited.ts` };
|
||||
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
|
||||
ok([
|
||||
...roots,
|
||||
{
|
||||
root: healthy,
|
||||
branchRoot: healthy,
|
||||
head: "main",
|
||||
headCommit: "def1234",
|
||||
operation: null,
|
||||
unavailable: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockResolvedValueOnce(ok([modified, healthyStatus]));
|
||||
vi.mocked(commands.vcsBranchInfo).mockResolvedValueOnce(ok(branch));
|
||||
|
||||
useProject.setState({ project: git });
|
||||
await refreshNow();
|
||||
// Simulate repo === null (primary queried) when the primary root drops offline.
|
||||
useVcs.setState({ repo: null, branchesLoaded: true });
|
||||
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValue(
|
||||
ok([
|
||||
{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true },
|
||||
{
|
||||
root: healthy,
|
||||
branchRoot: healthy,
|
||||
head: "main",
|
||||
headCommit: "def1234",
|
||||
operation: null,
|
||||
unavailable: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockResolvedValue(ok([healthyStatus]));
|
||||
vi.mocked(commands.vcsBranchInfo).mockImplementation(async (repo) => {
|
||||
if (!repo || repo === git.root) throw new Error("git repository is no longer valid");
|
||||
return ok(healthyInfo);
|
||||
});
|
||||
const listBranches = vi.spyOn(commands, "vcsBranches").mockImplementation(async (repo) => {
|
||||
if (!repo || repo === git.root) throw new Error("git repository is no longer valid");
|
||||
return ok([healthyBranch]);
|
||||
});
|
||||
|
||||
await refreshNow();
|
||||
await vi.waitFor(() =>
|
||||
expect(useVcs.getState()).toMatchObject({
|
||||
available: true,
|
||||
roots: [healthy],
|
||||
unavailableRoots: [git.root],
|
||||
repo: healthy,
|
||||
status: [healthyStatus],
|
||||
branch: healthyInfo,
|
||||
branches: [healthyBranch],
|
||||
error: null,
|
||||
}),
|
||||
);
|
||||
expect(listBranches).toHaveBeenLastCalledWith(healthy);
|
||||
});
|
||||
|
||||
it("preserves empty roots reference across repeated all-unavailable refreshes", async () => {
|
||||
useProject.setState({ project: git });
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValue(
|
||||
ok([{ root: git.root, branchRoot: git.root, head: null, headCommit: null, operation: null, unavailable: true }]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockRejectedValue(new Error("git repository is no longer valid"));
|
||||
vi.mocked(commands.vcsBranchInfo).mockRejectedValue(new Error("git repository is no longer valid"));
|
||||
|
||||
await refreshNow();
|
||||
const first = useVcs.getState();
|
||||
expect(first.roots).toEqual([]);
|
||||
expect(first.unavailableRoots).toEqual([git.root]);
|
||||
|
||||
await refreshNow();
|
||||
const second = useVcs.getState();
|
||||
expect(second.roots).toBe(first.roots);
|
||||
expect(second.unavailableRoots).toBe(first.unavailableRoots);
|
||||
expect(second.heads).toBe(first.heads);
|
||||
expect(second.operations).toBe(first.operations);
|
||||
});
|
||||
|
||||
it("recovers an unavailable sibling repository when refreshPathsNow receives an fsChanged batch", async () => {
|
||||
const sibling = "/a/sibling";
|
||||
const siblingStatus: FileStatus = { ...modified, path: `${sibling}/src/edited.ts` };
|
||||
useProject.setState({ project: git });
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
|
||||
ok([
|
||||
...roots,
|
||||
{ root: sibling, branchRoot: sibling, head: null, headCommit: null, operation: null, unavailable: true },
|
||||
]),
|
||||
);
|
||||
await refreshNow();
|
||||
expect(useVcs.getState()).toMatchObject({ roots: [git.root], unavailableRoots: [sibling] });
|
||||
|
||||
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(
|
||||
ok([
|
||||
...roots,
|
||||
{
|
||||
root: sibling,
|
||||
branchRoot: sibling,
|
||||
head: "main",
|
||||
headCommit: "def1234",
|
||||
operation: null,
|
||||
unavailable: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
vi.mocked(commands.vcsStatus).mockResolvedValueOnce(ok([modified, siblingStatus]));
|
||||
|
||||
await refreshPathsNow([`${sibling}/src/edited.ts`]);
|
||||
expect(useVcs.getState()).toMatchObject({
|
||||
roots: [git.root, sibling],
|
||||
unavailableRoots: [],
|
||||
status: [modified, siblingStatus],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,8 @@ export interface VcsState {
|
||||
root: string | null;
|
||||
/** Repository roots, the project's own repository first. */
|
||||
roots: string[];
|
||||
/** Repository roots whose worktree or git directory is currently missing / unmounted. */
|
||||
unavailableRoots: string[];
|
||||
/** Whether any repository has a configured remote, or null until known. */
|
||||
hasRemotes: boolean | null;
|
||||
unfetched: ReadonlyMap<string, ReadonlyMap<string, UnfetchedBranch>>;
|
||||
@@ -70,6 +72,7 @@ const initial: VcsState = {
|
||||
available: false,
|
||||
root: null,
|
||||
roots: [],
|
||||
unavailableRoots: [],
|
||||
hasRemotes: null,
|
||||
unfetched: new Map(),
|
||||
branchRoots: {},
|
||||
@@ -102,7 +105,7 @@ export function currentRepo(): string | null {
|
||||
/** Root of the selected repository, which its log's and diffs' repository-relative paths are relative to. */
|
||||
export function currentRepoRoot(): string | null {
|
||||
const s = useVcs.getState();
|
||||
return s.repo ?? s.roots[0] ?? s.root;
|
||||
return s.repo ?? s.roots[0] ?? (s.unavailableRoots.length > 0 ? null : s.root);
|
||||
}
|
||||
|
||||
/** An observation stops applying as soon as the tracking configuration or local ref changes. */
|
||||
@@ -282,8 +285,7 @@ export function refreshNow(): Promise<void> {
|
||||
scoped,
|
||||
]);
|
||||
if (generation !== projectGeneration) return;
|
||||
const roots = vcsRoots.map((r) => r.root);
|
||||
if (!roots.length) {
|
||||
if (!vcsRoots.length) {
|
||||
useVcs.setState({ ...initial, root: s.root, version: s.version });
|
||||
setContext("vcsAvailable", false);
|
||||
setContext("vcsShallowRepositories", "");
|
||||
@@ -292,27 +294,65 @@ export function refreshNow(): Promise<void> {
|
||||
setFileDecorations("vcs", new Map());
|
||||
return;
|
||||
}
|
||||
if ("error" in status) throw status.error;
|
||||
const hasRemotes = vcsRoots.some((r) => r.hasRemotes === true)
|
||||
? true
|
||||
: vcsRoots.every((r) => r.hasRemotes === false)
|
||||
? false
|
||||
: null;
|
||||
useVcs.setState({ hasRemotes });
|
||||
if (s.repo && !roots.includes(s.repo)) {
|
||||
const activeRoots = vcsRoots.filter((r) => !r.unavailable);
|
||||
const unavailableRoots = vcsRoots.filter((r) => r.unavailable).map((r) => r.root);
|
||||
const roots = activeRoots.map((r) => r.root);
|
||||
const sameRoots = roots.join("\n") === s.roots.join("\n");
|
||||
const sameUnavailable = unavailableRoots.join("\n") === s.unavailableRoots.join("\n");
|
||||
const nextUnavailable = sameUnavailable ? s.unavailableRoots : unavailableRoots;
|
||||
if (!roots.length) {
|
||||
useVcs.setState({
|
||||
roots: s.roots.length ? [] : s.roots,
|
||||
unavailableRoots: nextUnavailable,
|
||||
repo: null,
|
||||
hasRemotes: null,
|
||||
operations: Object.keys(s.operations).length ? {} : s.operations,
|
||||
heads: Object.keys(s.heads).length ? {} : s.heads,
|
||||
resolvedConflicts: s.resolvedConflicts.size ? new Set() : s.resolvedConflicts,
|
||||
branchRoots: Object.keys(s.branchRoots).length ? {} : s.branchRoots,
|
||||
branches: s.branches.length ? [] : s.branches,
|
||||
branchesLoaded: false,
|
||||
stashes: s.stashes.length ? [] : s.stashes,
|
||||
stashesLoaded: false,
|
||||
error: null,
|
||||
});
|
||||
setContext("vcsAvailable", true);
|
||||
setContext("vcsShallowRepositories", "");
|
||||
setContext("vcsLfsRepositories", false);
|
||||
setContext("vcsUninitializedSubmodules", false);
|
||||
applyStatus([], null, null);
|
||||
return;
|
||||
}
|
||||
const queriedRepo = s.repo ?? vcsRoots[0]?.root ?? null;
|
||||
if (queriedRepo && !roots.includes(queriedRepo)) {
|
||||
// Keep the loaded flags so the retry also reads the new repository's branch and stash lists.
|
||||
useVcs.setState({ repo: roots[0]!, branch: null, branches: [], stashes: [] });
|
||||
useVcs.setState({
|
||||
roots: sameRoots ? s.roots : roots,
|
||||
unavailableRoots: nextUnavailable,
|
||||
repo: roots[0]!,
|
||||
branchRoot: null,
|
||||
branch: null,
|
||||
branches: [],
|
||||
stashes: [],
|
||||
});
|
||||
void refreshNow();
|
||||
return;
|
||||
}
|
||||
if ("error" in status) throw status.error;
|
||||
const hasRemotes = activeRoots.some((r) => r.hasRemotes === true)
|
||||
? true
|
||||
: activeRoots.every((r) => r.hasRemotes === false)
|
||||
? false
|
||||
: null;
|
||||
useVcs.setState({ hasRemotes });
|
||||
if ("error" in selected) throw selected.error;
|
||||
const [branch, branches, stashes] = selected.values;
|
||||
const operations = Object.fromEntries(vcsRoots.filter((r) => r.operation).map((r) => [r.root, r.operation!]));
|
||||
const operations = Object.fromEntries(activeRoots.filter((r) => r.operation).map((r) => [r.root, r.operation!]));
|
||||
// `null` (before the first refresh) is the primary repository, listed first.
|
||||
const shown = s.repo && roots.includes(s.repo) ? s.repo : (roots[0] ?? null);
|
||||
const repo = attentionRepo(shown, s.operations, operations) ?? shown;
|
||||
const heads = Object.fromEntries(
|
||||
vcsRoots.map((r) => [
|
||||
activeRoots.map((r) => [
|
||||
r.root,
|
||||
{
|
||||
head: r.head,
|
||||
@@ -324,11 +364,11 @@ export function refreshNow(): Promise<void> {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const resolvedConflicts = new Set(vcsRoots.flatMap((r) => r.resolvedConflicts ?? []));
|
||||
const sameRoots = roots.join("\n") === s.roots.join("\n");
|
||||
const branchRoots = Object.fromEntries(vcsRoots.map((r) => [r.root, r.branchRoot]));
|
||||
const resolvedConflicts = new Set(activeRoots.flatMap((r) => r.resolvedConflicts ?? []));
|
||||
const branchRoots = Object.fromEntries(activeRoots.map((r) => [r.root, r.branchRoot]));
|
||||
const sameBranchRoots = sameRoots && roots.every((root) => branchRoots[root] === s.branchRoots[root]);
|
||||
useVcs.setState({
|
||||
unavailableRoots: nextUnavailable,
|
||||
operations,
|
||||
heads,
|
||||
resolvedConflicts,
|
||||
@@ -337,15 +377,15 @@ export function refreshNow(): Promise<void> {
|
||||
if (repo !== s.repo || !sameRoots) useVcs.setState({ roots: sameRoots ? s.roots : roots, repo });
|
||||
setContext(
|
||||
"vcsLfsRepositories",
|
||||
vcsRoots.some((r) => r.lfs),
|
||||
activeRoots.some((r) => r.lfs),
|
||||
);
|
||||
setContext(
|
||||
"vcsUninitializedSubmodules",
|
||||
vcsRoots.some((r) => r.uninitializedSubmodules?.length),
|
||||
activeRoots.some((r) => r.uninitializedSubmodules?.length),
|
||||
);
|
||||
setContext(
|
||||
"vcsShallowRepositories",
|
||||
vcsRoots
|
||||
activeRoots
|
||||
.filter((r) => r.shallow)
|
||||
.map((r) => r.root)
|
||||
.join("\n"),
|
||||
@@ -378,7 +418,13 @@ export function refreshNow(): Promise<void> {
|
||||
*/
|
||||
export function refreshPathsNow(paths: readonly string[]): Promise<void> {
|
||||
const state = useVcs.getState();
|
||||
if (!state.available || !state.statusLoaded || paths.length === 0 || paths.length > PATH_BATCH_LIMIT) {
|
||||
if (
|
||||
!state.available ||
|
||||
!state.statusLoaded ||
|
||||
paths.length === 0 ||
|
||||
paths.length > PATH_BATCH_LIMIT ||
|
||||
state.unavailableRoots.length > 0
|
||||
) {
|
||||
return refreshNow();
|
||||
}
|
||||
if (inflight) {
|
||||
@@ -485,16 +531,26 @@ export function applyStatus(
|
||||
}
|
||||
|
||||
export async function loadBranches(): Promise<Branch[]> {
|
||||
const { roots, unavailableRoots } = useVcs.getState();
|
||||
if (roots.length === 0 && unavailableRoots.length > 0) return [];
|
||||
const gen = projectGeneration;
|
||||
const repo = currentRepo();
|
||||
const branches = await call(commands.vcsBranches(repo));
|
||||
if (repo === currentRepo()) useVcs.setState({ branches, branchesLoaded: true });
|
||||
if (gen === projectGeneration && repo === currentRepo() && useVcs.getState().roots.length > 0) {
|
||||
useVcs.setState({ branches, branchesLoaded: true });
|
||||
}
|
||||
return branches;
|
||||
}
|
||||
|
||||
export async function loadStashes(): Promise<Stash[]> {
|
||||
const { roots, unavailableRoots } = useVcs.getState();
|
||||
if (roots.length === 0 && unavailableRoots.length > 0) return [];
|
||||
const gen = projectGeneration;
|
||||
const repo = currentRepo();
|
||||
const stashes = await call(commands.vcsStashes(repo));
|
||||
if (repo === currentRepo()) useVcs.setState({ stashes, stashesLoaded: true });
|
||||
if (gen === projectGeneration && repo === currentRepo() && useVcs.getState().roots.length > 0) {
|
||||
useVcs.setState({ stashes, stashesLoaded: true });
|
||||
}
|
||||
return stashes;
|
||||
}
|
||||
|
||||
@@ -563,9 +619,15 @@ export function installVcsStore(): () => void {
|
||||
if (useVcs.getState().available) setFileDecorations("vcs", statusDecorations(useVcs.getState().status, show));
|
||||
},
|
||||
);
|
||||
const onWindowFocus = () => {
|
||||
const s = useVcs.getState();
|
||||
if (s.available && s.unavailableRoots.length > 0) scheduleRefresh(200);
|
||||
};
|
||||
if (typeof window !== "undefined") window.addEventListener("focus", onWindowFocus);
|
||||
return () => {
|
||||
offFetchContext();
|
||||
offSettings();
|
||||
if (typeof window !== "undefined") window.removeEventListener("focus", onWindowFocus);
|
||||
clearTimeout(timer);
|
||||
unsubProject();
|
||||
offVcs();
|
||||
|
||||
@@ -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": "正在调试",
|
||||
@@ -5839,6 +5843,7 @@
|
||||
"{label} (seconds)": "{label}(秒)",
|
||||
"Succeeded: {version}": "成功:{version}",
|
||||
"All databases": "全部数据库",
|
||||
"Select all filtered": "全选筛选项",
|
||||
"Choose databases for {name}": "选择 {name} 的数据库",
|
||||
"Choose schemas for {name}": "选择 {name} 的架构",
|
||||
"Use source settings": "使用数据源设置",
|
||||
@@ -9281,6 +9286,18 @@
|
||||
"Role": "角色",
|
||||
"<role>": "<角色>",
|
||||
"Execute SQL Script": "执行 SQL 脚本",
|
||||
"tables": "表",
|
||||
"views": "视图",
|
||||
"materialized views": "物化视图",
|
||||
"routines": "例程",
|
||||
"procedures": "过程",
|
||||
"functions": "函数",
|
||||
"packages": "包",
|
||||
"sequences": "序列",
|
||||
"keys": "键",
|
||||
"foreign keys": "外键",
|
||||
"indexes": "索引",
|
||||
"triggers": "触发器",
|
||||
"stages": "暂存区",
|
||||
"streams": "流",
|
||||
"tasks": "任务",
|
||||
@@ -11557,5 +11574,16 @@
|
||||
"Packages come from the Python in WSL and are read-only here. To change them, install them there (for example with pip in the distribution), then reload the list.": "软件包来自 WSL 中的 Python,此处只读。如需更改,请在 WSL 中安装(例如在发行版中使用 pip),然后重新加载列表。",
|
||||
"{python} in WSL {distro}": "WSL {distro} 中的 {python}",
|
||||
"Type the absolute path of the Python in WSL, such as /home/me/.venv/bin/python.": "请输入 WSL 中 Python 的绝对路径,例如 /home/me/.venv/bin/python。",
|
||||
"WSL distributions could not be listed: {e}": "无法列出 WSL 发行版:{e}"
|
||||
"WSL distributions could not be listed: {e}": "无法列出 WSL 发行版:{e}",
|
||||
"unavailable": "不可用",
|
||||
"The project directory is currently unavailable.": "项目目录当前不可用。",
|
||||
"Configured Git repositories are currently unavailable.": "已配置的 Git 仓库当前不可用。",
|
||||
"Repositories are unavailable": "仓库不可用",
|
||||
"Repository is unavailable": "仓库不可用",
|
||||
"Directory Mappings…": "目录映射…",
|
||||
"Make sure the repository directories are accessible and retry.": "请确保仓库目录可访问后重试。",
|
||||
"Make sure the repository directory is accessible and retry.": "请确保仓库目录可访问后重试。",
|
||||
"Repository {name} is unavailable": "仓库 {name} 不可用",
|
||||
"{count} repositories are unavailable": "{count} 个仓库不可用",
|
||||
"The directory {root} cannot be reached. Make sure it is accessible or update Directory Mappings.": "无法访问目录 {root}。请确保该目录可访问,或更新目录映射。"
|
||||
}
|
||||
@@ -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
Заблокувати користувача