дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
11
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f4b70b0988 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 |
No files matched your search
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -308,6 +308,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +344,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -818,8 +825,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -839,8 +844,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -1291,8 +1312,10 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1310,14 +1333,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1470,26 +1493,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1853,7 +1909,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1868,10 +1924,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1885,11 +1946,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1899,8 +1961,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1908,13 +1973,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -2124,14 +2189,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2144,12 +2212,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -899,7 +899,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -981,7 +981,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1005,7 +1005,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1037,7 +1037,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1889,7 +1889,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1898,7 +1898,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1914,8 +1914,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1958,10 +1961,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -1995,10 +2001,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -2009,6 +2015,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2209,7 +2249,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2236,7 +2276,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2270,7 +2310,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2299,7 +2339,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2323,7 +2363,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3418,7 +3458,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -297,6 +297,8 @@ pub struct DbManager {
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
|
||||
|
||||
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
|
||||
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
|
||||
@@ -1429,13 +1431,34 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let mut tables: Vec<CompletionTable> = Vec::new();
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return self.jdbc_completion(id, p).await;
|
||||
}
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
|
||||
Pool::Snowflake(p) => {
|
||||
tables = snowflake::meta::completion(p).await?;
|
||||
Vec::new()
|
||||
}
|
||||
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
|
||||
// The default schema is read in full: under a shared row cap, a schema with many
|
||||
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
|
||||
_ if !default_schema.is_empty() => {
|
||||
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
|
||||
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
|
||||
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
|
||||
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
|
||||
rows
|
||||
}
|
||||
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
|
||||
};
|
||||
for r in rows {
|
||||
let mut it = r.into_iter().map(Option::unwrap_or_default);
|
||||
@@ -1471,16 +1494,6 @@ impl DbManager {
|
||||
})
|
||||
};
|
||||
let foreign_keys = group_foreign_keys(fk_rows, &tables);
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(CompletionModel { default_schema, tables, foreign_keys })
|
||||
}
|
||||
|
||||
|
||||
@@ -252,31 +252,47 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which schemas a [`completion_columns`] query reads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompletionScope<'a> {
|
||||
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
All,
|
||||
/// One schema, in full.
|
||||
Only(&'a str),
|
||||
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
Except(&'a str),
|
||||
}
|
||||
|
||||
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
|
||||
pub const COMPLETION_ROW_CAP: usize = 50_000;
|
||||
|
||||
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
|
||||
/// for SQL completion, grouped by table in column order.
|
||||
pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
let (query, schema, order) = match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => {
|
||||
DbDriver::Clickhouse => (
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
|
||||
ORDER BY c.database, c.table, c.position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Sqlite => {
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
"c.database, c.table, c.position",
|
||||
),
|
||||
DbDriver::Sqlite => (
|
||||
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
|
||||
}
|
||||
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
|
||||
DbDriver::Postgres => {
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
"m.name, p.cid",
|
||||
),
|
||||
DbDriver::Postgres => (
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
|
||||
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
|
||||
@@ -287,19 +303,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
|
||||
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
|
||||
"n.nspname",
|
||||
"n.nspname, c.relname, a.attnum",
|
||||
),
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::SqlServer => (
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
@@ -310,19 +328,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
"c.TABLE_SCHEMA",
|
||||
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
|
||||
),
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::Oracle => (
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
@@ -334,10 +354,22 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
|
||||
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
|
||||
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
|
||||
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
|
||||
}
|
||||
}
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
|
||||
"c.owner",
|
||||
"c.owner, c.table_name, c.column_id",
|
||||
),
|
||||
};
|
||||
let filter = match scope {
|
||||
CompletionScope::All => String::new(),
|
||||
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
|
||||
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
|
||||
};
|
||||
let cap = match (scope, driver) {
|
||||
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
|
||||
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
|
||||
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
|
||||
};
|
||||
format!("{query}{filter} ORDER BY {order}{cap}")
|
||||
}
|
||||
|
||||
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
|
||||
@@ -950,7 +982,7 @@ mod tests {
|
||||
let keys = indexes(driver, "default", "events");
|
||||
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
|
||||
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
|
||||
let completion = completion_columns(driver);
|
||||
let completion = completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion.contains("c.is_in_primary_key, 1"));
|
||||
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
|
||||
}
|
||||
@@ -1060,7 +1092,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
@@ -1074,7 +1106,7 @@ mod tests {
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
completion_columns(d, CompletionScope::All),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
@@ -1141,7 +1173,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
|
||||
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
|
||||
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
|
||||
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
|
||||
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
|
||||
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
|
||||
@@ -1256,7 +1288,7 @@ mod tests {
|
||||
let columns = columns(driver, "PUBLIC", "ORDERS");
|
||||
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
|
||||
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
|
||||
assert!(completion_columns(driver).contains("LIMIT 50000"));
|
||||
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
|
||||
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
|
||||
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
|
||||
assert_eq!(
|
||||
@@ -1268,6 +1300,35 @@ mod tests {
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_reads_the_default_schema_without_the_shared_cap() {
|
||||
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
|
||||
// sorting last had no columns.
|
||||
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
|
||||
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
|
||||
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
|
||||
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
|
||||
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
|
||||
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
|
||||
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
|
||||
for (driver, column) in [
|
||||
(DbDriver::Postgres, "n.nspname"),
|
||||
(DbDriver::Mysql, "c.table_schema"),
|
||||
(DbDriver::Clickhouse, "c.database"),
|
||||
(DbDriver::Snowflake, "c.table_schema"),
|
||||
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
|
||||
(DbDriver::Sqlite, "'main'"),
|
||||
] {
|
||||
let only = completion_columns(driver, CompletionScope::Only("app"));
|
||||
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
|
||||
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
|
||||
let rest = completion_columns(driver, CompletionScope::Except("app"));
|
||||
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
|
||||
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
|
||||
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_catalog_queries_run_on_older_servers() {
|
||||
let pg = DbDriver::Postgres;
|
||||
@@ -1279,7 +1340,7 @@ mod tests {
|
||||
tables(pg, "s"),
|
||||
columns(pg, "s", "t"),
|
||||
indexes(pg, "s", "t"),
|
||||
completion_columns(pg).to_owned(),
|
||||
completion_columns(pg, CompletionScope::All),
|
||||
foreign_keys(pg).to_owned(),
|
||||
table_foreign_keys(pg, "s", "t"),
|
||||
triggers(pg, "s", "t"),
|
||||
@@ -1290,7 +1351,7 @@ mod tests {
|
||||
let upper = q.to_uppercase();
|
||||
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
|
||||
}
|
||||
assert_eq!(postgres_legacy(completion_columns(pg)), None);
|
||||
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
|
||||
@@ -779,3 +779,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "wide".into();
|
||||
source.options.startup_script = format!("SET search_path = {schema}");
|
||||
sources.push(source);
|
||||
let password = server().map(|(.., password)| password);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("wide", password, false).await?;
|
||||
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
|
||||
let fill = format!(
|
||||
"DO $$ DECLARE cols text; BEGIN \
|
||||
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
|
||||
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
|
||||
END LOOP; END $$"
|
||||
);
|
||||
let result = async {
|
||||
db.execute("p", &fill, 1, &c).await?;
|
||||
let completion = db.completion("wide").await?;
|
||||
assert_eq!(completion.default_schema, schema);
|
||||
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
|
||||
assert_eq!(wide.len(), 260);
|
||||
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
|
||||
result
|
||||
}
|
||||
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
|
||||
@@ -46,18 +46,26 @@ fn main() {
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
|
||||
std::process::exit(2);
|
||||
};
|
||||
// `--replace`: stop another build's backend that still holds the project.
|
||||
let replace = args.get(2).is_some_and(|a| a == "--replace");
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let code = match ide_host::daemon::attach(
|
||||
&base,
|
||||
&home,
|
||||
project_path,
|
||||
replace,
|
||||
std::io::stdin(),
|
||||
std::io::stdout().lock(),
|
||||
) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
let mode = match args.as_slice() {
|
||||
|
||||
@@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket.
|
||||
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
|
||||
/// refuses to retire is stopped first.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
@@ -137,11 +139,11 @@ pub fn attach(
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
@@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<Unix
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
match existing_daemon(paths, build) {
|
||||
Ok(Some(stream)) => return Ok(stream),
|
||||
Ok(None) => {}
|
||||
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
@@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
@@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
|
||||
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
|
||||
fn stop_daemon(socket: &Path) -> Result<(), String> {
|
||||
let pids = daemon_pids(socket)?;
|
||||
if pids.is_empty() {
|
||||
return Err(format!("cannot find the backend serving {}", socket.display()));
|
||||
}
|
||||
let signal = |sig| {
|
||||
for pid in &pids {
|
||||
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
|
||||
let _ = rustix::process::kill_process(pid, sig);
|
||||
}
|
||||
}
|
||||
};
|
||||
let alive = || pids.iter().any(|pid| process_exists(*pid));
|
||||
signal(rustix::process::Signal::TERM);
|
||||
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
|
||||
while alive() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if alive() {
|
||||
signal(rustix::process::Signal::KILL);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
|
||||
fn process_exists(pid: i32) -> bool {
|
||||
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
Command::new("ps")
|
||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
||||
.output()
|
||||
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
|
||||
}
|
||||
|
||||
/// Processes started as `openidea-server --daemon <socket> <build>`.
|
||||
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
|
||||
let out = Command::new("ps")
|
||||
.args(["-axww", "-o", "pid=", "-o", "args="])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot list processes: {e}"))?;
|
||||
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
|
||||
ps.lines()
|
||||
.filter_map(|line| {
|
||||
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
|
||||
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
|
||||
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
@@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool {
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::daemon_pids_in;
|
||||
|
||||
#[test]
|
||||
fn finds_the_daemon_of_a_socket_in_the_process_list() {
|
||||
let ps = " 1 /sbin/init\n\
|
||||
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
|
||||
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
|
||||
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
|
||||
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
|
||||
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
|
||||
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -378,6 +378,7 @@ impl Host {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
|
||||
@@ -32,12 +32,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
let agents = if is_jvm_launch(&config) {
|
||||
let mut agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for(java_exec.as_deref())
|
||||
} else {
|
||||
Default::default()
|
||||
ide_run::java_agent::Agents::default()
|
||||
};
|
||||
match enhanced {
|
||||
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
|
||||
Some(Err(note)) => agents.notes.push(note),
|
||||
None => {}
|
||||
}
|
||||
let config = add_java_agents(config, &agents.options);
|
||||
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
@@ -249,6 +256,21 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
|
||||
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
|
||||
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
|
||||
/// console line saying why the session runs without it.
|
||||
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
(on && is_jvm_launch(config))
|
||||
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
@@ -380,13 +402,25 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
|
||||
config
|
||||
}
|
||||
|
||||
/// This window's breakpoints of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_breakpoints(path, breakpoints).await
|
||||
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of this window's line breakpoints with `files`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_replace_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.replace_breakpoints(host.owner_window(window), files).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -629,18 +663,20 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_function_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_function_breakpoints(breakpoints).await
|
||||
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
/// Field watchpoints; states aligned with `breakpoints`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_data_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_data_breakpoints(breakpoints).await
|
||||
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -916,6 +952,49 @@ mod tests {
|
||||
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = |name: &str, implementor: &str| {
|
||||
let home = tmp.path().join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
home.join("bin/java").to_string_lossy().into_owned()
|
||||
};
|
||||
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let mut config = launch(
|
||||
"java-debug",
|
||||
"launch",
|
||||
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
|
||||
);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
|
||||
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
|
||||
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
|
||||
|
||||
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
|
||||
for (adapter, request, extra) in [
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
|
||||
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
|
||||
] {
|
||||
let mut config = launch(adapter, request, extra);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), None);
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_server_port_only_for_local_java_debug() {
|
||||
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
|
||||
@@ -962,6 +1041,7 @@ ide_command::domain!(
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
debug_restart_frame,
|
||||
debug_resume,
|
||||
|
||||
@@ -222,6 +222,9 @@ impl Host {
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
|
||||
}
|
||||
if cfg.name == "jdtls" {
|
||||
// Before anything reads the install the command resolves to.
|
||||
let managed = ide_tools::tools_dir(&data_dir).join("jdtls").join("bin").join("jdtls");
|
||||
ide_sdk::jdtls::skip_plain_launcher_wrappers(cfg, &managed);
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
let cache = match &member {
|
||||
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
|
||||
|
||||
@@ -32,6 +32,10 @@ use std::sync::{Arc, OnceLock};
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
/// What `openidea-server --attach` reports when another build's backend keeps the project
|
||||
/// (clients match it to offer stopping that backend).
|
||||
pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \
|
||||
unsaved changes. Reconnect with that build, or stop its backend and open the project again.";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
/// Advertised only by a persistent backend with an editable idle timeout.
|
||||
|
||||
@@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!rejected.status.success());
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}");
|
||||
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
|
||||
let resumed = old_open().await;
|
||||
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
|
||||
@@ -798,6 +798,60 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
/// `--attach --replace` stops another build's backend that refuses to retire (#6119).
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn replace_stops_another_builds_busy_backend() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
const OLD_BUILD: &str = "fedcba9876543210";
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("h");
|
||||
let base = tmp.path().join("s");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
let mut previous_build = tokio::process::Command::new(SERVER)
|
||||
.arg("--daemon")
|
||||
.arg(&guard.0)
|
||||
.arg(OLD_BUILD)
|
||||
.envs(server_env(&home, &base, 10_800))
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
let old = Peer::connect(reader, writer, Arc::new(Client::default()));
|
||||
initialize(&old).await;
|
||||
let term = looping_terminal(&old, &project).await;
|
||||
old.kill();
|
||||
old.closed().await;
|
||||
|
||||
let client = Arc::new(Client::default());
|
||||
let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec();
|
||||
let env = server_env(&home, &base, 10_800);
|
||||
let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap();
|
||||
initialize(&new).await;
|
||||
let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap();
|
||||
assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}");
|
||||
until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
|
||||
assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty());
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
|
||||
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Enhanced class redefinition for Java debug sessions: on JetBrains Runtime,
|
||||
//! `-XX:+AllowEnhancedClassRedefinition` lets HotSwap (Reload Changed Classes) apply
|
||||
//! structural changes such as added or removed methods and fields. Other JVMs refuse to
|
||||
//! start with the flag, so it is added only when the launched JDK is JetBrains Runtime.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The JVM flag JetBrains Runtime takes.
|
||||
pub const OPTION: &str = "-XX:+AllowEnhancedClassRedefinition";
|
||||
|
||||
/// The flag when `java` (the launched `bin/java`; `None` when unknown) is JetBrains Runtime,
|
||||
/// else the console line saying why the session runs without it.
|
||||
pub fn enhanced_redefinition(java: Option<&Path>) -> Result<&'static str, String> {
|
||||
let java = java.filter(|java| java.components().count() > 1);
|
||||
match java {
|
||||
Some(java) if crate::java_agent::jdk_allows(Some(java), Some("jetbrains")) => Ok(OPTION),
|
||||
Some(java) => Err(format!(
|
||||
"Enhanced class redefinition is off for this session: {} is not a JetBrains Runtime. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE.",
|
||||
java.display()
|
||||
)),
|
||||
None => Err("Enhanced class redefinition is off for this session: the JDK it runs on is unknown. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE."
|
||||
.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn jdk(dir: &Path, implementor: &str) -> std::path::PathBuf {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
let java = bin.join("java");
|
||||
std::fs::write(&java, "").unwrap();
|
||||
java
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jetbrains_runtime_gets_the_flag() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "JetBrains s.r.o.");
|
||||
assert_eq!(enhanced_redefinition(Some(&java)), Ok(OPTION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_jdks_get_a_note_instead() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "Eclipse Adoptium");
|
||||
let note = enhanced_redefinition(Some(&java)).unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
assert!(note.contains(&java.display().to_string()), "{note}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_jdk_gets_a_note() {
|
||||
assert!(enhanced_redefinition(None).unwrap_err().contains("is unknown"));
|
||||
// A bare `java` names no JDK.
|
||||
assert!(enhanced_redefinition(Some(Path::new("java"))).unwrap_err().contains("is unknown"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod gradle_jvm;
|
||||
pub mod import;
|
||||
pub mod java_agent;
|
||||
pub mod java_cmdline;
|
||||
pub mod java_hotswap;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
|
||||
@@ -228,6 +228,45 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether `script` is a hand-written `jdtls` that starts the Equinox launcher with `java -jar`
|
||||
/// itself, like the one opencode puts into a JDK's `bin` (#6062). It knows none of the release
|
||||
/// script's options: each `--jvm-arg=` (the Lombok agent, heap, proxy) reaches jdtls as an
|
||||
/// application argument instead of a JVM option, and its own `-data` comes before the IDE's.
|
||||
fn is_plain_launcher_wrapper(script: &Path) -> bool {
|
||||
if std::fs::metadata(script).map_or(true, |m| m.len() > 64 * 1024) {
|
||||
return false;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(script) else { return false };
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
text.contains("org.eclipse.equinox.launcher") && !text.contains("--jvm-arg")
|
||||
}
|
||||
|
||||
/// Picks the `jdtls` to start when the first one on `PATH` is a [plain launcher
|
||||
/// wrapper](is_plain_launcher_wrapper): the next one there that isn't, else the IDE's own
|
||||
/// install (`managed`, `<tools>/jdtls/bin/jdtls`), which is offered for install while missing.
|
||||
/// A command naming a path is the user's choice and kept.
|
||||
pub fn skip_plain_launcher_wrappers(cfg: &mut LanguageServerConfig, managed: &Path) {
|
||||
if cfg.name != "jdtls" || Path::new(&cfg.command).components().count() != 1 {
|
||||
return;
|
||||
}
|
||||
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).unwrap_or_else(ide_core::tool_path::search_path);
|
||||
let mut candidates = std::env::split_paths(&search)
|
||||
.filter(|dir| !dir.as_os_str().is_empty())
|
||||
.filter_map(|dir| ide_core::process::find_executable(&cfg.command, dir.as_os_str()));
|
||||
let Some(first) = candidates.next() else { return };
|
||||
if !is_plain_launcher_wrapper(&first) {
|
||||
return;
|
||||
}
|
||||
let chosen = candidates.find(|c| !is_plain_launcher_wrapper(c)).unwrap_or_else(|| managed.to_path_buf());
|
||||
tracing::warn!(
|
||||
"{} starts jdtls with `java -jar` itself and ignores the IDE's JVM arguments (Lombok agent, \
|
||||
workspace); using {} instead",
|
||||
first.display(),
|
||||
chosen.display()
|
||||
);
|
||||
cfg.command = chosen.to_string_lossy().into_owned();
|
||||
}
|
||||
|
||||
/// The release script a `jdtls` command on `PATH` resolves to: itself when it
|
||||
/// already is one, or the script its Scoop shim launches. `None` for a command
|
||||
/// that is neither a release script nor a jdtls Scoop shim.
|
||||
@@ -560,6 +599,57 @@ mod tests {
|
||||
assert_eq!(find_install(home, "macos", "aarch64").unwrap().config, home.join("config_mac_arm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_java_jar_wrapper_first_on_path_is_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = |dir: &Path, text: &str| {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let name = if cfg!(windows) { "jdtls.cmd" } else { "jdtls" };
|
||||
std::fs::write(dir.join(name), text).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(dir.join(name), std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
dir.join(name)
|
||||
};
|
||||
// opencode's wrapper (#6062), then a release script.
|
||||
let wrapper = exe(
|
||||
&dir.path().join("jdk/bin"),
|
||||
"\"%JAVA_HOME%\\bin\\java\" -jar \"%JDTLS_HOME%\\plugins\\org.eclipse.equinox.launcher_1.7.100.jar\" -data \"%DATA_DIR%\" %*\n",
|
||||
);
|
||||
let release = exe(
|
||||
&dir.path().join("jdtls/bin"),
|
||||
"parser.add_argument('--jvm-arg', action='append')\nlauncher = 'org.eclipse.equinox.launcher_*.jar'\n",
|
||||
);
|
||||
let managed = dir.path().join("tools/jdtls/bin/jdtls");
|
||||
let cfg = |dirs: &[&Path]| -> LanguageServerConfig {
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
let path = std::env::join_paths(dirs.iter().map(|d| d.parent().unwrap())).unwrap();
|
||||
cfg.env.insert("PATH".into(), path.to_string_lossy().into_owned());
|
||||
cfg
|
||||
};
|
||||
|
||||
let mut next = cfg(&[&wrapper, &release]);
|
||||
skip_plain_launcher_wrappers(&mut next, &managed);
|
||||
assert_eq!(Path::new(&next.command), release);
|
||||
|
||||
let mut only = cfg(&[&wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut only, &managed);
|
||||
assert_eq!(Path::new(&only.command), managed, "the IDE's install, offered while missing");
|
||||
|
||||
let mut release_first = cfg(&[&release, &wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut release_first, &managed);
|
||||
assert_eq!(release_first.command, "jdtls");
|
||||
|
||||
// Wrappers that delegate (Homebrew's, a Scoop shim) and named commands are kept.
|
||||
let brew = exe(&dir.path().join("brew/bin"), "#!/bin/bash\nexec \"/opt/jdtls/libexec/bin/jdtls\" \"$@\"\n");
|
||||
let mut delegating = cfg(&[&brew, &release]);
|
||||
skip_plain_launcher_wrappers(&mut delegating, &managed);
|
||||
assert_eq!(delegating.command, "jdtls");
|
||||
let mut named = cfg(&[&wrapper]);
|
||||
named.command = wrapper.to_string_lossy().into_owned();
|
||||
skip_plain_launcher_wrappers(&mut named, &managed);
|
||||
assert_eq!(Path::new(&named.command), wrapper);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rewrites_the_release_script_to_java() {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "../src/platform/ipc";
|
||||
import { setInvokeRoute } from "../src/platform/tauriCore";
|
||||
import { schemeCss } from "../src/platform/colorScheme";
|
||||
import { lspDoc } from "../src/editor/lsp/lsp";
|
||||
import { semanticExtension } from "../src/editor/lsp/semantic";
|
||||
import { lspTheme } from "../src/editor/lsp/theme";
|
||||
|
||||
setInvokeRoute(() => null);
|
||||
commands.lspSemanticTokens = async () => ({
|
||||
status: "ok",
|
||||
data: {
|
||||
tokenTypes: ["namespace"],
|
||||
tokenModifiers: ["defaultLibrary", "globalScope"],
|
||||
data: [0, 0, 7, 0, 2, 1, 0, 3, 0, 3],
|
||||
},
|
||||
});
|
||||
const mode = new URLSearchParams(location.search).has("light") ? "light" : "dark";
|
||||
const style = document.createElement("style");
|
||||
style.textContent = schemeCss(mode, {
|
||||
[mode]: {
|
||||
packageReference: { foreground: "#446688" },
|
||||
predefined: { foreground: "#cc5500" },
|
||||
},
|
||||
});
|
||||
document.head.append(style);
|
||||
new EditorView({
|
||||
parent: document.body,
|
||||
doc: "example::hello();\nstd::cout << 1;",
|
||||
extensions: [
|
||||
lspTheme,
|
||||
lspDoc.of({ doc: 1, path: "demo.cpp", language: "cpp", uiMode: "C++", readOnly: false }),
|
||||
semanticExtension(),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./cppNamespaceStyle.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
for (const mode of ["dark", "light"]) {
|
||||
test(`C++ standard and user namespaces share the namespace colour (${mode})`, async ({ page }) => {
|
||||
await page.goto(`/e2e/cppNamespaceStyle.html${mode === "light" ? "?light" : ""}`);
|
||||
const namespaces = page.locator(".cm-sem-namespace");
|
||||
await expect(namespaces).toHaveCount(2);
|
||||
for (const namespace of await namespaces.all()) {
|
||||
await expect(namespace).toHaveCSS("color", "rgb(68, 102, 136)");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -78,7 +78,8 @@ test("precise filter values are ordered and filtering composes with result sorti
|
||||
const values = page.getByRole("group", { name: "Values", exact: true });
|
||||
const ascending = [integers[3]!, integers[2]!, integers[1]!, integers[0]!];
|
||||
await expect(values.locator("label")).toHaveText(ascending);
|
||||
await values.getByRole("checkbox", { name: integers[3], exact: true }).uncheck();
|
||||
// Checked values are the rows shown.
|
||||
for (const value of ascending.slice(1)) await values.getByRole("checkbox", { name: value, exact: true }).check();
|
||||
await page.keyboard.press("Escape");
|
||||
await grid
|
||||
.getByRole("columnheader", { name: /^value\b/ })
|
||||
|
||||
@@ -164,7 +164,7 @@ async fn install(
|
||||
|
||||
/// The arguments of `docker` that start the server in the container: in the project folder, told
|
||||
/// that the folder is trusted and that the CLI already ran the lifecycle commands.
|
||||
fn server_args(up: &Up, bin: &str) -> Vec<String> {
|
||||
fn server_args(up: &Up, bin: &str, replace: bool) -> Vec<String> {
|
||||
let mut args: Vec<String> = ["exec", "-i", "-u", &up.user, "-w", &up.folder].map(str::to_owned).into();
|
||||
for var in [
|
||||
format!("{}={}", ide_host::trust::TRUSTED_ROOT_ENV, up.folder),
|
||||
@@ -173,6 +173,9 @@ fn server_args(up: &Up, bin: &str) -> Vec<String> {
|
||||
args.extend(["-e".to_owned(), var]);
|
||||
}
|
||||
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
@@ -183,6 +186,7 @@ pub(crate) async fn connect(
|
||||
state: &crate::state::AppState,
|
||||
folder: &str,
|
||||
config: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
progress: &Arc<Progress>,
|
||||
@@ -215,16 +219,23 @@ pub(crate) async fn connect(
|
||||
let up = up(&cli, &docker, &local, config, tail).await?;
|
||||
let bin = ensure_server(state, &docker, &up, progress).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let peer = spawn(&docker, &up, &bin, handler, tail)?;
|
||||
let peer = spawn(&docker, &up, &bin, replace, handler, tail)?;
|
||||
let folder = up.folder.clone();
|
||||
Ok((peer, folder, Exec::new(docker, up, bin)))
|
||||
}
|
||||
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, replace: bool, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
let tail = tail.clone();
|
||||
let program = docker.to_string_lossy();
|
||||
Peer::spawn(&program, &server_args(up, bin), &std::env::temp_dir(), &[], handler, Box::new(move |l| tail.push(l)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
Peer::spawn(
|
||||
&program,
|
||||
&server_args(up, bin, replace),
|
||||
&std::env::temp_dir(),
|
||||
&[],
|
||||
handler,
|
||||
Box::new(move |l| tail.push(l)),
|
||||
)
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -237,7 +248,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_server_starts_in_the_folder_trusted_and_without_the_lifecycle() {
|
||||
let up = Up { container: ID.into(), user: "vscode".into(), folder: "/workspaces/my app".into() };
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server");
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server", false);
|
||||
assert_eq!(
|
||||
args,
|
||||
[
|
||||
@@ -374,7 +385,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let dir = version_dir(&found.home, "0.0.0-test");
|
||||
let bin = install(&docker, &up, &dir, "b1", &server, &progress).await.unwrap();
|
||||
assert_eq!(probe(&docker, &up, "0.0.0-test").await.unwrap().installed, std::slice::from_ref(&bin));
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &tail).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &tail).unwrap();
|
||||
let info: ide_host::rpc::ServerInfo = peer
|
||||
.request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None)
|
||||
.await
|
||||
@@ -446,7 +457,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
|
||||
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
|
||||
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(30), async {
|
||||
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
|
||||
assert_eq!(project["root"], up.folder);
|
||||
|
||||
@@ -673,6 +673,7 @@ pub async fn remote_connect(
|
||||
state: State<'_, AppState>,
|
||||
target: RemoteTarget,
|
||||
mut path: String,
|
||||
replace: bool,
|
||||
on_progress: Channel<RemoteProgress>,
|
||||
) -> IdeResult<RemoteProject> {
|
||||
let progress: Arc<Progress> = Arc::new(move |stage, fraction| {
|
||||
@@ -704,9 +705,10 @@ pub async fn remote_connect(
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let stream = session
|
||||
.exec_stream(&format!(
|
||||
"{} --attach {} 2>&1",
|
||||
"{} --attach {}{} 2>&1",
|
||||
ide_ssh::shell::tilde_quote(&bin),
|
||||
ide_ssh::shell::quote(attach_arg),
|
||||
if replace { " --replace" } else { "" },
|
||||
))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
@@ -723,12 +725,12 @@ pub async fn remote_connect(
|
||||
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, replace, handler, &tail)?;
|
||||
(peer, None, distro.clone(), format!("WSL: {distro}"))
|
||||
}
|
||||
RemoteTarget::DevContainer { folder, config } => {
|
||||
let (peer, root, run) =
|
||||
crate::remote_container::connect(&state, folder, config, handler, &tail, &progress).await?;
|
||||
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
|
||||
path = root;
|
||||
exec = Some(Arc::new(run));
|
||||
let name = std::path::Path::new(folder)
|
||||
@@ -740,6 +742,11 @@ pub async fn remote_connect(
|
||||
// A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too).
|
||||
let with_output = |e: IdeError| match tail.text() {
|
||||
t if t.is_empty() => e,
|
||||
// Another build's backend holds the project: the window offers to stop it (#6119).
|
||||
t if t.contains(ide_host::rpc::OTHER_BUILD_BUSY) => IdeError {
|
||||
data: Some(ide_core::error::ErrorData::RemoteBackendBusy),
|
||||
..IdeError::unavailable(ide_host::rpc::OTHER_BUILD_BUSY)
|
||||
},
|
||||
t => IdeError::unavailable(format!("{}: {t}", e.message)),
|
||||
};
|
||||
let info: ServerInfo = peer
|
||||
|
||||
@@ -187,10 +187,11 @@ pub(crate) fn spawn(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, replace, handler, tail)
|
||||
}
|
||||
|
||||
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
|
||||
@@ -199,10 +200,15 @@ fn spawn_with(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
let mut args: Vec<String> =
|
||||
["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
let tail = tail.clone();
|
||||
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
|
||||
@@ -305,7 +311,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
std::fs::write(&launcher, script).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tail = Tail::default();
|
||||
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
|
||||
let peer =
|
||||
spawn_with(launcher.to_str().unwrap(), distro, bin, project, false, Arc::new(Silent), &tail).unwrap();
|
||||
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
|
||||
panic!("{e:?}; launcher said: {}", tail.text());
|
||||
});
|
||||
@@ -314,7 +321,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_distro_name_never_starts_the_launcher() {
|
||||
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
let err =
|
||||
spawn_with("does-not-exist", "-d", "/x", "~", false, Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
assert!(err.message.contains("not a valid"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,7 @@ debug_jvm_thread_dump trusted project_host bin
|
||||
debug_listen_for_jvm trusted project_host bindings async
|
||||
debug_pause trusted project_host bindings async
|
||||
debug_redefine_classes trusted project_host bindings async
|
||||
debug_replace_breakpoints trusted project_host bindings async
|
||||
debug_resolve_variable trusted project_host bindings async
|
||||
debug_restart_frame trusted project_host bindings async
|
||||
debug_resume trusted project_host bindings async
|
||||
|
||||
@@ -480,6 +480,8 @@ export const commands = {
|
||||
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
|
||||
/** HotSwap (Reload Changed Classes) in a java-debug session. */
|
||||
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
|
||||
/** Replaces all of this window's line breakpoints with `files`. */
|
||||
debugReplaceBreakpoints: (files: { [key in string]: Breakpoint[] }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_replace_breakpoints", { files })),
|
||||
debugResolveVariable: (session: DebugSessionId, variable: Variable_Deserialize) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_resolve_variable", { session, variable })),
|
||||
/** Reset Frame (Drop Frame). */
|
||||
debugRestartFrame: (session: DebugSessionId, frameId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_restart_frame", { session, frameId })),
|
||||
@@ -490,6 +492,7 @@ export const commands = {
|
||||
debugSendInput: (session: DebugSessionId, text: string) => typedError<null, IdeError>(__TAURI_INVOKE("debug_send_input", { session, text })),
|
||||
/** This window's live sessions, including adapter-started child sessions. */
|
||||
debugSessions: () => typedError<SessionInfo[], IdeError>(__TAURI_INVOKE("debug_sessions")),
|
||||
/** This window's breakpoints of `path`. */
|
||||
debugSetBreakpoints: (path: string, breakpoints: Breakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_breakpoints", { path, breakpoints })),
|
||||
/** Field watchpoints; states aligned with `breakpoints`. */
|
||||
debugSetDataBreakpoints: (breakpoints: DataBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_data_breakpoints", { breakpoints })),
|
||||
@@ -1514,7 +1517,7 @@ export const commands = {
|
||||
* dev container, whose project folder is the container's own) in this window (installs /
|
||||
* starts the server as needed).
|
||||
*/
|
||||
remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, onProgress })),
|
||||
remoteConnect: (target: RemoteTarget, path: string, replace: boolean, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, replace, onProgress })),
|
||||
/** The remote session of this window (a settings window: its parent's), if any. */
|
||||
remoteCurrent: () => __TAURI_INVOKE<{
|
||||
target: RemoteTarget,
|
||||
@@ -6852,7 +6855,9 @@ report?: PushReport | null } |
|
||||
* jdtls could not set a module up as a Java project: the errors on its build files and
|
||||
* the builds enclosing it (`path: message`, the path relative to the project), nearest first.
|
||||
*/
|
||||
{ type: "javaBuildProblems"; problems: string[] };
|
||||
{ type: "javaBuildProblems"; problems: string[] } |
|
||||
/** A remote backend of another OpenIDEA build still serves the project and refused to retire. */
|
||||
{ type: "remoteBackendBusy" };
|
||||
|
||||
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
|
||||
/** The requested state is stale; the UI must use the current snapshot. */
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { semanticRanges } from "../index";
|
||||
|
||||
const doc = Text.of(["std"]);
|
||||
const token = (type: string, modifiers: string[], language = "cpp") =>
|
||||
semanticRanges(
|
||||
doc,
|
||||
{ tokenTypes: [type], tokenModifiers: modifiers, data: [0, 0, 3, 0, (1 << modifiers.length) - 1] },
|
||||
false,
|
||||
language,
|
||||
)[0]?.className.split(" ");
|
||||
|
||||
describe("C++ namespace semantic tokens", () => {
|
||||
it.each(["cpp", "CPP"])("keeps standard-library namespaces in the namespace colour (%s)", (language) => {
|
||||
expect(token("namespace", ["defaultLibrary", "globalScope"], language)).toEqual(["cm-sem-namespace"]);
|
||||
expect(token("namespace", ["defaultLibrary"], language)).toEqual(token("namespace", [], language));
|
||||
});
|
||||
|
||||
it("preserves namespace declaration and deprecation styles", () => {
|
||||
expect(token("namespace", ["defaultLibrary", "declaration", "deprecated"])).toEqual([
|
||||
"cm-sem-namespace",
|
||||
"cm-sem-declaration",
|
||||
"cm-sem-deprecated",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["class", "function", "variable"])("preserves builtin colouring for %s tokens", (type) => {
|
||||
expect(token(type, ["defaultLibrary"])).toContain("cm-sem-builtin");
|
||||
});
|
||||
|
||||
it("leaves other languages' namespace colouring unchanged", () => {
|
||||
expect(token("namespace", ["defaultLibrary"], "rust")).toEqual(["cm-sem-namespace", "cm-sem-builtin"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { registerLanguageSemantics } from "../languages";
|
||||
|
||||
registerLanguageSemantics("cpp", {
|
||||
tokenClasses({ type, classes }) {
|
||||
// clangd marks std and other library namespaces as defaultLibrary; keep their namespace colour.
|
||||
if (type !== "namespace") return;
|
||||
const builtin = classes.indexOf("cm-sem-builtin");
|
||||
if (builtin >= 0) classes.splice(builtin, 1);
|
||||
},
|
||||
});
|
||||
@@ -33,6 +33,7 @@ import "./php";
|
||||
import "./go";
|
||||
import "./java";
|
||||
import "./javascript";
|
||||
import "./cpp";
|
||||
|
||||
const semanticBackoff = featureBackoff();
|
||||
|
||||
|
||||
@@ -266,6 +266,37 @@ describe("HotSwap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("points a refused structural change to Enhanced class redefinition when the configuration has it off", async () => {
|
||||
const refused = "Failed to redefine classes: add method not implemented";
|
||||
const hint = "turn on Enhanced class redefinition in the run configuration";
|
||||
expect(hotSwapMessage(0, [refused], false, true).body).toContain(hint);
|
||||
expect(hotSwapMessage(0, [refused], false, false).body).toBe(refused);
|
||||
expect(hotSwapMessage(0, ["boom"], false, true).body).toBe("boom");
|
||||
|
||||
const withConfig = (kind: string, params: Record<string, string>) => ({
|
||||
...session(1, true),
|
||||
runConfig: { id: kind, kind, params } as unknown as NonNullable<DebugSession["runConfig"]>,
|
||||
});
|
||||
ipc.debugRedefineClasses.mockImplementation(() => ipc.ok({ changedClasses: [], errorMessage: refused }));
|
||||
for (const [s, shown] of [
|
||||
[withConfig("application", {}), true],
|
||||
[withConfig("spring-boot", {}), true],
|
||||
[withConfig("application", { enhancedClassRedefinition: "true" }), false],
|
||||
[withConfig("tomcat", {}), false],
|
||||
[session(1, true), false],
|
||||
] as const) {
|
||||
useDebug.setState({ sessions: { 1: s } });
|
||||
// oxlint-disable-next-line no-await-in-loop -- one reload per session shape; each assertion reads its notification
|
||||
await reloadChangedClasses(false);
|
||||
expect(notes.at(-1)).toMatchObject({ level: "error", title: "Hot Swap failed" });
|
||||
expect(String(notes.at(-1)!.body).includes(hint)).toBe(shown);
|
||||
}
|
||||
|
||||
useDebug.setState({ sessions: { 1: withConfig("application", {}) } });
|
||||
onHotCodeReplace(1 as DebugSessionId, { kind: "hotCodeReplace", changeType: "ERROR", message: refused });
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Hot Swap", body: expect.stringContaining(hint) });
|
||||
});
|
||||
|
||||
function pausedFrames(names: string[], restartFrame = true): DebugSession {
|
||||
return {
|
||||
...session(1, true),
|
||||
|
||||
@@ -157,6 +157,14 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("asks the host for enhanced class redefinition when the configuration turns it on", async () => {
|
||||
const on = { ...app, params: { enhancedClassRedefinition: "true" } };
|
||||
expect(JSON.parse((await javaLaunchConfig(on, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
expect(JSON.parse((await javaLaunchConfig(app, "/p")).extraJson!)).not.toHaveProperty("enhancedClassRedefinition");
|
||||
const kotlin = { ...on, debugAdapter: "kotlin-debug-adapter" };
|
||||
expect(JSON.parse((await javaLaunchConfig(kotlin, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
});
|
||||
|
||||
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
|
||||
for (const how of ["jarmanifest", "argfile"]) {
|
||||
shortenCommandLine = how;
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
debugSetBreakpoints: vi.fn(),
|
||||
debugReplaceBreakpoints: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
|
||||
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugCapabilities: vi.fn(async () => ({ status: "ok", data: {} })),
|
||||
@@ -169,6 +170,24 @@ it("drains an in-flight update and sends pending removals before startup", async
|
||||
expect(ipc.debugStart).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("hands the window's whole list to the backend before startup, even after a failed removal (#6116)", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValueOnce({ status: "ok", data: [] }).mockRejectedValueOnce(new Error("lost"));
|
||||
addBreakpoint("/p/Main.java", 4);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
removeAllBreakpoints();
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
addBreakpoint("/p/Other.java", 7);
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
ipc.debugReplaceBreakpoints.mockClear();
|
||||
await startSession(config("launch"));
|
||||
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledExactlyOnceWith({
|
||||
"/p/Other.java": [expect.objectContaining({ line: 7, enabled: true })],
|
||||
});
|
||||
expect(ipc.debugReplaceBreakpoints.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
ipc.debugStart.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
});
|
||||
|
||||
it("flushes persisted breakpoints immediately after project loading", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -87,6 +87,8 @@ export function loadBreakpoints(root: string | null) {
|
||||
}
|
||||
const previous = Object.keys(useBreakpoints.getState().byFile);
|
||||
useBreakpoints.setState({ root, byFile, muted, status: {} });
|
||||
// The backend may still hold files this window no longer lists (a reloaded window).
|
||||
void replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
for (const path of new Set([...previous, ...Object.keys(byFile)])) scheduleSync(path);
|
||||
}
|
||||
|
||||
@@ -129,6 +131,17 @@ async function drainBreakpoints() {
|
||||
await Promise.all([...paths].map((path) => syncFile(path)));
|
||||
paths = new Set([...timers.keys(), ...inFlight.keys()]);
|
||||
}
|
||||
// The new session gets exactly the files listed here, even if a removal never reached the
|
||||
// backend (#6116). Failing that, the session still starts with what the backend has.
|
||||
await replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
}
|
||||
|
||||
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
|
||||
async function replaceBreakpoints() {
|
||||
if (!isTauri() || useProject.getState().project?.trusted === false) return;
|
||||
const { byFile, muted } = useBreakpoints.getState();
|
||||
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
|
||||
await call(commands.debugReplaceBreakpoints(files));
|
||||
}
|
||||
|
||||
export function syncFile(path: string): Promise<void> {
|
||||
|
||||
@@ -59,15 +59,40 @@ const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`)
|
||||
|
||||
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
|
||||
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
|
||||
// JDI's refusals of a structural change: "add method not implemented", "schema change not implemented", …
|
||||
const structuralChange = (message: string) => /\bnot implemented\b/i.test(message);
|
||||
|
||||
/** Application and Spring Boot configurations offer Enhanced class redefinition (JetBrains Runtime's DCEVM). */
|
||||
const ENHANCEABLE_KINDS = new Set(["application", "spring-boot"]);
|
||||
|
||||
/** Whether the session's configuration could turn on Enhanced class redefinition but has not. */
|
||||
export function canEnhanceRedefinition(s: DebugSession): boolean {
|
||||
const rc = s.runConfig;
|
||||
return !!rc && ENHANCEABLE_KINDS.has(rc.kind) && rc.params?.enhancedClassRedefinition !== "true";
|
||||
}
|
||||
|
||||
/** The failure text, plus how to allow structural changes when JDI refused one and the configuration can. */
|
||||
function failureBody(errors: string[], enhanceable: boolean): string {
|
||||
const body = errors.join("\n");
|
||||
if (!enhanceable || !errors.some(structuralChange)) return body;
|
||||
return (
|
||||
body +
|
||||
"\n\n" +
|
||||
tx(
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Message for the reload result (IDEA wording). */
|
||||
export function hotSwapMessage(
|
||||
changed: number,
|
||||
errors: string[],
|
||||
bottomFrame = false,
|
||||
enhanceable = false,
|
||||
): { level: "info" | "warning" | "error"; title: string; body?: string } {
|
||||
if (errors.some((e) => !obsoleteMethods(e)))
|
||||
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
|
||||
return { level: "error", title: "Hot Swap failed", body: failureBody(errors, enhanceable) };
|
||||
if (errors.length)
|
||||
return {
|
||||
level: "warning",
|
||||
@@ -226,6 +251,7 @@ export async function reloadChangedClasses(build = true, configId?: string, allo
|
||||
changed.size,
|
||||
errors,
|
||||
affected.some((s) => s.status === "paused" && s.frames.length === 1),
|
||||
sessions.some(canEnhanceRedefinition),
|
||||
);
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
@@ -308,7 +334,7 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
|
||||
level: event.changeType === "ERROR" ? "error" : "warning",
|
||||
key: KEY,
|
||||
title: "Hot Swap",
|
||||
body: event.message,
|
||||
body: failureBody([event.message], canEnhanceRedefinition(useDebug.getState().sessions[session]!)),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -174,6 +174,8 @@ export async function javaLaunchConfig(
|
||||
preparation?.report?.(`${joinJavaArgs([resolved.command, ...resolved.args])}\n`);
|
||||
const agentNote = await remoteJavaAgentNote(rc);
|
||||
if (agentNote) preparation?.report?.(agentNote);
|
||||
// The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without.
|
||||
const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {};
|
||||
if (kotlin) {
|
||||
return {
|
||||
name: rc.name,
|
||||
@@ -191,6 +193,7 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command,
|
||||
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
programArgs: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -212,6 +215,7 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command === "java" ? undefined : resolved.command,
|
||||
vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
args: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -243,6 +247,7 @@ export async function javaLaunchConfig(
|
||||
shortenCommandLine: info.shortenCommandLine ?? "none",
|
||||
console: "internalConsole",
|
||||
stopOnEntry: false,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* to it (platform/remote.ts).
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -57,6 +57,16 @@ function trackPortsWindow(): () => void {
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
provideBackendBusyPrompt(() =>
|
||||
confirm({
|
||||
title: tx("Stop Remote Backend"),
|
||||
message: tx(
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
|
||||
),
|
||||
ok: tx("Stop Backend and Open"),
|
||||
icon: "warning",
|
||||
}),
|
||||
),
|
||||
trackPortsWindow(),
|
||||
installReconnect(),
|
||||
installDirenvNotifications(),
|
||||
|
||||
@@ -146,6 +146,16 @@ describe("Application / Spring Boot command line", () => {
|
||||
expect(parsed.programArgs).toEqual(["--server.port=8081", "two words"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["application", applicationType],
|
||||
["spring-boot", springBootType],
|
||||
] as const)("%s offers Enhanced class redefinition for Debug without changing the Run command", (_, type) => {
|
||||
expect(type.fields.find((f) => f.key === "enhancedClassRedefinition")).toMatchObject({ control: "checkbox" });
|
||||
const params = { mainClass: "a.Main", classpath: "${classpath}" };
|
||||
expect(type.commandLine({ ...params, enhancedClassRedefinition: "true" })).toEqual(type.commandLine(params));
|
||||
expect(jarApplicationType.fields.some((f) => f.key === "enhancedClassRedefinition")).toBe(false);
|
||||
});
|
||||
|
||||
it("reads VM options over several lines and with quoted spaces", () => {
|
||||
const line = applicationType.commandLine({
|
||||
mainClass: "a.Main",
|
||||
|
||||
@@ -78,6 +78,17 @@ const jreField: RunConfigTypeField = {
|
||||
})),
|
||||
};
|
||||
|
||||
/**
|
||||
* JetBrains Runtime's `-XX:+AllowEnhancedClassRedefinition` for Debug, so Reload Changed Classes can add or
|
||||
* remove methods and fields. The host adds it only on JetBrains Runtime (other JVMs refuse to start with it).
|
||||
*/
|
||||
const enhancedRedefinitionField: RunConfigTypeField = {
|
||||
key: "enhancedClassRedefinition",
|
||||
label: "Enhanced class redefinition",
|
||||
control: "checkbox",
|
||||
hint: "When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields",
|
||||
};
|
||||
|
||||
/** IDEA's "Use classpath of module": the module whose classpath and build the run uses. */
|
||||
const moduleField: RunConfigTypeField = {
|
||||
key: "module",
|
||||
@@ -119,6 +130,7 @@ function jvmApplicationType(spring: boolean): RunConfigTypeContribution {
|
||||
...(spring ? [profilesField("Comma separated; passed as --spring.profiles.active")] : []),
|
||||
...(spring ? updatePolicyFields(false) : []),
|
||||
jreField,
|
||||
enhancedRedefinitionField,
|
||||
moduleField,
|
||||
{
|
||||
key: "classpath",
|
||||
|
||||
@@ -438,9 +438,12 @@ function TwoPaneDiff({
|
||||
inputKey.current = input.key;
|
||||
// Swap Sides shows the request's sides the other way round; another request starts unswapped.
|
||||
const [swappedFor, setSwappedFor] = useState<DiffData | null>(null);
|
||||
// The one-side viewer puts its only editable document into the unified editor.
|
||||
const indexOnlyLeft = isIndex(input_.left) && input_.right.type === "text" && input_.right.absent;
|
||||
const swapped = !!indexOnlyLeft || swappedFor === input_;
|
||||
// The one-side viewer puts its only editable document into the unified editor. A deleted
|
||||
// file's diff shows the original text as the document itself: the absent side stays on the
|
||||
// left as the diff's original, as for a staged deletion.
|
||||
const deletedOneSided =
|
||||
!(input_.left.type === "text" && input_.left.absent) && input_.right.type === "text" && !!input_.right.absent;
|
||||
const swapped = deletedOneSided || swappedFor === input_;
|
||||
const data = useMemo(
|
||||
() => (swapped ? { ...input_, left: input_.right, right: input_.left } : input_),
|
||||
[input_, swapped],
|
||||
@@ -1788,7 +1791,7 @@ function TwoPaneDiff({
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={clsx(styles.root, fit && styles.fit, indexOnlyLeft && styles.indexDeletion)}
|
||||
className={clsx(styles.root, fit && styles.fit, deletedOneSided && styles.indexDeletion)}
|
||||
onKeyDown={onKeyDown}
|
||||
onFocusCapture={() => {
|
||||
setFocusedDiffNavigator(nav.current);
|
||||
@@ -1994,7 +1997,7 @@ function TwoPaneDiff({
|
||||
size="small"
|
||||
onClick={() => {
|
||||
void Promise.resolve(indexDoc?.save())
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", indexOnlyLeft ? input_ : data))
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", deletedOneSided ? input_ : data))
|
||||
.catch(() => {});
|
||||
}}
|
||||
/>
|
||||
@@ -2049,15 +2052,25 @@ function TwoPaneDiff({
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
// A deleted file's swapped viewer still reads in the request's order: revision → (deleted).
|
||||
<div className={labels}>
|
||||
<span className={styles.label} title={sourceLabels ? `${captionA} → ${captionB}` : undefined}>
|
||||
<span className={styles.labelText}>{sideLabel(left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleA} />}
|
||||
<span
|
||||
className={styles.label}
|
||||
title={
|
||||
sourceLabels ? (deletedOneSided ? `${captionB} → ${captionA}` : `${captionA} → ${captionB}`) : undefined
|
||||
}
|
||||
>
|
||||
<span className={styles.labelText}>{sideLabel(deletedOneSided ? right : left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleB : titleA)} />}
|
||||
{unifiedOnLeft && <span className={styles.badge}>{tx("editable")}</span>}
|
||||
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>} →
|
||||
<span className={styles.labelText}>{sideLabel(right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleB} />}
|
||||
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
|
||||
{eolDiffers && (deletedOneSided ? eolB : eolA) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeB : badgeA}</span>
|
||||
)}{" "}
|
||||
→<span className={styles.labelText}>{sideLabel(deletedOneSided ? left : right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleA : titleB)} />}
|
||||
{eolDiffers && (deletedOneSided ? eolA : eolB) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeA : badgeB}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
|
||||
const texts: Record<string, string> = { HEAD: "a\nb\nc\n" };
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
fsProbe: () => Promise.resolve({ status: "ok", data: { size: 0, binary: false, tooLarge: false } }),
|
||||
vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { DiffEditor } from "../DiffEditor";
|
||||
|
||||
const input = {
|
||||
kind: "diff",
|
||||
key: "diff:deleted",
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "rev", rev: "HEAD" },
|
||||
right: { type: "text", text: "", label: "(deleted)", absent: true },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
|
||||
/** Plain gutter numbers rendered for document lines (skipping the hidden width-calibration spacer). */
|
||||
const gutterNumbers = (container: HTMLElement) =>
|
||||
[...container.querySelectorAll(".cm-lineNumbers .cm-gutterElement")]
|
||||
.filter((n) => (n as HTMLElement).style.visibility !== "hidden")
|
||||
.map((n) => n.textContent)
|
||||
.filter((t) => t && /^\d+$/.test(t));
|
||||
|
||||
describe("line numbers of a deleted file's diff", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => localStorage.clear());
|
||||
|
||||
it("shows the original text as the document itself, numbered like an editor", async () => {
|
||||
const mounted = render(<DiffEditor input={input} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
// "a\nb\nc\n" is four CodeMirror lines, the last one empty, as in the editor itself.
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toEqual(["1", "2", "3", "4"]));
|
||||
const lines = [...mounted.container.querySelectorAll(".cm-content > .cm-line")].map((l) => l.textContent);
|
||||
expect(lines).toEqual(["a", "b", "c", ""]);
|
||||
// No mirrored widget numbers: the lines are real, so the gutter, selection and context
|
||||
// menu behave like the editor's.
|
||||
expect(mounted.container.querySelector(".cm-diffWidgetNumber")).toBeNull();
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the document's own numbers for an added file", async () => {
|
||||
const added = {
|
||||
...input,
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "text", text: "", label: "(does not exist)", absent: true },
|
||||
right: { type: "rev", rev: "HEAD" },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
texts.HEAD = "a\nb\nc\n";
|
||||
const mounted = render(<DiffEditor input={added} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toContain("3"));
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Chunk, MergeView } from "@codemirror/merge";
|
||||
import { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { bandAt, bandPath, transferY, PaddedPanes, UnalignedPanes, type Band } from "../diffScroll";
|
||||
import { collapsedDiffLines } from "../collapsedDiffLines";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -177,6 +178,32 @@ describe("synchronized navigation scrolling", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower pane adjusts scrollTop on measure", () => {
|
||||
vi.useFakeTimers();
|
||||
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Repeated wheel events must not cancel native momentum with scrollTo(instant).
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
expect(p.b.scrollDOM.scrollTo).not.toHaveBeenCalled();
|
||||
// Follower shifts from CodeMirror height measurement must not yank the wheel source back.
|
||||
p.scroll(p.a, 800);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Pointer interaction on the other pane hands control back immediately.
|
||||
p.a.scrollDOM.dispatchEvent(new Event("pointerdown"));
|
||||
p.scroll(p.a, 400);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(400);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
frame.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("padded pane scrolling (aligned diff)", () => {
|
||||
@@ -241,6 +268,60 @@ describe("padded pane scrolling (aligned diff)", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower shifts during layout", () => {
|
||||
vi.useFakeTimers();
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
p.scroll(p.a, 500);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
vi.advanceTimersByTime(150);
|
||||
p.scroll(p.a, 200);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(200);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapsed diff lines", () => {
|
||||
it("defers button DOM replacement from docViewUpdate into CodeMirror's measure write phase", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "a\nb\nc", extensions: [collapsedDiffLines()] }),
|
||||
parent,
|
||||
});
|
||||
const measureSpy = vi.spyOn(view, "requestMeasure");
|
||||
try {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cm-collapsedLines";
|
||||
row.textContent = "10 unchanged lines";
|
||||
view.contentDOM.appendChild(row);
|
||||
const plugin = (
|
||||
view as unknown as { plugins: Array<{ value: { docViewUpdate?: () => void } | null }> }
|
||||
).plugins.find((p) => typeof p.value?.docViewUpdate === "function");
|
||||
expect(plugin).toBeDefined();
|
||||
measureSpy.mockClear();
|
||||
plugin!.value!.docViewUpdate!();
|
||||
// Must not mutate DOM synchronously during docViewUpdate (triggers WebKit scrollTop clamping).
|
||||
expect(row.querySelector("button")).toBeNull();
|
||||
expect(measureSpy).toHaveBeenCalledTimes(1);
|
||||
const req = measureSpy.mock.calls[0]![0] as { write?: (v: unknown, view: EditorView) => void };
|
||||
req.write?.(null, view);
|
||||
expect(row.querySelector("button")).not.toBeNull();
|
||||
expect(row.querySelector("button")?.textContent).toBe("10 unchanged lines");
|
||||
} finally {
|
||||
measureSpy.mockRestore();
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("divider arrows", () => {
|
||||
|
||||
@@ -300,6 +300,26 @@ describe("log controls", () => {
|
||||
expect(rows[0]!.querySelector<HTMLElement>('[class*="colRepository"]')!.style.width).toBe("130px");
|
||||
});
|
||||
|
||||
it("without headers, a row strip on a leading Commit cell resizes the Repository column", async () => {
|
||||
useVcs.setState({ roots: ["/repo", "/other"] });
|
||||
const tip = { ...c("tip"), repo: "/repo" };
|
||||
api.commits = [tip];
|
||||
// Defaults: headers hidden, Commit first.
|
||||
useLogOptions.setState({ showRepository: true });
|
||||
render(<LogView />);
|
||||
const rows = await within(screen.getByRole("listbox", { name: "Commits" })).findAllByRole("option");
|
||||
const strip = rows[0]!.querySelector<HTMLElement>('[class*="colSubject"] > [class*="columnResize"]')!;
|
||||
strip.setPointerCapture = vi.fn();
|
||||
strip.hasPointerCapture = () => true;
|
||||
strip.releasePointerCapture = vi.fn();
|
||||
fireEvent.pointerDown(strip, { button: 0, pointerId: 9, clientX: 100 });
|
||||
fireEvent.pointerMove(strip, { pointerId: 9, clientX: 130 });
|
||||
fireEvent.pointerUp(strip, { pointerId: 9, clientX: 130 });
|
||||
expect(useLogOptions.getState().columnWidths.repository).toBe(130);
|
||||
// The strip swallows the press, so the row is not selected.
|
||||
expect(useGitLog.getState().selected).toBeNull();
|
||||
});
|
||||
|
||||
it("exposes a full-height column divider on data rows", async () => {
|
||||
useLogOptions.setState({ showColumnHeaders: true });
|
||||
render(<LogView />);
|
||||
|
||||
@@ -20,8 +20,13 @@ const collapseButtons = ViewPlugin.define((view) => {
|
||||
row.replaceChildren(button);
|
||||
}
|
||||
};
|
||||
view.requestMeasure({ read: () => null, write: enhance });
|
||||
return { docViewUpdate: enhance };
|
||||
// Defer DOM replacement into CodeMirror's measure write phase rather than mutating synchronously
|
||||
// during docViewUpdate: in WebKit, inserting the inline SVG while updated viewport gaps have not
|
||||
// flushed layout yet causes scrollTop to clamp backwards and trap wheel scrolling in a loop.
|
||||
const measure = { key: enhance, read: () => null, write: enhance };
|
||||
const schedule = () => view.requestMeasure(measure);
|
||||
schedule();
|
||||
return { docViewUpdate: schedule };
|
||||
});
|
||||
|
||||
export function collapsedDiffLines(): Extension {
|
||||
|
||||
@@ -193,17 +193,25 @@ export interface DiffPanes {
|
||||
* of the content, out of reach until the diff is scrolled to its end.
|
||||
*/
|
||||
export class PaddedPanes implements DiffPanes {
|
||||
readonly extension: Extension = [];
|
||||
readonly extension: Extension;
|
||||
private mv: MergeView | null = null;
|
||||
private sync: boolean;
|
||||
private scrolling: Side | null = null;
|
||||
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private wheelLeader: Side | null = null;
|
||||
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
/** The scroll position a pane was last moved to by the other one, to tell its echo from the user. */
|
||||
private readonly moved: Record<Side, number | null> = { a: null, b: null };
|
||||
private readonly cleanup: (() => void)[] = [];
|
||||
|
||||
constructor(sync: boolean) {
|
||||
this.sync = sync;
|
||||
this.extension = EditorView.updateListener.of((u) => {
|
||||
if (u.heightChanged && !u.docChanged && this.mv) {
|
||||
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
|
||||
if (side && this.moved[side] !== null) this.moved[side] = u.view.scrollDOM.scrollTop;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
attach(mv: MergeView) {
|
||||
@@ -211,8 +219,22 @@ export class PaddedPanes implements DiffPanes {
|
||||
for (const side of ["a", "b"] as const) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const onScroll = () => this.scrolled(side);
|
||||
const onWheel = () => {
|
||||
this.interruptScroll();
|
||||
this.leadWheel(side);
|
||||
};
|
||||
const onPointer = () => {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
};
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
this.cleanup.push(() => el.removeEventListener("scroll", onScroll));
|
||||
el.addEventListener("wheel", onWheel, { passive: true });
|
||||
el.addEventListener("pointerdown", onPointer);
|
||||
this.cleanup.push(() => {
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
el.removeEventListener("wheel", onWheel);
|
||||
el.removeEventListener("pointerdown", onPointer);
|
||||
});
|
||||
}
|
||||
this.resync();
|
||||
}
|
||||
@@ -225,12 +247,14 @@ export class PaddedPanes implements DiffPanes {
|
||||
setSync(on: boolean) {
|
||||
if (on === this.sync) return;
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.sync = on;
|
||||
this.resync();
|
||||
}
|
||||
|
||||
scrollTo(side: Side, options: ScrollToOptions) {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
this.view(side).scrollDOM.scrollTo(options);
|
||||
@@ -241,12 +265,14 @@ export class PaddedPanes implements DiffPanes {
|
||||
* other pane's delayed reflow follows it instead of being mistaken for a user scroll pulling back.
|
||||
*/
|
||||
leadScroll(side: Side) {
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
clearTimeout(this.wheelTimer);
|
||||
for (const f of this.cleanup) f();
|
||||
this.mv = null;
|
||||
}
|
||||
@@ -262,6 +288,16 @@ export class PaddedPanes implements DiffPanes {
|
||||
this.releaseScroll();
|
||||
return;
|
||||
}
|
||||
if (this.wheelLeader) {
|
||||
this.moved[from] = null;
|
||||
if (from === this.wheelLeader) {
|
||||
this.leadWheel(from);
|
||||
if (this.sync) this.follow(from);
|
||||
} else if (this.sync) {
|
||||
this.follow(this.wheelLeader);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const el = this.view(from).scrollDOM;
|
||||
const moved = this.moved[from];
|
||||
const echo = moved !== null && Math.abs(el.scrollTop - moved) <= 1;
|
||||
@@ -269,6 +305,17 @@ export class PaddedPanes implements DiffPanes {
|
||||
if (!echo && this.sync) this.follow(from);
|
||||
}
|
||||
|
||||
private leadWheel(side: Side) {
|
||||
this.wheelLeader = this.sync ? side : null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
|
||||
}
|
||||
|
||||
private clearWheel() {
|
||||
this.wheelLeader = null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
}
|
||||
|
||||
private follow(from: Side) {
|
||||
const to: Side = from === "a" ? "b" : "a";
|
||||
const el = this.view(to).scrollDOM;
|
||||
@@ -314,6 +361,8 @@ export class UnalignedPanes implements DiffPanes {
|
||||
private sync: boolean;
|
||||
private scrolling: Side | null = null;
|
||||
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private wheelLeader: Side | null = null;
|
||||
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private frame = -1;
|
||||
private resize: ResizeObserver | null = null;
|
||||
private readonly cleanup: (() => void)[] = [];
|
||||
@@ -326,7 +375,19 @@ export class UnalignedPanes implements DiffPanes {
|
||||
opts.initialRatio != null && Number.isFinite(opts.initialRatio)
|
||||
? Math.min(MAX_RATIO, Math.max(MIN_RATIO, opts.initialRatio))
|
||||
: loadRatio();
|
||||
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
|
||||
this.extension = [
|
||||
gapMarks,
|
||||
changedLineGutters,
|
||||
EditorView.updateListener.of((u) => {
|
||||
// When CodeMirror's measure adjusts a follower pane's scrollTop after line heights resolve,
|
||||
// update the expected echo so the layout adjustment is not mistaken for a user scroll.
|
||||
if (u.heightChanged && !u.docChanged && this.mv) {
|
||||
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
|
||||
if (side && this.moved[side].top !== null) this.moved[side].top = u.view.scrollDOM.scrollTop;
|
||||
}
|
||||
this.schedule();
|
||||
}),
|
||||
];
|
||||
this.divider.className = "cm-diffDivider";
|
||||
// A lone arrow is centred in the divider; a pair keeps to the two edges.
|
||||
this.divider.classList.toggle("cm-diffDivider-lone", !!opts.arrows && opts.arrows.toA !== opts.arrows.toB);
|
||||
@@ -349,13 +410,20 @@ export class UnalignedPanes implements DiffPanes {
|
||||
for (const side of ["a", "b"] as const) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const onScroll = () => this.scrolled(side);
|
||||
const onPointer = () => this.interruptScroll();
|
||||
const onWheel = () => {
|
||||
this.interruptScroll();
|
||||
this.leadWheel(side);
|
||||
};
|
||||
const onPointer = () => {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
};
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
el.addEventListener("wheel", onPointer, { passive: true });
|
||||
el.addEventListener("wheel", onWheel, { passive: true });
|
||||
el.addEventListener("pointerdown", onPointer);
|
||||
this.cleanup.push(() => {
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
el.removeEventListener("wheel", onPointer);
|
||||
el.removeEventListener("wheel", onWheel);
|
||||
el.removeEventListener("pointerdown", onPointer);
|
||||
});
|
||||
}
|
||||
@@ -428,6 +496,7 @@ export class UnalignedPanes implements DiffPanes {
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
e.preventDefault();
|
||||
this.interruptScroll();
|
||||
this.leadWheel("b");
|
||||
mv.b.scrollDOM.scrollBy(e.deltaX, e.deltaY);
|
||||
};
|
||||
this.divider.addEventListener("wheel", onWheel, { passive: false });
|
||||
@@ -459,17 +528,30 @@ export class UnalignedPanes implements DiffPanes {
|
||||
setSync(on: boolean) {
|
||||
if (on === this.sync) return;
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.sync = on;
|
||||
this.resync();
|
||||
}
|
||||
|
||||
scrollTo(side: Side, options: ScrollToOptions) {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
this.view(side).scrollDOM.scrollTo(options);
|
||||
}
|
||||
|
||||
private leadWheel(side: Side) {
|
||||
this.wheelLeader = this.sync ? side : null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
|
||||
}
|
||||
|
||||
private clearWheel() {
|
||||
this.wheelLeader = null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
}
|
||||
|
||||
private releaseScroll() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
if (this.scrolling) this.scrollTimer = setTimeout(() => (this.scrolling = null), 150);
|
||||
@@ -487,6 +569,7 @@ export class UnalignedPanes implements DiffPanes {
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.frame >= 0) cancelAnimationFrame(this.frame);
|
||||
this.resize?.disconnect();
|
||||
for (const f of this.cleanup) f();
|
||||
@@ -518,6 +601,19 @@ export class UnalignedPanes implements DiffPanes {
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
if (this.wheelLeader) {
|
||||
// Keep the actively wheel-scrolled pane in charge so follower measure adjustments never pull it back.
|
||||
const moved = this.moved[side];
|
||||
moved.top = moved.left = null;
|
||||
if (side === this.wheelLeader) {
|
||||
this.leadWheel(side);
|
||||
if (this.sync) this.follow(side);
|
||||
} else if (this.sync) {
|
||||
this.follow(this.wheelLeader);
|
||||
}
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
const el = this.view(side).scrollDOM;
|
||||
const moved = this.moved[side];
|
||||
const echo =
|
||||
|
||||
@@ -105,8 +105,24 @@ function CommitRowView({
|
||||
left={opts.refsOnLeft}
|
||||
/>
|
||||
);
|
||||
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
|
||||
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
|
||||
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
|
||||
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
|
||||
);
|
||||
const subjectCell = (
|
||||
<span key={SUBJECT_COLUMN.id} className={styles.colSubject}>
|
||||
{/* A leading Commit cell's left edge is the only row divider for the Repository column. */}
|
||||
{repository && visibleIds[0] === SUBJECT_COLUMN.id && (
|
||||
<RowResizeHandle
|
||||
target={{
|
||||
id: SUBJECT_COLUMN.id,
|
||||
width: 0,
|
||||
...columnPrev(visibleIds, SUBJECT_COLUMN.id, opts, columns, repository),
|
||||
leftOnly: true,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{graph && (
|
||||
<GraphCell
|
||||
row={graph}
|
||||
@@ -161,11 +177,6 @@ function CommitRowView({
|
||||
</Popup>
|
||||
</span>
|
||||
);
|
||||
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
|
||||
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
|
||||
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
|
||||
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
|
||||
);
|
||||
return (
|
||||
<div
|
||||
id={id}
|
||||
|
||||
@@ -712,3 +712,36 @@ describe(".icls schemes", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("annotation colour (#6108)", () => {
|
||||
const opt = (name: string, value: string) =>
|
||||
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
|
||||
const scheme = (parent: string | null, ...options: string[]) =>
|
||||
parseIcls(
|
||||
`<scheme name="A"${parent ? ` parent_scheme="${parent}"` : ""}><attributes>${options.join("")}</attributes></scheme>`,
|
||||
).scheme;
|
||||
|
||||
it.each([
|
||||
["Default", "#808000"],
|
||||
["Darcula", "#bbb529"],
|
||||
])("keeps %s's own annotation colour when the file only changes DEFAULT_METADATA", (parent, colour) => {
|
||||
// IntelliJ shows Java annotations with the parent's ANNOTATION_NAME_ATTRIBUTES, not the file's default.
|
||||
expect(scheme(parent, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe(colour);
|
||||
});
|
||||
|
||||
it("takes the file's annotation key over its DEFAULT_METADATA", () => {
|
||||
const s = scheme("Default", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
|
||||
expect(s.attributes.metadata?.foreground).toBe("#9e880d");
|
||||
});
|
||||
|
||||
it("uses DEFAULT_METADATA without a bundled parent", () => {
|
||||
expect(scheme(null, opt("DEFAULT_METADATA", "1d8711")).attributes.metadata?.foreground).toBe("#1d8711");
|
||||
});
|
||||
|
||||
it("exports the annotation colour under the annotation key, so it survives a re-import", () => {
|
||||
const imported = scheme("Default", opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d"));
|
||||
const xml = exportIcls("custom-a", { "custom-a": imported });
|
||||
expect(xml).toContain('<option name="ANNOTATION_NAME_ATTRIBUTES">');
|
||||
expect(parseIcls(xml).scheme.attributes.metadata?.foreground).toBe("#9e880d");
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,8 @@ const ATTRIBUTE_NAMES: Record<string, string> = {
|
||||
DEFAULT_DOC_COMMENT_TAG: "docCommentTag",
|
||||
DEFAULT_DOC_COMMENT_TAG_VALUE: "docCommentTagValue",
|
||||
DEFAULT_DOC_MARKUP: "docCommentMarkup",
|
||||
// Java's annotation key outranks the default it falls back to.
|
||||
ANNOTATION_NAME_ATTRIBUTES: "metadata",
|
||||
DEFAULT_METADATA: "metadata",
|
||||
DEFAULT_OPERATION_SIGN: "operator",
|
||||
DEFAULT_PARENTHS: "operator",
|
||||
@@ -297,6 +299,8 @@ for (const id of [
|
||||
// its fallback's. TypeScript keys win over JavaScript (TS.* falls back to JS.*), then Python, then the
|
||||
// shared defaults; within a language, the key listed first above. DEFAULT_DOT, _COMMA and _SEMICOLON are
|
||||
// not mapped: the one punctuation colour here would spread them to every brace and operator.
|
||||
/** ANNOTATION_NAME_ATTRIBUTES as IntelliJ's bundled Default and Darcula schemes set it. */
|
||||
const PARENT_ANNOTATIONS: Record<string, string> = { Default: "#808000", Darcula: "#bbb529" };
|
||||
const KEY_ORDER = new Map(Object.keys(ATTRIBUTE_NAMES).map((name, i) => [name, i]));
|
||||
const LANGUAGE_PRECEDENCE = ["TS.", "JS.", "PY."];
|
||||
const precedence = (name: string) => {
|
||||
@@ -488,6 +492,10 @@ export function parseIcls(
|
||||
const own = new Set([...entries.keys()].flatMap((name) => (name ? targets(name) : [])));
|
||||
for (const [id, value] of Object.entries(DARCULA_ATTRIBUTES)) if (!own.has(id)) attributes[id] ??= { ...value };
|
||||
}
|
||||
// Both bundled parents set Java's annotation key itself, so a file that leaves it out shows the parent's
|
||||
// colour there, not its own DEFAULT_METADATA.
|
||||
if (Object.hasOwn(PARENT_ANNOTATIONS, parentName) && !entries.has("ANNOTATION_NAME_ATTRIBUTES"))
|
||||
attributes.metadata = { bold: false, italic: false, foreground: PARENT_ANNOTATIONS[parentName]! };
|
||||
const bg = attributes.text?.background;
|
||||
const rgb = bg ? [1, 3, 5].map((i) => parseInt(bg.slice(i, i + 2), 16)) : [255, 255, 255];
|
||||
const dark = rgb[0]! * 0.299 + rgb[1]! * 0.587 + rgb[2]! * 0.114 < 128;
|
||||
|
||||
@@ -4071,5 +4071,7 @@
|
||||
"Granted with grant option": "Granted with grant option",
|
||||
"No privileges are granted on this table.": "No privileges are granted on this table.",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* With grant option: the grantee may grant the privilege to others.",
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source."
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source.",
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
|
||||
"Stop Backend and Open": "Stop Backend and Open"
|
||||
}
|
||||
@@ -1700,6 +1700,9 @@
|
||||
"Reload All Gradle Projects": "Recargar todos los proyectos de Gradle",
|
||||
"Reload All Maven Projects": "Recargar todos los proyectos de Maven",
|
||||
"Reload Changed Classes": "Recargar clases modificadas",
|
||||
"Enhanced class redefinition": "Redefinición de clases mejorada",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Al depurar en JetBrains Runtime, Recargar clases modificadas también puede añadir o eliminar métodos y campos",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para añadir o eliminar métodos y campos, activa Redefinición de clases mejorada en la configuración de ejecución y depura en JetBrains Runtime.",
|
||||
"Reload Environments": "Recargar entornos",
|
||||
"Reload History": "Recargar historial",
|
||||
"Reload List of Packages": "Recargar lista de paquetes",
|
||||
|
||||
@@ -1619,6 +1619,9 @@
|
||||
"Reload All Gradle Projects": "Recharger tous les projets Gradle",
|
||||
"Reload All Maven Projects": "Recharger tous les projets Maven",
|
||||
"Reload Changed Classes": "Recharger les classes modifiées",
|
||||
"Enhanced class redefinition": "Redéfinition de classes étendue",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Lors du débogage sur JetBrains Runtime, Recharger les classes modifiées peut aussi ajouter ou supprimer des méthodes et des champs",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Pour ajouter ou supprimer des méthodes et des champs, activez Redéfinition de classes étendue dans la configuration d'exécution et déboguez sur JetBrains Runtime.",
|
||||
"Reload Environments": "Recharger les environnements",
|
||||
"Reload History": "Recharger l'historique",
|
||||
"Reload List of Packages": "Recharger la liste des paquets",
|
||||
|
||||
@@ -1750,6 +1750,9 @@
|
||||
"Reload All Gradle Projects": "모든 Gradle 프로젝트 다시 로드",
|
||||
"Reload All Maven Projects": "모든 Maven 프로젝트 다시 로드",
|
||||
"Reload Changed Classes": "변경된 클래스 다시 로드",
|
||||
"Enhanced class redefinition": "향상된 클래스 재정의",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime에서 디버그할 때 변경된 클래스 다시 로드로 메서드와 필드도 추가하거나 제거할 수 있습니다",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "메서드와 필드를 추가하거나 제거하려면 실행 구성에서 향상된 클래스 재정의를 켜고 JetBrains Runtime에서 디버그하세요.",
|
||||
"Reload Environments": "환경 다시 로드",
|
||||
"Reload History": "기록 다시 로드",
|
||||
"Reload List of Packages": "패키지 목록 다시 로드",
|
||||
|
||||
@@ -1690,6 +1690,9 @@
|
||||
"Reload All Gradle Projects": "Przeładuj wszystkie projekty Gradle",
|
||||
"Reload All Maven Projects": "Przeładuj wszystkie projekty Maven",
|
||||
"Reload Changed Classes": "Przeładuj zmienione klasy",
|
||||
"Enhanced class redefinition": "Rozszerzona redefinicja klas",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Podczas debugowania w JetBrains Runtime Przeładuj zmienione klasy może też dodawać lub usuwać metody i pola",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Aby dodawać lub usuwać metody i pola, włącz Rozszerzoną redefinicję klas w konfiguracji uruchomieniowej i debuguj w JetBrains Runtime.",
|
||||
"Reload Environments": "Przeładuj środowiska",
|
||||
"Reload History": "Przeładuj historię",
|
||||
"Reload List of Packages": "Przeładuj listę pakietów",
|
||||
|
||||
@@ -1690,6 +1690,9 @@
|
||||
"Reload All Gradle Projects": "Recarregar todos os projetos Gradle",
|
||||
"Reload All Maven Projects": "Recarregar todos os projetos Maven",
|
||||
"Reload Changed Classes": "Recarregar classes alteradas",
|
||||
"Enhanced class redefinition": "Redefinição de classes aprimorada",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Ao depurar no JetBrains Runtime, Recarregar classes alteradas também pode adicionar ou remover métodos e campos",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para adicionar ou remover métodos e campos, ative Redefinição de classes aprimorada na configuração de execução e depure no JetBrains Runtime.",
|
||||
"Reload Environments": "Recarregar ambientes",
|
||||
"Reload History": "Recarregar histórico",
|
||||
"Reload List of Packages": "Recarregar lista de pacotes",
|
||||
|
||||
@@ -2947,6 +2947,9 @@
|
||||
"Generate Sources and Update Folders": "Сгенерировать исходный код и обновить каталоги",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "Запускает generate-sources, затем перезагружает проекты Maven, чтобы сгенерированные каталоги стали каталогами исходного кода",
|
||||
"Reload Changed Classes": "Перезагрузить изменённые классы",
|
||||
"Enhanced class redefinition": "Расширенное переопределение классов",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "При отладке на JetBrains Runtime команда «Перезагрузить изменённые классы» также может добавлять и удалять методы и поля",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Чтобы добавлять или удалять методы и поля, включите «Расширенное переопределение классов» в конфигурации запуска и отлаживайте на JetBrains Runtime.",
|
||||
"Reload Environments": "Перезагрузить окружения",
|
||||
"Reload History": "Перезагрузить историю",
|
||||
"Reload List of Packages": "Перезагрузить список пакетов",
|
||||
|
||||
@@ -4449,6 +4449,9 @@
|
||||
"Reload All Gradle Projects": "Tüm Gradle Projelerini Yeniden Yükle",
|
||||
"Reload All Maven Projects": "Tüm Maven Projelerini Yeniden Yükle",
|
||||
"Reload Changed Classes": "Değiştirilen Sınıfları Yeniden Yükle",
|
||||
"Enhanced class redefinition": "Gelişmiş sınıf yeniden tanımlama",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime üzerinde hata ayıklarken Değiştirilen Sınıfları Yeniden Yükle, yöntem ve alan da ekleyip kaldırabilir",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Yöntem ve alan eklemek veya kaldırmak için çalıştırma yapılandırmasında Gelişmiş sınıf yeniden tanımlamayı açın ve JetBrains Runtime üzerinde hata ayıklayın.",
|
||||
"Reload Environments": "Ortamları Yeniden Yükle",
|
||||
"Reload History": "Geçmişi Yeniden Yükle",
|
||||
"Reload List of Packages": "Paket Listesini Yeniden Yükle",
|
||||
|
||||
@@ -2523,6 +2523,9 @@
|
||||
"Generate Sources and Update Folders": "產生原始碼並更新資料夾",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "執行 generate-sources,然後重新載入 Maven 專案,使產生的資料夾成為原始碼資料夾",
|
||||
"Reload Changed Classes": "重新載入已更改的類別",
|
||||
"Enhanced class redefinition": "增強類別重新定義",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上偵錯時,「重新載入已更改的類別」也可以新增或刪除方法和欄位",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需新增或刪除方法和欄位,請在執行組態中開啟「增強類別重新定義」,並使用 JetBrains Runtime 偵錯。",
|
||||
"Reload Environments": "重新載入環境",
|
||||
"Reload History": "重新載入歷史記錄",
|
||||
"Reload List of Packages": "重新載入軟體包清單",
|
||||
|
||||
@@ -3016,6 +3016,9 @@
|
||||
"Generate Sources and Update Folders": "生成源代码并更新文件夹",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "执行 generate-sources,然后重新加载 Maven 项目,使生成的文件夹成为源代码文件夹",
|
||||
"Reload Changed Classes": "重新加载已更改的类",
|
||||
"Enhanced class redefinition": "增强类重定义",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上调试时,“重新加载已更改的类”还可以添加或删除方法和字段",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需添加或删除方法和字段,请在运行配置中开启“增强类重定义”,并使用 JetBrains Runtime 调试。",
|
||||
"Reload Environments": "重新加载环境",
|
||||
"Reload History": "重新加载历史记录",
|
||||
"Reload List of Packages": "重新加载软件包列表",
|
||||
@@ -10402,5 +10405,7 @@
|
||||
"No privileges are granted on this table.": "此表未授予任何权限。",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。",
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。",
|
||||
"Recent Find Usages": "最近的查找用法"
|
||||
"Recent Find Usages": "最近的查找用法",
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "另一个 OpenIDEA 版本(例如升级前的版本)的后端仍打开着这个项目,当前版本无法打开它。要停止那个后端并打开项目吗?它的终端、运行和智能体会话会结束,未保存的修改会丢失。",
|
||||
"Stop Backend and Open": "停止后端并打开"
|
||||
}
|
||||
@@ -237,6 +237,27 @@ async function attachRemote(r: RemoteProject, path: string): Promise<void> {
|
||||
|
||||
let connectAttempt = 0;
|
||||
|
||||
let backendBusyPrompt: ((target: RemoteTarget) => Promise<boolean>) | null = null;
|
||||
|
||||
/** Asks whether to stop another build's backend that still holds the project (#6119). */
|
||||
export function provideBackendBusyPrompt(value: (target: RemoteTarget) => Promise<boolean>): () => void {
|
||||
backendBusyPrompt = value;
|
||||
return () => {
|
||||
if (backendBusyPrompt === value) backendBusyPrompt = null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Connects; when another build's backend still holds the project, stops it once the user agrees. */
|
||||
async function connectOrReplace(target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) {
|
||||
try {
|
||||
return await call(commands.remoteConnect(target, path, false, onProgress));
|
||||
} catch (e) {
|
||||
const busy = e instanceof IpcError && e.data?.type === "remoteBackendBusy";
|
||||
if (!busy || !backendBusyPrompt || !(await backendBusyPrompt(target))) throw e;
|
||||
return await call(commands.remoteConnect(target, path, true, onProgress));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `path` of `target` (an SSH host or a WSL distribution) in this window. A dev container's
|
||||
* project folder is the one in the container: `path` is then only a label.
|
||||
@@ -256,7 +277,7 @@ export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
location,
|
||||
});
|
||||
try {
|
||||
const r = await call(commands.remoteConnect(target, path, onProgress));
|
||||
const r = await connectOrReplace(target, path, onProgress);
|
||||
// Another connect replaced this one, or the user cancelled. Disconnecting here
|
||||
// would drop the connection that replacement published. Cancel already disconnects.
|
||||
if (!current()) {
|
||||
@@ -280,7 +301,7 @@ export async function reconnectRemote(): Promise<void> {
|
||||
if (!session) return;
|
||||
useRemote.setState({ reconnecting: true });
|
||||
try {
|
||||
const r = await call(commands.remoteConnect(session.target, session.root, new Channel<RemoteProgress>()));
|
||||
const r = await connectOrReplace(session.target, session.root, new Channel<RemoteProgress>());
|
||||
useProject.setState({ project: null });
|
||||
await attachRemote(r, session.root);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { commands, type RemoteTarget } from "./ipc";
|
||||
import { connectRemote, provideBackendBusyPrompt } from "./remote";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: unknown = null;
|
||||
},
|
||||
}));
|
||||
vi.mock("./ipc", async (original) => ({
|
||||
...(await original<typeof import("./ipc")>()),
|
||||
isTauri: () => true,
|
||||
}));
|
||||
|
||||
const target: RemoteTarget = { kind: "ssh", config: "box" };
|
||||
const busy = {
|
||||
status: "error" as const,
|
||||
error: { kind: "unavailable" as const, message: "busy", data: { type: "remoteBackendBusy" as const } },
|
||||
};
|
||||
const stop = { status: "error" as const, error: { kind: "unavailable" as const, message: "second attempt" } };
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("stops another build's backend once the user agrees, then connects again (#6119)", async () => {
|
||||
const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValueOnce(busy).mockResolvedValueOnce(stop);
|
||||
const prompt = vi.fn(async () => true);
|
||||
const dispose = provideBackendBusyPrompt(prompt);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt");
|
||||
dispose();
|
||||
expect(prompt).toHaveBeenCalledOnce();
|
||||
expect(connect.mock.calls.map((c) => c[2])).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it("keeps the error when the user declines", async () => {
|
||||
const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValue(busy);
|
||||
const dispose = provideBackendBusyPrompt(async () => false);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("busy");
|
||||
dispose();
|
||||
expect(connect).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("doesn't ask about other connection errors", async () => {
|
||||
vi.spyOn(commands, "remoteConnect").mockResolvedValue(stop);
|
||||
const prompt = vi.fn(async () => true);
|
||||
const dispose = provideBackendBusyPrompt(prompt);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt");
|
||||
dispose();
|
||||
expect(prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
Reference in new issue
Заблокувати користувача