дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 01:31:41 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
32671b605a | ||
|
|
c73d858895 | ||
|
|
6e5486586c | ||
|
|
93642b3741 |
No files matched your search
@@ -275,6 +275,11 @@ pub enum DebugEvent {
|
||||
},
|
||||
/// The session's capabilities changed after it started: fetch them again.
|
||||
Capabilities,
|
||||
/// The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`,
|
||||
/// `variables`; empty means all) is stale and has to be fetched again.
|
||||
Invalidated {
|
||||
areas: Vec<String>,
|
||||
},
|
||||
JvmBackend {
|
||||
state: JvmBackendState,
|
||||
},
|
||||
@@ -330,4 +335,12 @@ mod tests {
|
||||
);
|
||||
assert_eq!(serde_json::to_value(DebugEvent::Capabilities).unwrap(), json!({"kind": "capabilities"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidated_event_json_shape() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(DebugEvent::Invalidated { areas: vec!["variables".into()] }).unwrap(),
|
||||
json!({"kind": "invalidated", "areas": ["variables"]})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,13 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
|
||||
"stdio",
|
||||
"Install Kotlin Debug Adapter in Settings › Languages & Frameworks › Language Servers",
|
||||
),
|
||||
// Inside the language server: reached through `debugServer`, never started.
|
||||
"kotlin-lsp" => cfg(
|
||||
"kotlin-lsp",
|
||||
&[],
|
||||
"tcp",
|
||||
"Install JetBrains Kotlin LSP in Settings › Languages & Frameworks › Language Servers",
|
||||
),
|
||||
// Windows installs `python.exe`; `python3.exe` there is at most a Store alias.
|
||||
"debugpy" => cfg(
|
||||
if cfg!(windows) { "python" } else { "python3" },
|
||||
|
||||
@@ -29,7 +29,7 @@ pub(crate) use scan::watch_for_attached_jvm;
|
||||
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
|
||||
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
|
||||
|
||||
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER];
|
||||
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
|
||||
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -9,11 +9,15 @@ use std::{
|
||||
|
||||
pub const ADAPTER: &str = "kotlin-debug-adapter";
|
||||
|
||||
/// The adapter attaches to a JVM the IDE starts, through the JDWP link. It resumes the VM while
|
||||
/// constructing its debuggee, before its breakpoint hooks exist, so the link holds resumes back
|
||||
/// until the attach is done.
|
||||
pub(crate) fn link_options() -> ide_jdwp::LinkOptions {
|
||||
ide_jdwp::LinkOptions { hold_resumes: true }
|
||||
/// fwcd's adapter or kotlin-lsp's: both debug a JVM the IDE starts, through the JDWP link.
|
||||
pub fn is_kotlin(adapter: &str) -> bool {
|
||||
adapter == ADAPTER || adapter == crate::kotlin_lsp::ADAPTER
|
||||
}
|
||||
|
||||
/// fwcd's adapter resumes the VM while constructing its debuggee, before its breakpoint hooks
|
||||
/// exist, so only its link holds resumes back until the attach is done.
|
||||
pub(crate) fn link_options(adapter: &str) -> ide_jdwp::LinkOptions {
|
||||
ide_jdwp::LinkOptions { hold_resumes: adapter == ADAPTER }
|
||||
}
|
||||
|
||||
pub struct SourceMirror {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! JetBrains kotlin-lsp's debugger: a DAP server inside the language server, reached through
|
||||
//! the `debugServer` port it opens once the project is imported.
|
||||
//!
|
||||
//! Known limits, with no guard here: an evaluate that calls a function with a breakpoint, right
|
||||
//! after a step over a suspension point, loses every later stop at that breakpoint; while
|
||||
//! stepping, breakpoints hit by other coroutines are skipped.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
pub const ADAPTER: &str = "kotlin-lsp";
|
||||
/// The `adapterID` its debug server expects in `initialize`.
|
||||
pub const DAP_ADAPTER_ID: &str = "intellij_jvm";
|
||||
|
||||
/// The path of a `file:` URI, as kotlin-lsp reports some sources (percent-encoded); `None` for
|
||||
/// anything else, including a URI naming another host.
|
||||
pub(crate) fn source_path(path: &str) -> Option<PathBuf> {
|
||||
let rest = path.strip_prefix("file:")?;
|
||||
let path = match rest.strip_prefix("//") {
|
||||
Some(authority) => {
|
||||
let slash = authority.find('/')?;
|
||||
if !matches!(&authority[..slash], "" | "localhost") {
|
||||
return None;
|
||||
}
|
||||
&authority[slash..]
|
||||
}
|
||||
None => rest,
|
||||
};
|
||||
let decoded = percent_encoding::percent_decode_str(path).decode_utf8().ok()?;
|
||||
// `/C:/p/App.kt` on Windows.
|
||||
let decoded = match decoded.strip_prefix('/') {
|
||||
Some(drive) if cfg!(windows) && drive.as_bytes().get(1) == Some(&b':') => drive,
|
||||
_ => &decoded,
|
||||
};
|
||||
Some(PathBuf::from(decoded))
|
||||
}
|
||||
|
||||
pub(crate) fn frame_name(name: &str) -> &str {
|
||||
name.strip_prefix("at ").unwrap_or(name)
|
||||
}
|
||||
|
||||
/// What kotlin-lsp's DAP server does unlike other adapters.
|
||||
///
|
||||
/// It never answers a request that carries a thread id from an earlier stop (K1 G4), so such a
|
||||
/// request would wait out `REQUEST_TIMEOUT`: [`Self::check_thread`] refuses it first. Only thread
|
||||
/// ids were measured; a stale `frameId` or `variablesReference` may wait the same way. A step
|
||||
/// ends with `reason: "breakpoint"`; a real breakpoint hit during a step is then reported as a
|
||||
/// step too, since the stop carries neither `hitBreakpointIds` nor a description.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Quirks {
|
||||
step_pending: AtomicBool,
|
||||
/// The stop (a `Suspension` ticket) and the thread ids seen in it.
|
||||
threads: Mutex<(u64, HashSet<i64>)>,
|
||||
}
|
||||
|
||||
impl Quirks {
|
||||
/// Before `next`, `stepIn`, `stepOut` or a forced step.
|
||||
pub fn step_sent(&self) {
|
||||
self.step_pending.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Before `continue` or run to cursor, or after a step request failed.
|
||||
pub fn resume_sent(&self) {
|
||||
self.step_pending.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
/// The reason to report for a `stopped` event.
|
||||
pub fn stop_reason(&self, reason: String) -> String {
|
||||
let stepped = self.step_pending.swap(false, Ordering::AcqRel);
|
||||
if stepped && reason == "breakpoint" { "step".into() } else { reason }
|
||||
}
|
||||
|
||||
/// Thread ids seen in stop `stop`: a `stopped` event's, or a `threads` reply to a request sent
|
||||
/// during that stop. A reply from an older stop changes nothing.
|
||||
pub fn saw_threads(&self, stop: u64, ids: impl IntoIterator<Item = i64>) {
|
||||
let mut threads = self.threads.lock();
|
||||
if stop > threads.0 {
|
||||
*threads = (stop, ids.into_iter().collect());
|
||||
} else if stop == threads.0 {
|
||||
threads.1.extend(ids);
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuses a thread id that is not one of current stop `stop`'s, once some are known.
|
||||
pub fn check_thread(&self, stop: u64, suspended: bool, id: i64) -> IdeResult<()> {
|
||||
let threads = self.threads.lock();
|
||||
if suspended && threads.0 == stop && !threads.1.is_empty() && !threads.1.contains(&id) {
|
||||
return Err(IdeError::invalid(format!("thread {id} belongs to an earlier stop")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn file_uris_become_paths() {
|
||||
assert_eq!(source_path("file:///p/a%20b/App.kt").as_deref(), Some(Path::new("/p/a b/App.kt")));
|
||||
assert_eq!(source_path("file://localhost/p/x.kt").as_deref(), Some(Path::new("/p/x.kt")));
|
||||
assert_eq!(source_path("/p/x.kt"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_names_lose_the_at_prefix() {
|
||||
assert_eq!(frame_name("at com.x.AppKt.main(App.kt:13)"), "com.x.AppKt.main(App.kt:13)");
|
||||
assert_eq!(frame_name("main"), "main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_pending_step_turns_a_breakpoint_into_a_step() {
|
||||
let quirks = Quirks::default();
|
||||
quirks.step_sent();
|
||||
assert_eq!(quirks.stop_reason("breakpoint".into()), "step");
|
||||
assert_eq!(quirks.stop_reason("breakpoint".into()), "breakpoint");
|
||||
quirks.step_sent();
|
||||
quirks.resume_sent();
|
||||
assert_eq!(quirks.stop_reason("breakpoint".into()), "breakpoint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_are_checked_against_the_current_stop() {
|
||||
let quirks = Quirks::default();
|
||||
quirks.saw_threads(3, [18]);
|
||||
assert!(quirks.check_thread(3, true, 18).is_ok());
|
||||
assert!(quirks.check_thread(3, true, 6).is_err());
|
||||
assert!(quirks.check_thread(4, true, 6).is_ok(), "nothing known about stop 4 yet");
|
||||
assert!(quirks.check_thread(3, false, 6).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_threads_reply_does_not_change_a_newer_stop() {
|
||||
let quirks = Quirks::default();
|
||||
quirks.saw_threads(4, [2]);
|
||||
quirks.saw_threads(3, [1]);
|
||||
assert!(quirks.check_thread(4, true, 1).is_err());
|
||||
quirks.saw_threads(4, [7]);
|
||||
assert!(quirks.check_thread(4, true, 2).is_ok() && quirks.check_thread(4, true, 7).is_ok());
|
||||
quirks.saw_threads(5, [9]);
|
||||
assert!(quirks.check_thread(5, true, 2).is_err());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ pub mod connection;
|
||||
pub mod jdwp;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod session;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -610,6 +611,16 @@ fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A step request's outcome; a failed one leaves no step pending, so the next stop keeps its reason.
|
||||
fn step_settled(session: &Session, sent: Result<Value, DapError>) -> Result<Value, DapError> {
|
||||
if sent.is_err()
|
||||
&& let Some(quirks) = session.kotlin_lsp_quirks()
|
||||
{
|
||||
quirks.resume_sent();
|
||||
}
|
||||
sent
|
||||
}
|
||||
|
||||
/// Delve compiles the debuggee to `__debug_bin` in the session's cwd (on Windows
|
||||
/// `__debug_bin.exe` plus `__debug_bin.exe<digits>` in DAP mode) and removes it on a
|
||||
/// graceful exit — a shutdown it doesn't always reach, so the files pile up. Sweep
|
||||
@@ -981,6 +992,7 @@ impl DebugManager {
|
||||
arguments["projectRoot"] = json!(mirror.root());
|
||||
*s.kotlin_mirror.lock() = Some(mirror);
|
||||
}
|
||||
let is_kotlin_lsp = s.adapter == kotlin_lsp::ADAPTER;
|
||||
let caps = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
@@ -988,7 +1000,7 @@ impl DebugManager {
|
||||
json!({
|
||||
"clientID": "openidea",
|
||||
"clientName": "OpenIDEA",
|
||||
"adapterID": s.adapter,
|
||||
"adapterID": if is_kotlin_lsp { kotlin_lsp::DAP_ADAPTER_ID } else { s.adapter.as_str() },
|
||||
"locale": "en",
|
||||
"linesStartAt1": true,
|
||||
"columnsStartAt1": true,
|
||||
@@ -998,7 +1010,8 @@ impl DebugManager {
|
||||
"supportsRunInTerminalRequest": true,
|
||||
"supportsStartDebuggingRequest": true,
|
||||
"supportsProgressReporting": true,
|
||||
"supportsInvalidatedEvent": false,
|
||||
// kotlin-lsp sends `invalidated` either way.
|
||||
"supportsInvalidatedEvent": is_kotlin_lsp,
|
||||
"supportsMemoryReferences": false,
|
||||
"supportsArgsCanBeInterpretedByShell": false,
|
||||
}),
|
||||
@@ -1008,7 +1021,7 @@ impl DebugManager {
|
||||
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
|
||||
|
||||
// The Kotlin adapters ignore the resolved classpath and project runtime on launch.
|
||||
let request = if s.adapter == kotlin::ADAPTER && s.request == "launch" {
|
||||
let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" {
|
||||
session::start_kotlin_debuggee(s, &mut arguments).await?;
|
||||
"attach"
|
||||
} else {
|
||||
@@ -1032,7 +1045,7 @@ impl DebugManager {
|
||||
jvm_memory::find_attached_jvm(s, port, finder).await;
|
||||
}
|
||||
}
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
if kotlin::is_kotlin(&s.adapter) {
|
||||
let host = arguments
|
||||
.get("hostName")
|
||||
.and_then(Value::as_str)
|
||||
@@ -1044,7 +1057,7 @@ impl DebugManager {
|
||||
.and_then(|p| u16::try_from(p).ok())
|
||||
.filter(|p| *p != 0)
|
||||
.ok_or_else(|| IdeError::invalid("Invalid Kotlin JDWP port"))?;
|
||||
let (link, port) = ide_jdwp::JdwpLink::start(host, port, kotlin::link_options()).await?;
|
||||
let (link, port) = ide_jdwp::JdwpLink::start(host, port, kotlin::link_options(&s.adapter)).await?;
|
||||
*s.jvm_inspector.lock() = Some(Arc::new(ide_jdwp::LinkInspector::new(link.clone())));
|
||||
jvm_memory::watch_link(s, &link);
|
||||
*s.jdwp_link.lock() = Some(link);
|
||||
@@ -1381,6 +1394,8 @@ impl DebugManager {
|
||||
|
||||
pub async fn threads(&self, s: DebugSessionId) -> IdeResult<Vec<ThreadInfo>> {
|
||||
let session = self.session(s)?;
|
||||
// Before sending: a stop that overtakes the reply must not take the reply's ids as its own.
|
||||
let stop = session.suspended.ticket();
|
||||
let body = session.conn.request_timeout("threads", Value::Null, REQUEST_TIMEOUT).await?;
|
||||
let threads: Vec<ThreadInfo> = body
|
||||
.get("threads")
|
||||
@@ -1394,11 +1409,15 @@ impl DebugManager {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(quirks) = session.kotlin_lsp_quirks() {
|
||||
quirks.saw_threads(stop, threads.iter().map(|t| t.id));
|
||||
}
|
||||
Ok(threads)
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
@@ -1407,11 +1426,15 @@ impl DebugManager {
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
if let Some(client) = frame.path.as_deref().and_then(|p| session.client_path(&p.to_string_lossy())) {
|
||||
frame.path = Some(client.into());
|
||||
}
|
||||
if kotlin_lsp {
|
||||
frame.name = kotlin_lsp::frame_name(&frame.name).to_owned();
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
@@ -1523,6 +1546,10 @@ impl DebugManager {
|
||||
|
||||
pub async fn resume(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
if let Some(quirks) = session.kotlin_lsp_quirks() {
|
||||
quirks.resume_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
|
||||
// DAP: a response without the flag continued every thread.
|
||||
@@ -1567,8 +1594,13 @@ impl DebugManager {
|
||||
StepKind::Out => "stepOut",
|
||||
};
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
if let Some(quirks) = session.kotlin_lsp_quirks() {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
|
||||
@@ -1587,6 +1619,8 @@ impl DebugManager {
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
// Before touching breakpoints: a refused `continue` would leave them replaced.
|
||||
session.check_thread(thread_id)?;
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
@@ -1661,6 +1695,7 @@ impl DebugManager {
|
||||
/// Force Step Over: `next` with every breakpoint suspended until the step ends.
|
||||
pub async fn force_step_over(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
self.suspend_breakpoints(&session, None).await?;
|
||||
self.step(s, thread_id, StepKind::Over).await
|
||||
}
|
||||
@@ -1668,11 +1703,16 @@ impl DebugManager {
|
||||
/// Step into a specific call of the current line (Smart Step Into).
|
||||
pub async fn step_in_target(&self, s: DebugSessionId, thread_id: i64, target_id: i64) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
if let Some(quirks) = session.kotlin_lsp_quirks() {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
session
|
||||
let sent = session
|
||||
.conn
|
||||
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
|
||||
.await?;
|
||||
.await;
|
||||
step_settled(&session, sent)?;
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
|
||||
Ok(())
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::adapter::AdapterSpec;
|
||||
use crate::connection::{Connection, DapError, Incoming};
|
||||
use crate::kotlin_lsp;
|
||||
use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionBreakpoint, SessionOwner};
|
||||
use ide_core::event::DebugEvent;
|
||||
#[cfg(unix)]
|
||||
@@ -103,6 +104,8 @@ pub(crate) struct Session {
|
||||
pub jvm_located: watch::Sender<bool>,
|
||||
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
|
||||
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
|
||||
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
|
||||
pub(crate) quirks: kotlin_lsp::Quirks,
|
||||
}
|
||||
|
||||
/// Which threads of the program are suspended: each from its `stopped` event until a
|
||||
@@ -252,6 +255,19 @@ impl Session {
|
||||
jvm_located: watch::channel(false).0,
|
||||
kotlin_mirror: Mutex::new(None),
|
||||
jvm_memory: tokio::sync::Mutex::default(),
|
||||
quirks: kotlin_lsp::Quirks::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kotlin_lsp_quirks(&self) -> Option<&kotlin_lsp::Quirks> {
|
||||
(self.adapter == kotlin_lsp::ADAPTER).then_some(&self.quirks)
|
||||
}
|
||||
|
||||
/// Call before sending a request for thread `id`.
|
||||
pub fn check_thread(&self, id: i64) -> ide_core::IdeResult<()> {
|
||||
match self.kotlin_lsp_quirks() {
|
||||
Some(quirks) => quirks.check_thread(self.suspended.ticket(), self.suspended.get(), id),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +299,11 @@ impl Session {
|
||||
|
||||
/// A path from the adapter as the IDE knows it (undoes [`Session::adapter_path`]).
|
||||
pub fn client_path(&self, path: &str) -> Option<PathBuf> {
|
||||
if self.adapter == kotlin_lsp::ADAPTER
|
||||
&& let Some(path) = kotlin_lsp::source_path(path)
|
||||
{
|
||||
return Some(path);
|
||||
}
|
||||
if let Some(real) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.client_path(Path::new(path))) {
|
||||
return Some(real);
|
||||
}
|
||||
@@ -697,7 +718,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
"stopped" => {
|
||||
let all = body.get("allThreadsStopped").and_then(Value::as_bool).unwrap_or(false);
|
||||
s.suspended.stopped(int("threadId"), all);
|
||||
let reason = str_("reason").unwrap_or_else(|| "pause".into());
|
||||
let mut reason = str_("reason").unwrap_or_else(|| "pause".into());
|
||||
if let Some(quirks) = s.kotlin_lsp_quirks() {
|
||||
quirks.saw_threads(s.suspended.ticket(), int("threadId"));
|
||||
reason = quirks.stop_reason(reason);
|
||||
}
|
||||
mgr.restore_breakpoints(s).await;
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
@@ -799,6 +824,14 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
change_type: crate::hot_code_replace_type(body.get("changeType")),
|
||||
message: str_("message").unwrap_or_default(),
|
||||
}),
|
||||
// Sent only by adapters told `supportsInvalidatedEvent` (kotlin-lsp).
|
||||
"invalidated" => s.emit(DebugEvent::Invalidated {
|
||||
areas: body
|
||||
.get("areas")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
|
||||
.unwrap_or_default(),
|
||||
}),
|
||||
_ => tracing::trace!("dap: ignored event {event}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,8 +126,22 @@ struct Script {
|
||||
continued_after_stop: bool,
|
||||
/// Close the connection when a `pause` request arrives (the adapter dies).
|
||||
hang_up_on_pause: bool,
|
||||
/// Close the connection at the first request after the first `stopped` event.
|
||||
hang_up_after_stop: bool,
|
||||
/// Answer `continue` with this body and keep the program running, instead of letting it exit.
|
||||
continue_reply: Option<Value>,
|
||||
/// Answer `continue` and stop at a breakpoint again, instead of letting the program exit.
|
||||
stop_after_continue: bool,
|
||||
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
|
||||
step_reason: Option<&'static str>,
|
||||
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
|
||||
refuse_next: bool,
|
||||
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
|
||||
invalidated_after_stop: bool,
|
||||
/// On `threads`: stop again on thread 2 first, then answer with thread 1 of the earlier stop.
|
||||
stop_during_threads: bool,
|
||||
/// Name of the first stack frame (`main` when unset).
|
||||
frame_name: Option<&'static str>,
|
||||
/// Answer `initialize` only after this long (a slow adapter keeps the session connecting).
|
||||
delay_initialize: Option<Duration>,
|
||||
initialized_delay: Duration,
|
||||
@@ -156,7 +170,14 @@ impl Default for Script {
|
||||
hold_set_breakpoints: 0,
|
||||
continued_after_stop: false,
|
||||
hang_up_on_pause: false,
|
||||
hang_up_after_stop: false,
|
||||
continue_reply: None,
|
||||
stop_after_continue: false,
|
||||
step_reason: None,
|
||||
refuse_next: false,
|
||||
invalidated_after_stop: false,
|
||||
stop_during_threads: false,
|
||||
frame_name: None,
|
||||
delay_initialize: None,
|
||||
initialized_delay: Duration::ZERO,
|
||||
launch_delay: Duration::ZERO,
|
||||
@@ -202,6 +223,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
let mut seq = 1000;
|
||||
let mut pending_launch: Option<i64> = None;
|
||||
let mut held: Vec<Value> = Vec::new();
|
||||
let mut stopped = false;
|
||||
let mut running = false;
|
||||
macro_rules! send {
|
||||
($v:expr) => {{
|
||||
@@ -222,6 +244,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
if msg["type"] == "response" {
|
||||
continue;
|
||||
}
|
||||
if script.hang_up_after_stop && stopped {
|
||||
break;
|
||||
}
|
||||
match msg["command"].as_str().unwrap_or_default() {
|
||||
"initialize" => {
|
||||
if let Some(delay) = script.delay_initialize {
|
||||
@@ -320,9 +345,18 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, Value::Null);
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "restart", "threadId": 1}}));
|
||||
}
|
||||
"next" if script.refuse_next => {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "next", "success": false, "message": "refused"})
|
||||
);
|
||||
// Lets the client handle the refusal before the stop.
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
|
||||
}
|
||||
"next" => {
|
||||
ok!(msg, Value::Null);
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
|
||||
}
|
||||
"setVariable" => {
|
||||
ok!(msg, json!({"value": format!("{}!", msg["arguments"]["value"].as_str().unwrap()), "type": "int"}))
|
||||
@@ -358,6 +392,12 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
stopped = true;
|
||||
if script.invalidated_after_stop {
|
||||
send!(
|
||||
json!({"type": "event", "event": "invalidated", "body": {"areas": ["variables"], "threadId": 1}})
|
||||
);
|
||||
}
|
||||
if script.continued_after_stop {
|
||||
send!(json!({"type": "event", "event": "continued", "body": {"threadId": 1}}));
|
||||
}
|
||||
@@ -365,11 +405,19 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
json!({"type": "event", "event": "breakpoint", "body": {"reason": "changed", "breakpoint": {"id": 1, "verified": false, "message": "moved", "line": 9, "source": {"path": script.source_path}}}})
|
||||
);
|
||||
}
|
||||
"threads" if script.stop_during_threads => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 2, "allThreadsStopped": true}})
|
||||
);
|
||||
// Lets the client handle the stop before it reads the reply.
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "\"main\"@1"}]}));
|
||||
}
|
||||
"threads" => ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})),
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
{"id": 10, "name": "main", "line": 5, "column": 3, "source": {"path": script.source_path.as_deref().unwrap_or("/p/a.py")}},
|
||||
{"id": 10, "name": script.frame_name.unwrap_or("main"), "line": 5, "column": 3, "source": {"path": script.source_path.as_deref().unwrap_or("/p/a.py")}},
|
||||
{"id": 11, "name": "lib", "line": 1, "column": 1, "source": {"path": "/usr/lib/x.py", "presentationHint": "deemphasize"}},
|
||||
]})
|
||||
),
|
||||
@@ -393,6 +441,12 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
]})
|
||||
),
|
||||
"continue" if script.continue_reply.is_some() => ok!(msg, script.continue_reply.clone().unwrap()),
|
||||
"continue" if script.stop_after_continue => {
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
}
|
||||
"continue" => {
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
send!(json!({"type": "event", "event": "exited", "body": {"exitCode": 3}}));
|
||||
@@ -2401,6 +2455,13 @@ fn kotlin_attach(project: &std::path::Path, host: &str, port: u16) -> LaunchConf
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_options_hold_only_for_fwcd() {
|
||||
assert!(kotlin::link_options(kotlin::ADAPTER).hold_resumes);
|
||||
assert!(!kotlin::link_options(kotlin_lsp::ADAPTER).hold_resumes);
|
||||
assert!(!kotlin::link_options("x").hold_resumes);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_session_installs_link_inspector() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2472,6 +2533,229 @@ async fn closing_the_session_drops_the_link() {
|
||||
assert!(session.jvm_inspector.lock().is_none());
|
||||
}
|
||||
|
||||
/// kotlin-lsp's debugger, reached through the language server's `debugServer` port (the fake ignores it).
|
||||
fn kotlin_lsp_attach(project: &std::path::Path) -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
adapter: kotlin_lsp::ADAPTER.into(),
|
||||
request: "attach".into(),
|
||||
cwd: Some(project.to_owned().into()),
|
||||
extra_json: Some(
|
||||
json!({"debugServer": 4711, "hostName": "127.0.0.1", "port": 5005, "projectRoot": project}).to_string(),
|
||||
),
|
||||
..config()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_lsp_initializes_as_intellij_jvm() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
for (config, adapter_id, invalidated) in [
|
||||
(kotlin_lsp_attach(project.path()), "intellij_jvm", true),
|
||||
(kotlin_attach(project.path(), "127.0.0.1", 5005), "kotlin-debug-adapter", false),
|
||||
] {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config).await.unwrap();
|
||||
let init = &h.request("initialize")["arguments"];
|
||||
assert_eq!(init["adapterID"], adapter_id);
|
||||
assert_eq!(init["supportsInvalidatedEvent"], invalidated, "{adapter_id}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let h = harness(Script::default());
|
||||
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();
|
||||
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"];
|
||||
assert_eq!(sent["projectRoot"], json!(project.path()));
|
||||
assert!(sent.get("debugServer").is_none());
|
||||
assert_eq!(sent["hostName"], "127.0.0.1");
|
||||
let link_port = sent["port"].as_u64().unwrap();
|
||||
assert!(link_port != 0 && link_port != 5005);
|
||||
let session = h.manager.session(id).unwrap();
|
||||
assert!(session.kotlin_mirror.lock().is_none());
|
||||
assert!(session.jdwp_link.lock().is_some() && session.jvm_inspector.lock().is_some());
|
||||
assert_eq!(session.attach_target.get(), Some(&("127.0.0.1".to_owned(), 5005)));
|
||||
assert!(!kotlin::link_options(&session.adapter).hold_resumes);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_lsp_waits_for_the_configuration_done_reply() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
// fwcd never answers it (`kotlin_configures_without_configuration_done_response`).
|
||||
let h = harness(Script { ignore_configuration_done: true, ..Default::default() });
|
||||
let fwcd = h.start(kotlin_attach(project.path(), "127.0.0.1", 5005));
|
||||
let id = tokio::time::timeout(Duration::from_secs(2), fwcd).await.unwrap().unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
tokio::time::pause();
|
||||
let h = harness(Script { ignore_configuration_done: true, ..Default::default() });
|
||||
let started = tokio::time::Instant::now();
|
||||
let err = h.start(kotlin_lsp_attach(project.path())).await.unwrap_err();
|
||||
assert!(started.elapsed() >= REQUEST_TIMEOUT, "{:?}", started.elapsed());
|
||||
assert!(err.message.contains("configurationDone"), "{err:?}");
|
||||
assert!(h.manager.sessions(None).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_lsp_sessions_have_the_memory_tab() {
|
||||
let h = harness(Script::default());
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert!(h.manager.capabilities(id).unwrap().jvm_memory);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn losing_the_kotlin_lsp_connection_ends_the_session() {
|
||||
let h = harness(Script { hang_up_after_stop: true, ..Script::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let session = h.manager.session(id).unwrap();
|
||||
assert!(session.jdwp_link.lock().is_some());
|
||||
let _ = session.conn.request_timeout("threads", Value::Null, Duration::from_secs(2)).await;
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
assert!(h.manager.sessions(None).is_empty());
|
||||
assert!(session.jdwp_link.lock().is_none());
|
||||
assert!(session.jvm_inspector.lock().is_none());
|
||||
}
|
||||
|
||||
/// The reasons of the first `count` stops, once that many arrived.
|
||||
async fn stop_reasons(h: &Harness, count: usize) -> Vec<String> {
|
||||
for _ in 0..200 {
|
||||
let reasons: Vec<String> = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(reason.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if reasons.len() >= count {
|
||||
return reasons;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("{count} stops not received; got {:?}", h.events.lock());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_step_stop_is_reported_as_a_step() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
for (config, reason) in [(kotlin_lsp_attach(project.path()), "step"), (config(), "breakpoint")] {
|
||||
let h = harness(Script { step_reason: Some("breakpoint"), ..Script::default() });
|
||||
let id = h.start(config).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
assert_eq!(stop_reasons(&h, 2).await, ["breakpoint", reason]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_breakpoint_after_continue_stays_a_breakpoint() {
|
||||
let h = harness(Script { step_reason: Some("breakpoint"), stop_after_continue: true, ..Script::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
stop_reasons(&h, 2).await;
|
||||
// The fake ends `stepIn` with no stop: the `continue` after it decides the next one.
|
||||
h.manager.step(id, 1, StepKind::Into).await.unwrap();
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
assert_eq!(stop_reasons(&h, 3).await, ["breakpoint", "step", "breakpoint"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_breakpoint_after_a_refused_step_stays_a_breakpoint() {
|
||||
let h = harness(Script { refuse_next: true, ..Script::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert!(h.manager.step(id, 1, StepKind::Over).await.is_err());
|
||||
assert_eq!(stop_reasons(&h, 2).await, ["breakpoint", "breakpoint"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_thread_from_an_earlier_stop_is_refused() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
for (config, kotlin_lsp) in [(kotlin_lsp_attach(project.path()), true), (config(), false)] {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert_eq!(h.manager.threads(id).await.unwrap().len(), 1);
|
||||
let started = tokio::time::Instant::now();
|
||||
let stale = h.manager.stack_trace(id, 99).await;
|
||||
let asked =
|
||||
|command: &str| h.log.lock().iter().any(|m| m["command"] == command && m["arguments"]["threadId"] == 99);
|
||||
if kotlin_lsp {
|
||||
assert!(stale.is_err() && started.elapsed() < Duration::from_millis(100), "{stale:?}");
|
||||
assert!(h.manager.step(id, 99, StepKind::Over).await.is_err());
|
||||
assert!(h.manager.resume(id, 99).await.is_err());
|
||||
assert!(!asked("stackTrace") && !asked("next") && !asked("continue"));
|
||||
} else {
|
||||
assert!(stale.is_ok() && asked("stackTrace"), "{stale:?}");
|
||||
}
|
||||
assert!(h.manager.stack_trace(id, 1).await.is_ok());
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_threads_reply_from_before_a_stop_does_not_vouch_for_its_ids() {
|
||||
let h = harness(Script { stop_during_threads: true, ..Script::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let threads = h.manager.threads(id).await.unwrap();
|
||||
// M3 maps kotlin-lsp's threads by these names.
|
||||
assert_eq!((threads[0].id, threads[0].name.as_str()), (1, "\"main\"@1"));
|
||||
stop_reasons(&h, 2).await;
|
||||
assert!(h.manager.stack_trace(id, 1).await.is_err());
|
||||
assert!(h.manager.stack_trace(id, 2).await.is_ok());
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_lsp_frames_get_real_paths() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let at = "at com.x.AppKt.main(App.kt:13)";
|
||||
for (config, path, name) in [
|
||||
(kotlin_lsp_attach(project.path()), "/p/App.kt", "com.x.AppKt.main(App.kt:13)"),
|
||||
(java_config("launch"), "file:///p/App.kt", at),
|
||||
] {
|
||||
let script = Script { source_path: Some("file:///p/App.kt".into()), frame_name: Some(at), ..Script::default() };
|
||||
let h = harness(script);
|
||||
let id = h.start(config).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames[0].path.as_ref().map(|p| p.0.clone()), Some(PathBuf::from(path)));
|
||||
assert_eq!(frames[0].name, name);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalidated_events_reach_the_client() {
|
||||
let h = harness(Script { invalidated_after_stop: true, ..Script::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
match h.wait_event(|e| matches!(e, DebugEvent::Invalidated { .. })).await {
|
||||
DebugEvent::Invalidated { areas } => assert_eq!(areas, ["variables"]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn rdbg_drains_test_output_after_dap_closes_before_killing_the_process() {
|
||||
|
||||
@@ -9,6 +9,14 @@ use std::path::{Path, PathBuf};
|
||||
/// configuration and roaming data keep following the OS.
|
||||
pub const LOCAL_DATA_ENV: &str = "OPENIDEA_LOCAL_DATA_DIR";
|
||||
|
||||
/// A custom local-data root chosen in Settings › System Settings › Caches,
|
||||
/// stored in the configuration directory. The environment variable still wins.
|
||||
pub const OVERRIDE_FILE: &str = "local-data-dir.txt";
|
||||
|
||||
/// A pending move of the local data to a newly chosen directory, carried out
|
||||
/// at the next start (before any project opens), like File › Invalidate Caches.
|
||||
const MIGRATION_FILE: &str = "local-data-migration.json";
|
||||
|
||||
/// `$OPENIDEA_LOCAL_DATA_DIR/<identifier>` when set, else the OS local data directory
|
||||
/// (Tauri's `app_local_data_dir`). The identifier keeps release and per-worktree
|
||||
/// debug builds apart under one root. A set but unusable path is an error, never a
|
||||
@@ -17,6 +25,203 @@ pub fn local_data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
resolve_local(std::env::var_os(LOCAL_DATA_ENV), dirs::data_local_dir(), identifier)
|
||||
}
|
||||
|
||||
/// The directory to actually start with: the environment override, else a valid
|
||||
/// custom directory from Settings, else the OS default. A stored but unusable
|
||||
/// custom directory is an error, never a silent fallback.
|
||||
pub fn startup_local_data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
startup_resolve(std::env::var_os(LOCAL_DATA_ENV), stored_override(identifier), dirs::data_local_dir(), identifier)
|
||||
}
|
||||
|
||||
fn startup_resolve(
|
||||
var: Option<OsString>,
|
||||
stored: Option<PathBuf>,
|
||||
os: Option<PathBuf>,
|
||||
identifier: &str,
|
||||
) -> Result<PathBuf, String> {
|
||||
if var.as_ref().is_some_and(|v| !v.is_empty()) {
|
||||
return resolve_local(var, os, identifier);
|
||||
}
|
||||
let Some(root) = stored else { return resolve_local(None, os, identifier) };
|
||||
if !root.is_absolute() {
|
||||
return Err(format!("custom local data directory must be an absolute path: {}", root.display()));
|
||||
}
|
||||
resolve_root(root, identifier, "custom local data directory")
|
||||
}
|
||||
|
||||
/// The file holding the custom local-data root, if the platform exposes its
|
||||
/// configuration directory. Both startup and Settings use this one path.
|
||||
pub fn override_path(identifier: &str) -> Option<PathBuf> {
|
||||
dirs::config_dir().map(|dir| dir.join(identifier).join(OVERRIDE_FILE))
|
||||
}
|
||||
|
||||
fn migration_path(identifier: &str) -> Option<PathBuf> {
|
||||
dirs::config_dir().map(|dir| dir.join(identifier).join(MIGRATION_FILE))
|
||||
}
|
||||
|
||||
/// The custom root stored by Settings, if any (validated when it is used).
|
||||
pub fn stored_override(identifier: &str) -> Option<PathBuf> {
|
||||
stored_override_in(&override_path(identifier)?)
|
||||
}
|
||||
|
||||
fn stored_override_in(path: &Path) -> Option<PathBuf> {
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
let trimmed = text.trim();
|
||||
(!trimmed.is_empty()).then(|| PathBuf::from(trimmed))
|
||||
}
|
||||
|
||||
/// The OS default local data directory (what clearing the custom directory
|
||||
/// returns to), ignoring any stored override. The environment still applies.
|
||||
pub fn default_local_data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
local_data_dir(identifier)
|
||||
}
|
||||
|
||||
/// Stores (`Some`) or clears (`None`) the custom local-data root, returning the
|
||||
/// directory that takes effect after a restart. A pending custom migration to
|
||||
/// anywhere else is dropped: only the caller schedules the matching one.
|
||||
pub fn set_override(identifier: &str, root: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let Some(path) = override_path(identifier) else {
|
||||
return Err("cannot find the configuration directory".into());
|
||||
};
|
||||
set_override_in(&path, &migration_path(identifier), root, identifier)
|
||||
}
|
||||
|
||||
fn set_override_in(
|
||||
path: &Path,
|
||||
migration: &Option<PathBuf>,
|
||||
root: Option<&Path>,
|
||||
identifier: &str,
|
||||
) -> Result<PathBuf, String> {
|
||||
if let Some(migration) = migration {
|
||||
let _ = fs::remove_file(migration);
|
||||
}
|
||||
let Some(root) = root else {
|
||||
if let Err(error) = fs::remove_file(path)
|
||||
&& error.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
return Err(format!("cannot clear the custom local data directory: {error}"));
|
||||
}
|
||||
return local_data_dir(identifier);
|
||||
};
|
||||
if !root.is_absolute() {
|
||||
return Err(format!("custom local data directory must be an absolute path: {}", root.display()));
|
||||
}
|
||||
let dir = resolve_root(root.to_path_buf(), identifier, "custom local data directory")?;
|
||||
if let Some(parent) = path.parent()
|
||||
&& let Err(error) = fs::create_dir_all(parent)
|
||||
{
|
||||
return Err(format!("cannot store the custom local data directory: {error}"));
|
||||
}
|
||||
if let Err(error) = fs::write(path, format!("{}\n", root.display())) {
|
||||
return Err(format!("cannot store the custom local data directory: {error}"));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
struct CustomMigration {
|
||||
from: PathBuf,
|
||||
to: PathBuf,
|
||||
}
|
||||
|
||||
/// Schedules a move of the local data from `from` to `to` at the next start.
|
||||
/// Returns false when there is nothing to move. The caller restarts the IDE.
|
||||
pub fn schedule_custom_migration(identifier: &str, from: &Path, to: &Path) -> Result<bool, String> {
|
||||
let Some(path) = migration_path(identifier) else {
|
||||
return Err("cannot find the configuration directory".into());
|
||||
};
|
||||
schedule_custom_migration_in(&path, from, to)
|
||||
}
|
||||
|
||||
fn schedule_custom_migration_in(path: &Path, from: &Path, to: &Path) -> Result<bool, String> {
|
||||
if from == to {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(parent) = path.parent()
|
||||
&& let Err(error) = fs::create_dir_all(parent)
|
||||
{
|
||||
return Err(format!("cannot schedule the data move: {error}"));
|
||||
}
|
||||
let json = serde_json::to_vec(&CustomMigration { from: from.into(), to: to.into() })
|
||||
.map_err(|error| format!("cannot schedule the data move: {error}"))?;
|
||||
if let Err(error) = fs::write(path, json) {
|
||||
return Err(format!("cannot schedule the data move: {error}"));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Carries out a scheduled custom migration aimed at `local` (call at start-up,
|
||||
/// before projects open). Entries that appear in the meantime are never
|
||||
/// overwritten; a partially moved tree is retried at the next start.
|
||||
pub fn apply_custom_migration(identifier: &str, local: &Path) {
|
||||
let Some(path) = migration_path(identifier) else { return };
|
||||
apply_custom_migration_in(&path, local);
|
||||
}
|
||||
|
||||
fn apply_custom_migration_in(path: &Path, local: &Path) {
|
||||
let Ok(bytes) = fs::read(path) else { return };
|
||||
let Ok(job) = serde_json::from_slice::<CustomMigration>(&bytes) else {
|
||||
let _ = fs::remove_file(path);
|
||||
return;
|
||||
};
|
||||
if job.to != local || job.from == local {
|
||||
let _ = fs::remove_file(path);
|
||||
return;
|
||||
}
|
||||
move_entries(&job.from, local, &custom_entries(&job.from));
|
||||
let leftover = custom_entries(&job.from).into_iter().any(|entry| job.from.join(entry).exists());
|
||||
if !leftover {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries of a local-data tree that move to a newly chosen directory.
|
||||
/// Non-relocatable tool installs (virtual environments with absolute interpreter
|
||||
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`.
|
||||
fn custom_entries(root: &Path) -> Vec<PathBuf> {
|
||||
let mut entries = local_entries(root);
|
||||
for extra in ["logs", "agents/tools"] {
|
||||
let entry = PathBuf::from(extra);
|
||||
if !entries.contains(&entry) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// Moves the local-data tree from `from` to `to`, entry by entry. Same-volume
|
||||
/// entries rename at once; cross-volume copies run in the background. Targets
|
||||
/// created in the meantime are never merged into or overwritten.
|
||||
fn move_entries(from: &Path, to: &Path, entries: &[PathBuf]) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let mut copies = Vec::new();
|
||||
for entry in entries {
|
||||
let source = from.join(entry);
|
||||
let target = to.join(entry);
|
||||
match try_rename(&source, &target) {
|
||||
Ok(true) => copies.push((source, target)),
|
||||
Ok(false) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(?source, ?target, %error, "data move failed; keeping old data, using new location")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !copies.is_empty() {
|
||||
let result = std::thread::Builder::new().name("openidea-data-migration".into()).spawn(move || {
|
||||
for (source, target) in copies {
|
||||
tracing::info!(?source, ?target, "copying data to the new location in background");
|
||||
if let Err(error) = copy_then_remove(&source, &target) {
|
||||
tracing::warn!(?source, ?target, %error, "data copy failed; keeping old data");
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(%error, "cannot start data migration worker; keeping old data");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_local(var: Option<OsString>, os: Option<PathBuf>, identifier: &str) -> Result<PathBuf, String> {
|
||||
let Some(root) = var.filter(|v| !v.is_empty()).map(PathBuf::from) else {
|
||||
return os.map(|dir| dir.join(identifier)).ok_or_else(|| "cannot find the local data directory".into());
|
||||
@@ -25,10 +230,14 @@ fn resolve_local(var: Option<OsString>, os: Option<PathBuf>, identifier: &str) -
|
||||
if !root.is_absolute() {
|
||||
return Err(format!("{LOCAL_DATA_ENV} must be an absolute path: {}", root.display()));
|
||||
}
|
||||
resolve_root(root, identifier, LOCAL_DATA_ENV)
|
||||
}
|
||||
|
||||
fn resolve_root(root: PathBuf, identifier: &str, what: &str) -> Result<PathBuf, String> {
|
||||
let dir = root.join(identifier);
|
||||
fs::create_dir_all(&dir)
|
||||
.and_then(|()| tempfile::NamedTempFile::new_in(&dir).map(drop))
|
||||
.map_err(|error| format!("{LOCAL_DATA_ENV}: cannot write to {}: {error}", dir.display()))?;
|
||||
.map_err(|error| format!("{what}: cannot write to {}: {error}", dir.display()))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
@@ -77,6 +286,11 @@ pub fn migrate(data: &Path, local: &Path) {
|
||||
}
|
||||
|
||||
fn migrate_entries(data: &Path, local: &Path) {
|
||||
move_entries(data, local, &local_entries(data));
|
||||
}
|
||||
|
||||
/// The rebuildable entries of the legacy roaming tree that move to Local.
|
||||
fn local_entries(data: &Path) -> Vec<PathBuf> {
|
||||
let mut entries: Vec<PathBuf> = [
|
||||
"language-server-runtimes",
|
||||
"index",
|
||||
@@ -118,31 +332,7 @@ fn migrate_entries(data: &Path, local: &Path) {
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => tracing::warn!(%error, "cannot enumerate legacy tools; keeping old data, using Local"),
|
||||
}
|
||||
let mut copies = Vec::new();
|
||||
for entry in entries {
|
||||
let source = data.join(&entry);
|
||||
let target = data_path(data, local, &entry);
|
||||
match try_rename(&source, &target) {
|
||||
Ok(true) => copies.push((source, target)),
|
||||
Ok(false) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(?source, ?target, %error, "data migration failed; keeping old data, using Local")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !copies.is_empty() {
|
||||
let result = std::thread::Builder::new().name("openidea-data-migration".into()).spawn(move || {
|
||||
for (source, target) in copies {
|
||||
tracing::info!(?source, ?target, "copying legacy data in background");
|
||||
if let Err(error) = copy_then_remove(&source, &target) {
|
||||
tracing::warn!(?source, ?target, %error, "data copy failed; keeping old data, using Local");
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(%error, "cannot start data migration worker; keeping old data, using Local");
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// Returns true when a cross-volume copy is needed.
|
||||
@@ -597,4 +787,108 @@ mod tests {
|
||||
.any(|e| e.file_name().to_string_lossy().starts_with(".migration-"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_override_round_trips_and_validates() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("local-data-dir.txt");
|
||||
let migration = tmp.path().join("local-data-migration.json");
|
||||
let id = "ai.test.openidea";
|
||||
assert_eq!(stored_override_in(&file), None);
|
||||
|
||||
let root = tmp.path().join("custom-root");
|
||||
let dir = set_override_in(&file, &Some(migration.clone()), Some(&root), id).unwrap();
|
||||
assert_eq!(dir, root.join(id));
|
||||
assert!(dir.is_dir());
|
||||
assert_eq!(stored_override_in(&file), Some(root.clone()));
|
||||
assert_eq!(startup_resolve(None, stored_override_in(&file), Some(tmp.path().join("os")), id).unwrap(), dir);
|
||||
|
||||
// A relative root is rejected before anything is written.
|
||||
let before = fs::read_to_string(&file).unwrap();
|
||||
let error = set_override_in(&file, &Some(migration.clone()), Some(Path::new("relative")), id).unwrap_err();
|
||||
assert!(error.contains("absolute"), "{error}");
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), before);
|
||||
|
||||
// An unwritable root (an existing file) is rejected too.
|
||||
let blocker = tmp.path().join("blocker");
|
||||
fs::write(&blocker, "").unwrap();
|
||||
let error = set_override_in(&file, &Some(migration.clone()), Some(&blocker), id).unwrap_err();
|
||||
assert!(error.contains("cannot write"), "{error}");
|
||||
|
||||
// Clearing removes the file and returns the default.
|
||||
let dir = set_override_in(&file, &Some(migration), None, id).unwrap();
|
||||
assert!(!file.exists());
|
||||
assert_eq!(dir, local_data_dir(id).unwrap());
|
||||
assert_eq!(stored_override_in(&file), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_prefers_the_environment_then_the_override() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let os = tmp.path().join("os");
|
||||
let custom = tmp.path().join("custom");
|
||||
let env = tmp.path().join("env");
|
||||
let id = "ai.test.openidea";
|
||||
|
||||
let error = startup_resolve(None, Some(PathBuf::from("relative")), Some(os.clone()), id).unwrap_err();
|
||||
assert!(error.contains("absolute"), "{error}");
|
||||
|
||||
// The environment wins over a stored override.
|
||||
let dir = startup_resolve(Some(env.clone().into()), Some(custom.clone()), Some(os.clone()), id).unwrap();
|
||||
assert_eq!(dir, env.join(id));
|
||||
|
||||
// Without the environment the override wins over the OS default.
|
||||
let dir = startup_resolve(None, Some(custom.clone()), Some(os.clone()), id).unwrap();
|
||||
assert_eq!(dir, custom.join(id));
|
||||
|
||||
// And without either the OS default applies.
|
||||
let dir = startup_resolve(None, None, Some(os.clone()), id).unwrap();
|
||||
assert_eq!(dir, os.join(id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_migration_moves_the_tree_and_clears_itself() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let marker = tmp.path().join("local-data-migration.json");
|
||||
let from = tmp.path().join("old-local");
|
||||
let to = tmp.path().join("new-local");
|
||||
fs::create_dir_all(from.join("index/p1")).unwrap();
|
||||
fs::write(from.join("index/p1/symbols"), "index").unwrap();
|
||||
fs::create_dir_all(from.join("cache/p1")).unwrap();
|
||||
fs::write(from.join("cache/p1/build"), "cache").unwrap();
|
||||
fs::create_dir_all(from.join("tools/demo/bin")).unwrap();
|
||||
fs::write(from.join("tools/demo/bin/demo.cmd"), "payload").unwrap();
|
||||
fs::write(from.join("history"), "roaming stays").unwrap();
|
||||
|
||||
// Nothing to move: no marker is written.
|
||||
assert!(!schedule_custom_migration_in(&marker, &from, &from).unwrap());
|
||||
assert!(!marker.exists());
|
||||
|
||||
assert!(schedule_custom_migration_in(&marker, &from, &to).unwrap());
|
||||
apply_custom_migration_in(&marker, &to);
|
||||
assert!(!marker.exists());
|
||||
assert_eq!(fs::read_to_string(to.join("index/p1/symbols")).unwrap(), "index");
|
||||
assert_eq!(fs::read_to_string(to.join("cache/p1/build")).unwrap(), "cache");
|
||||
assert!(to.join("tools/demo/bin/demo.cmd").exists());
|
||||
assert!(!from.join("index").exists());
|
||||
// Roaming content is not local data and stays behind.
|
||||
assert_eq!(fs::read_to_string(from.join("history")).unwrap(), "roaming stays");
|
||||
|
||||
// A migration aimed elsewhere is dropped without touching anything.
|
||||
fs::create_dir_all(from.join("lsp")).unwrap();
|
||||
assert!(schedule_custom_migration_in(&marker, &from, &tmp.path().join("elsewhere")).unwrap());
|
||||
apply_custom_migration_in(&marker, &to);
|
||||
assert!(!marker.exists());
|
||||
assert!(from.join("lsp").exists());
|
||||
assert!(!to.join("lsp").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_entries_cover_logs_and_agent_tools() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let entries = custom_entries(tmp.path());
|
||||
for expected in ["logs", "agents/tools", "index", "cache", "lsp", "agents/registry.json"] {
|
||||
assert!(entries.contains(&PathBuf::from(expected)), "{entries:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
mod kotlin;
|
||||
#[cfg(test)]
|
||||
mod kotlin_tests;
|
||||
mod output;
|
||||
|
||||
use crate::Host;
|
||||
@@ -41,6 +44,7 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
config = kotlin::choose_kotlin_debugger(host, window, config).await?;
|
||||
if config.adapter == ide_dap::kotlin::ADAPTER {
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let runtime_root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
//! Kotlin debugging: kotlin-lsp's debugger when the project's kotlin-lsp can serve it, else
|
||||
//! kotlin-debug-adapter with a notice saying why.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::task::CancelHandle;
|
||||
use ide_core::{CancellationToken, IdeEvent, IdeResult, SharedSink, TaskId};
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) const KOTLIN_IMPORT_WAIT: Duration = Duration::from_secs(120);
|
||||
/// A ready kotlin-lsp answers well within this; only a longer wait shows a task.
|
||||
const TASK_DELAY: Duration = Duration::from_millis(500);
|
||||
|
||||
// Catalogued as written (`{detail}` replaced at runtime): the text catalog test counts these
|
||||
// literals as the use of its entries.
|
||||
const TASK_TITLE: &str = "Waiting for kotlin-lsp to import the project";
|
||||
const NOTICE_TITLE: &str = "Debugging Kotlin with kotlin-debug-adapter";
|
||||
const NOT_CONFIGURED: &str = "kotlin-lsp is not the Kotlin language server of this project.";
|
||||
const NOT_INSTALLED: &str = "kotlin-lsp is not installed.";
|
||||
const NOT_STARTED: &str = "kotlin-lsp did not start: {detail}";
|
||||
const STILL_IMPORTING: &str =
|
||||
"kotlin-lsp is still importing the project. Debug again once the import has finished to use its debugger.";
|
||||
const IMPORT_FAILED: &str = "kotlin-lsp could not import the project.";
|
||||
const FAILED: &str = "kotlin-lsp could not start its debugger: {detail}";
|
||||
|
||||
/// `config` for kotlin-lsp's debug server on `port`; the rest of the launch stays as it is.
|
||||
pub(super) fn use_kotlin_lsp(mut config: LaunchConfig, port: u16) -> IdeResult<LaunchConfig> {
|
||||
let mut extra = extra_object(&config)?;
|
||||
extra.insert("debugServer".into(), port.into());
|
||||
config.adapter = ide_dap::kotlin_lsp::ADAPTER.into();
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The dedupe key of `reason` and the notice body (English, translated by the UI's catalog).
|
||||
pub(super) fn fallback_notice(reason: &KotlinDebugUnavailable) -> (&'static str, String) {
|
||||
match reason {
|
||||
KotlinDebugUnavailable::NotConfigured => ("notConfigured", NOT_CONFIGURED.into()),
|
||||
KotlinDebugUnavailable::NotInstalled => ("notInstalled", NOT_INSTALLED.into()),
|
||||
KotlinDebugUnavailable::NotStarted(detail) => ("notStarted", NOT_STARTED.replace("{detail}", detail)),
|
||||
KotlinDebugUnavailable::StillImporting => ("stillImporting", STILL_IMPORTING.into()),
|
||||
KotlinDebugUnavailable::ImportFailed => ("importFailed", IMPORT_FAILED.into()),
|
||||
KotlinDebugUnavailable::Failed(detail) => ("failed", FAILED.replace("{detail}", detail)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A kotlin-debug-adapter launch becomes a kotlin-lsp one when the project's kotlin-lsp has
|
||||
/// imported the module and started its debug server; otherwise it stays on
|
||||
/// kotlin-debug-adapter and the window is told why (once per reason).
|
||||
pub(super) async fn choose_kotlin_debugger(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<LaunchConfig> {
|
||||
if config.adapter == ide_dap::kotlin_lsp::ADAPTER {
|
||||
require_debug_server(&config)?;
|
||||
return Ok(config);
|
||||
}
|
||||
if config.adapter != ide_dap::kotlin::ADAPTER {
|
||||
return Ok(config);
|
||||
}
|
||||
let Ok(project) = host.project(window) else {
|
||||
tracing::info!(
|
||||
"debugging Kotlin with kotlin-debug-adapter: {}",
|
||||
fallback_notice(&KotlinDebugUnavailable::NotConfigured).1
|
||||
);
|
||||
return Ok(config);
|
||||
};
|
||||
let path = debug_path(&config).unwrap_or_else(|| project.root.clone());
|
||||
let lsp = project.lsp.clone();
|
||||
let chosen = wait_for_debug_server(&project.sink, |cancel| async move {
|
||||
lsp.kotlin_debug_server(&path, KOTLIN_IMPORT_WAIT, &cancel).await
|
||||
})
|
||||
.await;
|
||||
match chosen {
|
||||
Ok(server) => use_kotlin_lsp(config, server.port),
|
||||
Err(reason) => {
|
||||
report_fallback(&project.kotlin_debug_notices, &project.sink, &reason);
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// kotlin-lsp is only reached through the port its language server opened; without one
|
||||
/// ide-dap would try to spawn a `kotlin-lsp` adapter that does not exist.
|
||||
fn require_debug_server(config: &LaunchConfig) -> IdeResult<()> {
|
||||
match extra_object(config)?.get("debugServer") {
|
||||
None | Some(serde_json::Value::Null) => Err(ide_core::IdeError::invalid(
|
||||
"A kotlin-lsp debug configuration needs \"debugServer\": the port of kotlin-lsp's debug server. \
|
||||
Use kotlin-debug-adapter to let the IDE start it.",
|
||||
)),
|
||||
Some(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra_object(config: &LaunchConfig) -> IdeResult<serde_json::Map<String, serde_json::Value>> {
|
||||
match config.extra_json.as_deref().map(serde_json::from_str).transpose() {
|
||||
Ok(None) => Ok(serde_json::Map::new()),
|
||||
Ok(Some(serde_json::Value::Object(extra))) => Ok(extra),
|
||||
Ok(Some(other)) => Err(ide_core::IdeError::invalid(format!("launch arguments are not an object: {other}"))),
|
||||
Err(e) => Err(ide_core::IdeError::invalid(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module to debug: the launch's `projectRoot`, else its working directory.
|
||||
fn debug_path(config: &LaunchConfig) -> Option<PathBuf> {
|
||||
let extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok());
|
||||
extra
|
||||
.as_ref()
|
||||
.and_then(|e| e.get("projectRoot")?.as_str())
|
||||
.filter(|root| !root.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| config.cwd.as_deref().map(PathBuf::from))
|
||||
}
|
||||
|
||||
/// Runs `debug_server` with a token the user can cancel; a wait longer than [`TASK_DELAY`]
|
||||
/// shows as a cancellable task, which ends however the wait does (also when dropped).
|
||||
async fn wait_for_debug_server<F, Fut>(
|
||||
sink: &SharedSink,
|
||||
debug_server: F,
|
||||
) -> Result<KotlinDebugServer, KotlinDebugUnavailable>
|
||||
where
|
||||
F: FnOnce(CancellationToken) -> Fut,
|
||||
Fut: Future<Output = Result<KotlinDebugServer, KotlinDebugUnavailable>>,
|
||||
{
|
||||
let cancel = CancellationToken::new();
|
||||
let id = TaskId::next();
|
||||
let handle = ide_core::task::on_cancel(id, {
|
||||
let cancel = cancel.clone();
|
||||
move || cancel.cancel()
|
||||
});
|
||||
let wait = debug_server(cancel);
|
||||
tokio::pin!(wait);
|
||||
if let Ok(answer) = tokio::time::timeout(TASK_DELAY, &mut wait).await {
|
||||
return answer;
|
||||
}
|
||||
let _task = WaitTask::start(sink.clone(), id, handle);
|
||||
wait.await
|
||||
}
|
||||
|
||||
/// The visible import wait; dropping it ends the task.
|
||||
struct WaitTask {
|
||||
sink: SharedSink,
|
||||
id: TaskId,
|
||||
_cancel: CancelHandle,
|
||||
}
|
||||
|
||||
impl WaitTask {
|
||||
fn start(sink: SharedSink, id: TaskId, cancel: CancelHandle) -> Self {
|
||||
let task = Self { sink, id, _cancel: cancel };
|
||||
task.emit(false);
|
||||
task
|
||||
}
|
||||
|
||||
fn emit(&self, done: bool) {
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: self.id,
|
||||
title: TASK_TITLE.into(),
|
||||
message: None,
|
||||
fraction: None,
|
||||
done,
|
||||
cancellable: !done,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WaitTask {
|
||||
fn drop(&mut self) {
|
||||
self.emit(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs every fallback; notifies the window once per reason.
|
||||
fn report_fallback(notices: &Mutex<HashSet<&'static str>>, sink: &SharedSink, reason: &KotlinDebugUnavailable) {
|
||||
let (key, body) = fallback_notice(reason);
|
||||
tracing::info!("debugging Kotlin with kotlin-debug-adapter: {body}");
|
||||
if notices.lock().insert(key) {
|
||||
sink.emit(IdeEvent::Notify { level: NotifyLevel::Info, title: NOTICE_TITLE.into(), body: Some(body) });
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn launch(adapter: &str, extra: serde_json::Value) -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "AppKt".into(),
|
||||
adapter: adapter.into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some("/cwd".into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(extra.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra(config: &LaunchConfig) -> serde_json::Value {
|
||||
serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn reasons() -> Vec<KotlinDebugUnavailable> {
|
||||
vec![
|
||||
KotlinDebugUnavailable::NotConfigured,
|
||||
KotlinDebugUnavailable::NotInstalled,
|
||||
KotlinDebugUnavailable::NotStarted("needs JDK 21".into()),
|
||||
KotlinDebugUnavailable::StillImporting,
|
||||
KotlinDebugUnavailable::ImportFailed,
|
||||
KotlinDebugUnavailable::Failed("boom".into()),
|
||||
]
|
||||
}
|
||||
|
||||
fn recording_sink() -> (SharedSink, Arc<Mutex<Vec<IdeEvent>>>) {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let recorded = events.clone();
|
||||
(Arc::new(move |event| recorded.lock().push(event)), events)
|
||||
}
|
||||
|
||||
/// `(done, cancellable)` of each task event, with the task id.
|
||||
fn tasks(events: &Mutex<Vec<IdeEvent>>) -> Vec<(ide_core::TaskId, String, bool, bool)> {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { id, title, done, cancellable, .. } => Some((*id, title.clone(), *done, *cancellable)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn server() -> KotlinDebugServer {
|
||||
KotlinDebugServer { port: 4711, root: PathBuf::from("/p") }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_lsp_takes_the_debug_server_port() {
|
||||
let config = launch(ide_dap::kotlin::ADAPTER, serde_json::json!({"mainClass": "a.AppKt", "projectRoot": "/p"}));
|
||||
let c = use_kotlin_lsp(config, 4711).unwrap();
|
||||
assert_eq!(c.adapter, ide_dap::kotlin_lsp::ADAPTER);
|
||||
let args = extra(&c);
|
||||
assert_eq!(args["debugServer"], 4711);
|
||||
assert_eq!(args["mainClass"], "a.AppKt");
|
||||
assert_eq!(args["projectRoot"], "/p");
|
||||
assert!(args.get("__adapterJavaHome").is_none());
|
||||
assert_eq!(
|
||||
(c.name.as_str(), c.request.as_str(), c.cwd.as_deref()),
|
||||
("AppKt", "launch", Some(Path::new("/cwd")))
|
||||
);
|
||||
let mut bare = launch(ide_dap::kotlin::ADAPTER, serde_json::json!({}));
|
||||
bare.extra_json = None;
|
||||
assert_eq!(extra(&use_kotlin_lsp(bare, 4711).unwrap())["debugServer"], 4711);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fallback_reason_has_a_catalogued_text() {
|
||||
let catalogs: [(&str, serde_json::Value); 2] = [
|
||||
("en", serde_json::from_str(include_str!("../../../../../src/platform/locales/text/en.json")).unwrap()),
|
||||
("zh", serde_json::from_str(include_str!("../../../../../src/platform/locales/text/zh.json")).unwrap()),
|
||||
];
|
||||
let templates = [NOT_CONFIGURED, NOT_INSTALLED, NOT_STARTED, STILL_IMPORTING, IMPORT_FAILED, FAILED];
|
||||
for reason in reasons() {
|
||||
let (_, body) = fallback_notice(&reason);
|
||||
let detail = match &reason {
|
||||
KotlinDebugUnavailable::NotStarted(d) | KotlinDebugUnavailable::Failed(d) => d.as_str(),
|
||||
_ => "",
|
||||
};
|
||||
assert!(
|
||||
templates.iter().any(|t| t.replace("{detail}", detail) == body),
|
||||
"{reason:?}: {body:?} is not built from a catalogued template"
|
||||
);
|
||||
}
|
||||
for text in templates.iter().chain([&NOTICE_TITLE, &TASK_TITLE]) {
|
||||
for (locale, catalog) in &catalogs {
|
||||
let translated = catalog[*text].as_str().unwrap_or_else(|| panic!("{locale}.json lacks {text:?}"));
|
||||
if *locale == "zh" {
|
||||
assert_ne!(translated, *text, "zh.json leaves {text:?} untranslated");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_reasons_have_distinct_keys() {
|
||||
let keys: HashSet<_> = reasons().iter().map(|r| fallback_notice(r).0).collect();
|
||||
assert_eq!(keys.len(), reasons().len());
|
||||
// The detail does not make another reason.
|
||||
assert_eq!(
|
||||
fallback_notice(&KotlinDebugUnavailable::Failed("a".into())).0,
|
||||
fallback_notice(&KotlinDebugUnavailable::Failed("b".into())).0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kotlin_lsp_config_without_a_debug_server_is_refused() {
|
||||
let refused = require_debug_server(&launch(ide_dap::kotlin_lsp::ADAPTER, serde_json::json!({}))).unwrap_err();
|
||||
assert_eq!(refused.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert!(refused.message.contains("debugServer"), "{}", refused.message);
|
||||
let mut bare = launch(ide_dap::kotlin_lsp::ADAPTER, serde_json::json!({}));
|
||||
bare.extra_json = None;
|
||||
assert!(require_debug_server(&bare).is_err());
|
||||
assert!(
|
||||
require_debug_server(&launch(ide_dap::kotlin_lsp::ADAPTER, serde_json::json!({"debugServer": null})))
|
||||
.is_err()
|
||||
);
|
||||
for port in [serde_json::json!(4711), serde_json::json!("10.0.0.5:4711")] {
|
||||
require_debug_server(&launch(ide_dap::kotlin_lsp::ADAPTER, serde_json::json!({"debugServer": port})))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_is_the_project_root_else_the_working_directory() {
|
||||
let with_root = launch(ide_dap::kotlin::ADAPTER, serde_json::json!({"projectRoot": "/p/app"}));
|
||||
assert_eq!(debug_path(&with_root), Some(PathBuf::from("/p/app")));
|
||||
assert_eq!(debug_path(&launch(ide_dap::kotlin::ADAPTER, serde_json::json!({}))), Some(PathBuf::from("/cwd")));
|
||||
let mut neither = launch(ide_dap::kotlin::ADAPTER, serde_json::json!({}));
|
||||
neither.cwd = None;
|
||||
assert_eq!(debug_path(&neither), None);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_quick_answer_shows_no_task() {
|
||||
let (sink, events) = recording_sink();
|
||||
assert_eq!(wait_for_debug_server(&sink, |_| async { Ok(server()) }).await, Ok(server()));
|
||||
assert!(events.lock().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_longer_wait_shows_a_task_that_ends_on_every_outcome() {
|
||||
for outcome in [Ok(server()), Err(KotlinDebugUnavailable::ImportFailed)] {
|
||||
let (sink, events) = recording_sink();
|
||||
let answer = outcome.clone();
|
||||
let result = wait_for_debug_server(&sink, |_| async move {
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
answer
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result, outcome);
|
||||
let tasks = tasks(&events);
|
||||
assert_eq!(tasks.len(), 2, "{tasks:?}");
|
||||
assert_eq!(tasks[0].0, tasks[1].0);
|
||||
assert_eq!(tasks[0].1, TASK_TITLE);
|
||||
assert_eq!((tasks[0].2, tasks[0].3), (false, true));
|
||||
assert_eq!((tasks[1].2, tasks[1].3), (true, false));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cancelling_the_task_stops_the_wait() {
|
||||
let (sink, events) = recording_sink();
|
||||
let wait = tokio::spawn(async move {
|
||||
wait_for_debug_server(&sink, |cancel| async move {
|
||||
cancel.cancelled().await;
|
||||
Err(KotlinDebugUnavailable::StillImporting)
|
||||
})
|
||||
.await
|
||||
});
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let id = tasks(&events)[0].0;
|
||||
assert!(ide_core::task::cancel(id));
|
||||
assert_eq!(wait.await.unwrap(), Err(KotlinDebugUnavailable::StillImporting));
|
||||
assert_eq!(tasks(&events).last().map(|t| t.2), Some(true));
|
||||
assert!(!ide_core::task::cancel(id), "an ended wait is no longer cancellable");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_dropped_wait_ends_its_task() {
|
||||
let (sink, events) = recording_sink();
|
||||
let wait = tokio::spawn(async move {
|
||||
wait_for_debug_server(&sink, |_| std::future::pending::<Result<KotlinDebugServer, _>>()).await
|
||||
});
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
wait.abort();
|
||||
let _ = wait.await;
|
||||
assert_eq!(tasks(&events).iter().map(|t| t.2).collect::<Vec<_>>(), [false, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_notice_shows_once_per_reason() {
|
||||
let (sink, events) = recording_sink();
|
||||
let notices = Mutex::new(HashSet::new());
|
||||
for reason in [
|
||||
KotlinDebugUnavailable::StillImporting,
|
||||
KotlinDebugUnavailable::StillImporting,
|
||||
KotlinDebugUnavailable::NotStarted("needs JDK 21".into()),
|
||||
KotlinDebugUnavailable::NotStarted("crashed".into()),
|
||||
] {
|
||||
report_fallback(¬ices, &sink, &reason);
|
||||
}
|
||||
let notes: Vec<_> = events
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
IdeEvent::Notify { level, title, body } => (*level, title.clone(), body.clone()),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
notes,
|
||||
[
|
||||
(NotifyLevel::Info, NOTICE_TITLE.to_string(), Some(STILL_IMPORTING.to_string())),
|
||||
(
|
||||
NotifyLevel::Info,
|
||||
NOTICE_TITLE.to_string(),
|
||||
Some("kotlin-lsp did not start: needs JDK 21".to_string())
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Kotlin's debugger choice through a real `Host` and project: the fallback notice and the
|
||||
//! refusal of a kotlin-lsp configuration without its debug server.
|
||||
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_lsp::KotlinDebugUnavailable;
|
||||
use ide_workspace::SettingsScope;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
const NOTICE_TITLE: &str = "Debugging Kotlin with kotlin-debug-adapter";
|
||||
|
||||
struct Fixture {
|
||||
host: Host,
|
||||
root: PathBuf,
|
||||
events: Arc<Mutex<Vec<IdeEvent>>>,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// A trusted Gradle project opened with these global settings; kotlin-debug-adapter is a
|
||||
/// missing executable, so a session fails right after the debugger is chosen.
|
||||
async fn new(settings: &[(&str, serde_json::Value)]) -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("settings.gradle.kts"), "rootProject.name = \"app\"\n").unwrap();
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured = events.clone();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |_| {
|
||||
let events = captured.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
}),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let missing = base.join("missing").join("kotlin-debug-adapter");
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "tools", serde_json::json!({"kotlin-debug-adapter": {"path": missing}}))
|
||||
.unwrap();
|
||||
for (key, value) in settings {
|
||||
host.global_settings.set(SettingsScope::Global, key, value.clone()).unwrap();
|
||||
}
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
Self { host, root, events, _temp: temp }
|
||||
}
|
||||
|
||||
fn launch(&self, adapter: &str, extra: serde_json::Value) -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "AppKt".into(),
|
||||
adapter: adapter.into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(self.root.clone().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(extra.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn kotlin_launch(&self) -> LaunchConfig {
|
||||
let extra = serde_json::json!({"mainClass": "com.example.AppKt", "projectRoot": self.root});
|
||||
self.launch(ide_dap::kotlin::ADAPTER, extra)
|
||||
}
|
||||
|
||||
/// `(level, body)` of each fallback notice.
|
||||
fn notices(&self) -> Vec<(NotifyLevel, Option<String>)> {
|
||||
self.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Notify { level, title, body } if title == NOTICE_TITLE => Some((*level, body.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two Debugs, each failing only at kotlin-debug-adapter's missing executable.
|
||||
async fn debug_twice(f: &Fixture) {
|
||||
for _ in 0..2 {
|
||||
let error = debug_start(&f.host, "main", f.kotlin_launch()).await.unwrap_err();
|
||||
assert!(!error.message.contains("Restricted Mode"), "{}", error.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn kotlin_lsp_turned_off_gives_one_notice_over_two_debugs() {
|
||||
let f = Fixture::new(&[("languageServers", serde_json::json!({"kotlin-lsp": {"enabled": false}}))]).await;
|
||||
debug_twice(&f).await;
|
||||
let (_, body) = kotlin::fallback_notice(&KotlinDebugUnavailable::NotConfigured);
|
||||
assert_eq!(f.notices(), [(NotifyLevel::Info, Some(body))]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_missing_kotlin_lsp_gives_one_notice_over_two_debugs() {
|
||||
let missing = serde_json::json!({"kotlin-lsp": {"command": "/nonexistent/kotlin-lsp"}});
|
||||
let f = Fixture::new(&[("languageServers", missing)]).await;
|
||||
debug_twice(&f).await;
|
||||
let (_, body) = kotlin::fallback_notice(&KotlinDebugUnavailable::NotInstalled);
|
||||
assert_eq!(f.notices(), [(NotifyLevel::Info, Some(body))]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_kotlin_lsp_config_without_its_debug_server_is_refused() {
|
||||
let f = Fixture::new(&[]).await;
|
||||
let config = f.launch(ide_dap::kotlin_lsp::ADAPTER, serde_json::json!({"mainClass": "com.example.AppKt"}));
|
||||
let refused = debug_start(&f.host, "main", config).await.unwrap_err();
|
||||
assert_eq!(refused.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert!(refused.message.contains("debugServer"), "{}", refused.message);
|
||||
assert!(f.notices().is_empty());
|
||||
}
|
||||
@@ -169,6 +169,25 @@ pub async fn remote_rename(state: &Host, connection: FsConnection, from: String,
|
||||
state.remote.remote_rename(&connection, &from, &to).await
|
||||
}
|
||||
|
||||
/// Remote Host › Download to…: remote files and folders into a local folder, each under its
|
||||
/// own name.
|
||||
pub async fn remote_download_into(
|
||||
window: &str,
|
||||
state: &Host,
|
||||
connection: FsConnection,
|
||||
paths: Vec<String>,
|
||||
target: IpcPath,
|
||||
request: RequestId,
|
||||
) -> IdeResult<TransferReport> {
|
||||
let project = state.project(window)?;
|
||||
let token = state.begin_request(request);
|
||||
let (mut report, done) = progress(project.sink.clone(), "Downloading", token.clone());
|
||||
let r = state.remote.download_into(&connection, &paths, &target, &token, &mut report).await;
|
||||
done();
|
||||
state.end_request(request);
|
||||
r
|
||||
}
|
||||
|
||||
pub async fn deploy_test_connection(state: &Host, connection: FsConnection, path: String) -> IdeResult<()> {
|
||||
state.remote.test_connection(&connection, &path).await
|
||||
}
|
||||
@@ -197,6 +216,17 @@ pub(crate) fn register(d: &mut crate::rpc::Dispatcher) {
|
||||
d.add("remote_of", |c| async move { Ok(remote_of(&c.host, c.arg("path")?)) });
|
||||
d.add("remote_delete", |c| async move { remote_delete(&c.host, c.arg("connection")?, c.arg("path")?).await });
|
||||
d.add("remote_mkdir", |c| async move { remote_mkdir(&c.host, c.arg("connection")?, c.arg("path")?).await });
|
||||
d.add("remote_download_into", |c| async move {
|
||||
remote_download_into(
|
||||
&c.window,
|
||||
&c.host,
|
||||
c.arg("connection")?,
|
||||
c.arg("paths")?,
|
||||
c.arg("target")?,
|
||||
c.arg("request")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("remote_rename", |c| async move {
|
||||
remote_rename(&c.host, c.arg("connection")?, c.arg("from")?, c.arg("to")?).await
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@ use ide_vfs::Watcher;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -50,6 +50,8 @@ pub struct Project {
|
||||
pub cache_dir: PathBuf,
|
||||
/// Superseded launch snapshots retained until this project session ends.
|
||||
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
pub db: Arc<ide_db::DbManager>,
|
||||
/// HTTP Client responses (IDEA's `.idea/httpRequests`), in the app data dir.
|
||||
@@ -563,6 +565,7 @@ impl Host {
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
@@ -724,6 +727,7 @@ impl Host {
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
|
||||
@@ -330,6 +330,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"remote_delete",
|
||||
"remote_mkdir",
|
||||
"remote_rename",
|
||||
"remote_download_into",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
|
||||
@@ -94,6 +94,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
"remote_delete",
|
||||
"remote_mkdir",
|
||||
"remote_rename",
|
||||
"remote_download_into",
|
||||
"remote_import_local",
|
||||
"remote_bootstrap_exec",
|
||||
"deploy_upload",
|
||||
|
||||
@@ -398,6 +398,9 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
}
|
||||
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
|
||||
"intellij/workspaceImportState" if self.server.name == crate::kotlin_lsp::KOTLIN_LSP => {
|
||||
crate::kotlin_lsp::record_import_state(&self.server, self.generation, ¶ms)
|
||||
}
|
||||
"language/status" if self.server.name == "jdtls" && params["type"] == "ServiceReady" => {
|
||||
mgr.java_import_ready(self.server.clone(), self.generation);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! kotlin-lsp's built-in debug adapter: `start_debug_server` once the server has imported
|
||||
//! the project (breakpoints set before that are "verified" but never hit).
|
||||
|
||||
use crate::LspManager;
|
||||
use crate::server::Server;
|
||||
use ide_core::event::ServerStatus;
|
||||
use ide_core::{CancellationToken, LanguageId};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// The server's name in `languages/kotlin.toml`.
|
||||
pub const KOTLIN_LSP: &str = "kotlin-lsp";
|
||||
/// A cold start imports the Gradle model before answering `initialize`.
|
||||
const READY_TIMEOUT: Duration = Duration::from_secs(240);
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The last `intellij/workspaceImportState` of the current instance.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ImportState {
|
||||
pub finished: bool,
|
||||
/// Workspace folders whose import did not succeed.
|
||||
pub failed: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct KotlinDebugServer {
|
||||
/// Local TCP port of the DAP server.
|
||||
pub port: u16,
|
||||
/// Root of the kotlin-lsp instance that serves it.
|
||||
pub root: PathBuf,
|
||||
}
|
||||
|
||||
/// Why kotlin-lsp cannot debug the module, for the fallback notice.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum KotlinDebugUnavailable {
|
||||
/// No `kotlin-lsp` among the module's servers (disabled in settings, another server chosen).
|
||||
NotConfigured,
|
||||
NotInstalled,
|
||||
/// The status message, else the status.
|
||||
NotStarted(String),
|
||||
/// The import did not finish in time, or the wait was cancelled.
|
||||
StillImporting,
|
||||
ImportFailed,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Records `intellij/workspaceImportState` from instance `generation`. Completion is this
|
||||
/// notification, not "no `$/progress` left": kotlin-lsp reports "Indexing" every few seconds.
|
||||
pub(crate) fn record_import_state(server: &Server, generation: u64, params: &Value) {
|
||||
let failed = params["folders"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|folder| folder["status"] != "SUCCESS")
|
||||
.filter_map(|folder| folder["folderUri"].as_str().and_then(crate::uri::uri_to_path))
|
||||
.collect();
|
||||
server.set_import_state(generation, ImportState { finished: params["phase"] == "FINISHED", failed });
|
||||
}
|
||||
|
||||
fn importing(server: &Server) -> bool {
|
||||
server.progress.lock().values().any(|p| p.title.contains("Importing"))
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// Starts kotlin-lsp's debug server for `path` (a module directory or source file) once
|
||||
/// the project is imported, starting kotlin-lsp if needed. `import_wait` bounds the wait
|
||||
/// for the import after the server is up; cancelling `cancel` ends it as
|
||||
/// [`KotlinDebugUnavailable::StillImporting`].
|
||||
pub async fn kotlin_debug_server(
|
||||
&self,
|
||||
path: &Path,
|
||||
import_wait: Duration,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<KotlinDebugServer, KotlinDebugUnavailable> {
|
||||
let server = self
|
||||
.servers_for(&LanguageId::new("kotlin"), path)
|
||||
.into_iter()
|
||||
.find(|s| s.name == KOTLIN_LSP)
|
||||
.ok_or(KotlinDebugUnavailable::NotConfigured)?;
|
||||
self.ensure_started(&server);
|
||||
let ready = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(KotlinDebugUnavailable::StillImporting),
|
||||
ready = server.wait_ready(READY_TIMEOUT) => ready,
|
||||
};
|
||||
if ready.is_none() {
|
||||
let status = server.status();
|
||||
return Err(match status {
|
||||
ServerStatus::Missing => KotlinDebugUnavailable::NotInstalled,
|
||||
ServerStatus::Misconfigured | ServerStatus::Crashed => {
|
||||
KotlinDebugUnavailable::NotStarted(server.status_message().unwrap_or_else(|| format!("{status:?}")))
|
||||
}
|
||||
_ => KotlinDebugUnavailable::NotStarted(format!("{status:?}")),
|
||||
});
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(KotlinDebugUnavailable::StillImporting),
|
||||
imported = tokio::time::timeout(import_wait, wait_for_import(&server, path)) => {
|
||||
imported.unwrap_or(Err(KotlinDebugUnavailable::StillImporting))?
|
||||
}
|
||||
}
|
||||
// The instance that finished importing, also when it replaced the one waited for.
|
||||
let Some(run) = server.running() else {
|
||||
return Err(KotlinDebugUnavailable::NotStarted(format!("{:?}", server.status())));
|
||||
};
|
||||
let params =
|
||||
json!({ "command": "start_debug_server", "arguments": [crate::uri::path_to_uri_string(&server.root)] });
|
||||
let request = run.peer.request::<Value, Value>("workspace/executeCommand", params, Some(cancel.clone()));
|
||||
let port = match tokio::time::timeout(COMMAND_TIMEOUT, request).await {
|
||||
Ok(Ok(port)) => port,
|
||||
Ok(Err(e)) => return Err(KotlinDebugUnavailable::Failed(e.to_string())),
|
||||
Err(_) => {
|
||||
return Err(KotlinDebugUnavailable::Failed(format!(
|
||||
"start_debug_server timed out after {} s",
|
||||
COMMAND_TIMEOUT.as_secs()
|
||||
)));
|
||||
}
|
||||
};
|
||||
match port.as_u64().and_then(|p| u16::try_from(p).ok()).filter(|p| *p != 0) {
|
||||
Some(port) => Ok(KotlinDebugServer { port, root: server.root.clone() }),
|
||||
None => Err(KotlinDebugUnavailable::Failed(format!("unexpected debug server port: {port}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until the current instance reports its import finished and its "Importing" task
|
||||
/// ended, which arrive in either order.
|
||||
async fn wait_for_import(server: &Server, path: &Path) -> Result<(), KotlinDebugUnavailable> {
|
||||
let mut state = server.import_state.subscribe();
|
||||
loop {
|
||||
// Created before the check so a progress end in between still wakes us.
|
||||
let progress_ended = server.phase_notified();
|
||||
let current = state.borrow_and_update().clone();
|
||||
if let Some(current) = current
|
||||
&& current.finished
|
||||
&& !importing(server)
|
||||
{
|
||||
if current.failed.iter().any(|dir| canonical(path).starts_with(canonical(dir))) {
|
||||
return Err(KotlinDebugUnavailable::ImportFailed);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
tokio::select! {
|
||||
_ = state.changed() => {}
|
||||
() = progress_ended => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` with its deepest existing ancestor resolved, so a symlinked root (or `/tmp` vs
|
||||
/// `/private/tmp` on macOS) and the folder URIs kotlin-lsp reports name one directory alike.
|
||||
fn canonical(path: &Path) -> PathBuf {
|
||||
for ancestor in path.ancestors() {
|
||||
if let Ok(real) = dunce::canonicalize(ancestor) {
|
||||
let rest = path.strip_prefix(ancestor).unwrap_or(Path::new(""));
|
||||
return if rest.as_os_str().is_empty() { real } else { real.join(rest) };
|
||||
}
|
||||
}
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{IdeEvent, SharedSink};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn an_instance_that_was_replaced_does_not_record_its_import() {
|
||||
let cfg = toml::from_str("name = \"kotlin-lsp\"\ncommand = \"kotlin-lsp\"").unwrap();
|
||||
let server = Server::new(cfg, PathBuf::from("/p"), LanguageId::new("kotlin"));
|
||||
let finished = json!({ "phase": "FINISHED", "folders": [
|
||||
{ "folderUri": "file:///p/", "status": "SUCCESS" },
|
||||
{ "folderUri": "file:///p/lib/", "status": "FAILED" },
|
||||
]});
|
||||
let old = server.begin_start().unwrap();
|
||||
record_import_state(&server, old, &json!({ "phase": "IN_PROGRESS", "folders": [] }));
|
||||
assert_eq!(*server.import_state.borrow(), Some(ImportState { finished: false, failed: vec![] }));
|
||||
record_import_state(&server, old, &finished);
|
||||
let done = Some(ImportState { finished: true, failed: vec![PathBuf::from("/p/lib")] });
|
||||
assert_eq!(*server.import_state.borrow(), done);
|
||||
|
||||
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
|
||||
server.begin_stop(&sink, false);
|
||||
let new = server.begin_start().unwrap();
|
||||
assert_eq!(*server.import_state.borrow(), None);
|
||||
// The dying instance's FINISHED arrives after the restart.
|
||||
record_import_state(&server, old, &finished);
|
||||
assert_eq!(*server.import_state.borrow(), None);
|
||||
record_import_state(&server, new, &finished);
|
||||
assert_eq!(*server.import_state.borrow(), done);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod handler;
|
||||
mod injections;
|
||||
mod inspect;
|
||||
pub mod jdtls;
|
||||
mod kotlin_lsp;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
@@ -38,6 +39,7 @@ mod vue_navigation;
|
||||
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
|
||||
pub use inspect::{FileInspection, InspectHost, InspectOptions};
|
||||
pub use jdtls::jvm_inspect::JdtJvmInspector;
|
||||
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
|
||||
|
||||
@@ -148,6 +148,8 @@ pub struct Server {
|
||||
/// The instance whose just registered external project is loading, until an open file's
|
||||
/// diagnostics arrive (0: none).
|
||||
pub external_loading: std::sync::atomic::AtomicU64,
|
||||
/// kotlin-lsp's project import as the current instance last reported it.
|
||||
pub(crate) import_state: watch::Sender<Option<crate::kotlin_lsp::ImportState>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
@@ -193,6 +195,7 @@ impl Server {
|
||||
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
|
||||
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
|
||||
external_loading: std::sync::atomic::AtomicU64::new(0),
|
||||
import_state: watch::channel(None).0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,10 +252,20 @@ impl Server {
|
||||
*self.started.lock() = Some(Instant::now());
|
||||
// A crash report quotes only this instance's output, not its predecessors'.
|
||||
self.stderr.lock().clear();
|
||||
self.import_state.send_replace(None);
|
||||
self.phase.send_replace(Phase::Starting);
|
||||
Some(st.generation)
|
||||
}
|
||||
|
||||
/// Publishes instance `generation`'s import state unless a newer start replaced it; checked
|
||||
/// under the state lock so it cannot land after [`Self::begin_start`]'s reset.
|
||||
pub(crate) fn set_import_state(&self, generation: u64, state: crate::kotlin_lsp::ImportState) {
|
||||
let st = self.state.lock();
|
||||
if st.generation == generation {
|
||||
self.import_state.send_replace(Some(state));
|
||||
}
|
||||
}
|
||||
|
||||
/// Starting → Missing/Failed, publishing the status the failed start reports
|
||||
/// before waiters wake: a request that wakes on `Phase::Down` reads the status
|
||||
/// to say why it has no server, and must not still see `Starting`.
|
||||
|
||||
@@ -7,7 +7,7 @@ use ide_core::{
|
||||
use ide_jsonrpc::{Handler, NoopHandler, Peer};
|
||||
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::types::*;
|
||||
use ide_lsp::{LaunchError, Launcher, LspManager};
|
||||
use ide_lsp::{KotlinDebugServer, KotlinDebugUnavailable, LaunchError, Launcher, LspManager};
|
||||
use ide_text::AppliedChange;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
@@ -5990,6 +5990,208 @@ async fn hierarchy_refactorings_name_the_servers_without_them() {
|
||||
assert_eq!(e.message, "plain doesn't support Pull Members Up");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ kotlin-lsp debug server
|
||||
|
||||
type KotlinDebug = Result<KotlinDebugServer, KotlinDebugUnavailable>;
|
||||
|
||||
fn kotlin_lsp_harness() -> (Harness, Arc<MockState>) {
|
||||
let h = harness_for("kotlin", "kt", &[("kotlin-lsp", incremental_caps())], &[]);
|
||||
let s = h.launcher.state("kotlin-lsp");
|
||||
s.respond("workspace/executeCommand", json!(4711));
|
||||
(h, s)
|
||||
}
|
||||
|
||||
fn spawn_kotlin_debug_server(
|
||||
h: &Harness,
|
||||
path: &Path,
|
||||
import_wait: Duration,
|
||||
cancel: &CancellationToken,
|
||||
) -> tokio::task::JoinHandle<KotlinDebug> {
|
||||
let (mgr, path, cancel) = (h.mgr.clone(), path.to_owned(), cancel.clone());
|
||||
tokio::spawn(async move { mgr.kotlin_debug_server(&path, import_wait, &cancel).await })
|
||||
}
|
||||
|
||||
async fn joined(debug: tokio::task::JoinHandle<KotlinDebug>) -> KotlinDebug {
|
||||
tokio::time::timeout(Duration::from_secs(10), debug).await.expect("kotlin_debug_server returned").unwrap()
|
||||
}
|
||||
|
||||
fn import_progress(s: &MockState, value: Value) {
|
||||
s.peer().notify("$/progress", json!({ "token": "import", "value": value })).unwrap();
|
||||
}
|
||||
|
||||
fn import_finished(s: &MockState, folders: &[(&Path, &str)]) {
|
||||
let folders: Vec<Value> = folders
|
||||
.iter()
|
||||
.map(|(dir, status)| json!({ "folderUri": format!("{}/", uri_of(dir)), "tool": "gradle", "status": status }))
|
||||
.collect();
|
||||
s.peer().notify("intellij/workspaceImportState", json!({ "phase": "FINISHED", "folders": folders })).unwrap();
|
||||
}
|
||||
|
||||
fn debug_server_requests(s: &MockState) -> Vec<Value> {
|
||||
s.requested("workspace/executeCommand")
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn waits_for_the_import_before_starting_the_debug_server() {
|
||||
// kotlin-lsp sends the progress end and FINISHED within the same millisecond, in either order.
|
||||
for finished_first in [false, true] {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let main = h.root.join("Main.kt");
|
||||
std::fs::write(&main, "fun main() {}").unwrap();
|
||||
let debug = spawn_kotlin_debug_server(&h, &main, Duration::from_secs(10), &CancellationToken::new());
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
// Repeats every few seconds while the project stays usable: never waited for.
|
||||
s.peer()
|
||||
.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } }))
|
||||
.unwrap();
|
||||
import_progress(&s, json!({ "kind": "begin", "title": "Importing" }));
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Busy).await;
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert!(debug_server_requests(&s).is_empty(), "started while importing");
|
||||
|
||||
if finished_first {
|
||||
import_finished(&s, &[(&h.root, "SUCCESS")]);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(debug_server_requests(&s).is_empty(), "started while the Importing task runs");
|
||||
import_progress(&s, json!({ "kind": "end" }));
|
||||
} else {
|
||||
import_progress(&s, json!({ "kind": "end" }));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(debug_server_requests(&s).is_empty(), "started before FINISHED");
|
||||
import_finished(&s, &[(&h.root, "SUCCESS")]);
|
||||
}
|
||||
|
||||
assert_eq!(joined(debug).await, Ok(KotlinDebugServer { port: 4711, root: h.root.clone() }));
|
||||
assert_eq!(
|
||||
debug_server_requests(&s),
|
||||
vec![json!({ "command": "start_debug_server", "arguments": [uri_of(&h.root)] })],
|
||||
"finished_first: {finished_first}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn still_importing_after_the_wait_is_reported() {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let r = h.mgr.kotlin_debug_server(&h.root, Duration::from_millis(200), &CancellationToken::new()).await;
|
||||
assert_eq!(r, Err(KotlinDebugUnavailable::StillImporting));
|
||||
assert!(debug_server_requests(&s).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelling_the_import_wait_reports_still_importing() {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let cancel = CancellationToken::new();
|
||||
let debug = spawn_kotlin_debug_server(&h, &h.root, Duration::from_secs(60), &cancel);
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(!debug.is_finished());
|
||||
cancel.cancel();
|
||||
assert_eq!(joined(debug).await, Err(KotlinDebugUnavailable::StillImporting));
|
||||
assert!(debug_server_requests(&s).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_import_of_the_module_is_reported() {
|
||||
// Another module that failed does not keep this one from debugging.
|
||||
for other_module_failed in [false, true] {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let main = h.root.join("app/Main.kt");
|
||||
let debug = spawn_kotlin_debug_server(&h, &main, Duration::from_secs(10), &CancellationToken::new());
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
let lib = h.root.join("lib");
|
||||
let (folders, expected) = if other_module_failed {
|
||||
(
|
||||
vec![(h.root.as_path(), "SUCCESS"), (lib.as_path(), "FAILED")],
|
||||
Ok(KotlinDebugServer { port: 4711, root: h.root.clone() }),
|
||||
)
|
||||
} else {
|
||||
(vec![(h.root.as_path(), "FAILED")], Err(KotlinDebugUnavailable::ImportFailed))
|
||||
};
|
||||
import_finished(&s, &folders);
|
||||
assert_eq!(joined(debug).await, expected, "other_module_failed: {other_module_failed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_import_is_reported_through_a_symlinked_root() {
|
||||
// The debugged path names the root through a symlink, the folder URI names its target,
|
||||
// and the file does not exist yet.
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let links = tempfile::tempdir().unwrap();
|
||||
let link = links.path().join("project");
|
||||
std::os::unix::fs::symlink(&h.root, &link).unwrap();
|
||||
let debug =
|
||||
spawn_kotlin_debug_server(&h, &link.join("app/Main.kt"), Duration::from_secs(10), &CancellationToken::new());
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
import_finished(&s, &[(&h.root, "FAILED")]);
|
||||
assert_eq!(joined(debug).await, Err(KotlinDebugUnavailable::ImportFailed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_older_finished_import_does_not_count_after_a_restart() {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
let debug = spawn_kotlin_debug_server(&h, &h.root, Duration::from_secs(10), &CancellationToken::new());
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
import_finished(&s, &[(&h.root, "SUCCESS")]);
|
||||
assert!(joined(debug).await.is_ok());
|
||||
|
||||
let id = h.mgr.servers()[0].id;
|
||||
h.mgr.restart(id).await.unwrap();
|
||||
let r = h.mgr.kotlin_debug_server(&h.root, Duration::from_millis(300), &CancellationToken::new()).await;
|
||||
assert_eq!(r, Err(KotlinDebugUnavailable::StillImporting));
|
||||
assert_eq!(debug_server_requests(&s).len(), 1);
|
||||
|
||||
let debug = spawn_kotlin_debug_server(&h, &h.root, Duration::from_secs(10), &CancellationToken::new());
|
||||
import_finished(&s, &[(&h.root, "SUCCESS")]);
|
||||
assert_eq!(joined(debug).await, Ok(KotlinDebugServer { port: 4711, root: h.root.clone() }));
|
||||
assert_eq!(debug_server_requests(&s).len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn without_kotlin_lsp_the_reason_is_not_configured() {
|
||||
let wait = Duration::from_secs(1);
|
||||
let cancel = CancellationToken::new();
|
||||
let h = harness_for("kotlin", "kt", &[("kotlin-language-server", incremental_caps())], &[]);
|
||||
assert_eq!(h.mgr.kotlin_debug_server(&h.root, wait, &cancel).await, Err(KotlinDebugUnavailable::NotConfigured));
|
||||
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
s.missing.store(true, Ordering::SeqCst);
|
||||
assert_eq!(h.mgr.kotlin_debug_server(&h.root, wait, &cancel).await, Err(KotlinDebugUnavailable::NotInstalled));
|
||||
|
||||
let (h, _) = kotlin_lsp_harness();
|
||||
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.launch_error = Some("needs JDK 21".into())));
|
||||
assert_eq!(
|
||||
h.mgr.kotlin_debug_server(&h.root, wait, &cancel).await,
|
||||
Err(KotlinDebugUnavailable::NotStarted("needs JDK 21".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_debug_server_error_is_reported() {
|
||||
let (h, s) = kotlin_lsp_harness();
|
||||
s.errors.lock().insert("workspace/executeCommand".into(), (-32603, "boom".into()));
|
||||
let debug = spawn_kotlin_debug_server(&h, &h.root, Duration::from_secs(10), &CancellationToken::new());
|
||||
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
|
||||
import_finished(&s, &[(&h.root, "SUCCESS")]);
|
||||
match joined(debug).await {
|
||||
Err(KotlinDebugUnavailable::Failed(m)) => assert!(m.contains("boom"), "{m}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
|
||||
s.errors.lock().clear();
|
||||
for port in [json!(0), json!(65536), json!("4711"), Value::Null] {
|
||||
s.respond("workspace/executeCommand", port.clone());
|
||||
match h.mgr.kotlin_debug_server(&h.root, Duration::from_secs(1), &CancellationToken::new()).await {
|
||||
Err(KotlinDebugUnavailable::Failed(m)) => {
|
||||
assert_eq!(m, format!("unexpected debug server port: {port}"))
|
||||
}
|
||||
other => panic!("{port}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn injected_documents_route_and_resolve_without_exposing_virtual_files() {
|
||||
for encoding in ["utf-16", "utf-8"] {
|
||||
|
||||
@@ -69,7 +69,7 @@ pub struct TransferError {
|
||||
}
|
||||
|
||||
impl TransferReport {
|
||||
fn fail(&mut self, path: impl Into<String>, e: IdeError) {
|
||||
pub(crate) fn fail(&mut self, path: impl Into<String>, e: IdeError) {
|
||||
self.errors.push(TransferError { path: path.into(), message: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +286,70 @@ impl RemoteService {
|
||||
r
|
||||
}
|
||||
|
||||
/// Remote Host › Download to…: `remotes` (folders recursively) into the local folder `dir`,
|
||||
/// each under its own name, without the server path above it. Existing files are replaced.
|
||||
pub async fn download_into(
|
||||
&self,
|
||||
connection: &FsConnection,
|
||||
remotes: &[String],
|
||||
dir: &Path,
|
||||
cancel: &CancellationToken,
|
||||
progress: &mut (dyn FnMut(&str, usize, usize) + Send),
|
||||
) -> IdeResult<TransferReport> {
|
||||
let fs = self.fs(connection).await?;
|
||||
let mut report = TransferReport::default();
|
||||
let mut folders = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
for remote in remotes {
|
||||
let Some(top) = download_target(dir, remote, remote) else {
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
};
|
||||
match fs.stat(remote).await {
|
||||
Ok(Some(e)) if e.is_dir => {
|
||||
folders.push(top);
|
||||
let mut entries = Vec::new();
|
||||
if let Err(e) = remote_tree(&fs, remote, cancel, &mut entries).await {
|
||||
report.fail(remote.clone(), e);
|
||||
}
|
||||
for entry in entries {
|
||||
match download_target(dir, remote, &entry.path) {
|
||||
Some(local) if entry.is_dir => folders.push(local),
|
||||
Some(local) => jobs.push((entry.path, local)),
|
||||
None => report.skipped += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(_)) => jobs.push((remote.clone(), top)),
|
||||
Ok(None) => report.fail(remote.clone(), IdeError::not_found(format!("{remote} does not exist"))),
|
||||
Err(e) => report.fail(remote.clone(), e),
|
||||
}
|
||||
}
|
||||
for folder in &folders {
|
||||
if let Err(e) = tokio::fs::create_dir_all(folder).await {
|
||||
report.fail(folder.display().to_string(), e.into());
|
||||
}
|
||||
}
|
||||
for (i, (remote, local)) in jobs.iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
progress(remote, i, jobs.len());
|
||||
if let Some(parent) = local.parent()
|
||||
&& let Err(e) = tokio::fs::create_dir_all(parent).await
|
||||
{
|
||||
report.fail(remote.clone(), e.into());
|
||||
continue;
|
||||
}
|
||||
match fs.download(remote, local).await {
|
||||
Ok(()) => report.files += 1,
|
||||
Err(e) => report.fail(remote.clone(), e),
|
||||
}
|
||||
}
|
||||
fs.close().await;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
// --- save hook -----------------------------------------------------------------
|
||||
|
||||
/// After a document save: uploads a remote file's copy, or (automatic upload)
|
||||
@@ -497,3 +561,70 @@ fn cache_key(connection: &FsConnection) -> String {
|
||||
FsConnection::Sftp { ssh } => format!("sftp-{ssh}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Files and folders under remote folder `dir` (symlinked folders are not followed).
|
||||
async fn remote_tree(
|
||||
fs: &RemoteFs,
|
||||
dir: &str,
|
||||
cancel: &CancellationToken,
|
||||
out: &mut Vec<RemoteEntry>,
|
||||
) -> IdeResult<()> {
|
||||
for e in fs.list(dir).await? {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let descend = e.is_dir && !e.is_symlink;
|
||||
let path = e.path.clone();
|
||||
out.push(e);
|
||||
if descend {
|
||||
Box::pin(remote_tree(fs, &path, cancel, out)).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where remote `path`, inside the downloaded `selected` file or folder, lands under local `dir`:
|
||||
/// `dir/<name of selected>/<rest>`. `None` for a name that would leave `dir`.
|
||||
fn download_target(dir: &Path, selected: &str, path: &str) -> Option<PathBuf> {
|
||||
let selected = selected.trim_end_matches('/');
|
||||
let name = selected.rsplit('/').next()?;
|
||||
let rest = path.trim_end_matches('/').strip_prefix(selected)?;
|
||||
if !rest.is_empty() && !rest.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let mut local = dir.to_path_buf();
|
||||
for part in std::iter::once(name).chain(rest.split('/').filter(|p| !p.is_empty())) {
|
||||
if matches!(part, "" | "." | "..") || part.contains('\\') || (cfg!(windows) && part.contains(':')) {
|
||||
return None;
|
||||
}
|
||||
local.push(part);
|
||||
}
|
||||
Some(local)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod download_into_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn downloads_keep_only_the_selected_name() {
|
||||
let dir = Path::new("/p/project");
|
||||
let selected = "/home/u/www/site/current/drush";
|
||||
assert_eq!(download_target(dir, selected, selected), Some(dir.join("drush")));
|
||||
assert_eq!(download_target(dir, "/home/u/www/site/current/drush/", selected), Some(dir.join("drush")));
|
||||
assert_eq!(
|
||||
download_target(dir, selected, "/home/u/www/site/current/drush/src/a.php"),
|
||||
Some(dir.join("drush").join("src").join("a.php"))
|
||||
);
|
||||
assert_eq!(download_target(dir, "/srv/app.log", "/srv/app.log"), Some(dir.join("app.log")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_that_would_leave_the_folder_are_refused() {
|
||||
let dir = Path::new("/p/project");
|
||||
assert_eq!(download_target(dir, "/srv/a", "/srv/a/../../etc/passwd"), None);
|
||||
assert_eq!(download_target(dir, "/srv/a", "/srv/ab/x"), None, "a sibling with the same prefix");
|
||||
assert_eq!(download_target(dir, "/", "/etc"), None, "the root has no name");
|
||||
assert_eq!(download_target(dir, "/srv/..", "/srv/.."), None);
|
||||
}
|
||||
}
|
||||
@@ -319,3 +319,37 @@ async fn browser_mappings_resolve_symlinks_and_download_to_the_project() {
|
||||
assert!(report.errors.is_empty());
|
||||
assert_eq!(std::fs::read_to_string(local).unwrap(), "from the server");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_into_copies_only_the_selected_items() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let server = tmp.path().join("srv/www/site/current");
|
||||
let project = tmp.path().join("project");
|
||||
std::fs::create_dir_all(server.join("drush/sub")).unwrap();
|
||||
std::fs::create_dir_all(server.join("drush/empty")).unwrap();
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::write(server.join("drush/a.txt"), "a").unwrap();
|
||||
std::fs::write(server.join("drush/sub/b.txt"), "b").unwrap();
|
||||
std::fs::write(server.join("index.php"), "php").unwrap();
|
||||
std::fs::write(project.join("index.php"), "old").unwrap();
|
||||
let service = service(tmp.path());
|
||||
let remotes = [server.join("drush"), server.join("index.php")].map(|p| p.to_str().unwrap().to_owned());
|
||||
let report = service
|
||||
.download_into(&FsConnection::Local, &remotes, &project, &CancellationToken::new(), &mut |_, _, _| {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(report.files, 3, "{report:?}");
|
||||
assert!(report.errors.is_empty(), "{report:?}");
|
||||
assert_eq!(std::fs::read_to_string(project.join("drush/a.txt")).unwrap(), "a");
|
||||
assert_eq!(std::fs::read_to_string(project.join("drush/sub/b.txt")).unwrap(), "b");
|
||||
assert!(project.join("drush/empty").is_dir());
|
||||
assert_eq!(std::fs::read_to_string(project.join("index.php")).unwrap(), "php");
|
||||
assert!(!project.join("srv").exists() && !project.join("www").exists());
|
||||
|
||||
let missing = [server.join("gone").to_str().unwrap().to_owned()];
|
||||
let report = service
|
||||
.download_into(&FsConnection::Local, &missing, &project, &CancellationToken::new(), &mut |_, _, _| {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((report.files, report.errors.len()), (0, 1), "{report:?}");
|
||||
}
|
||||
+143
-40
@@ -21,7 +21,7 @@ import { activate as activateBuildTools } from "@/features/build-tools";
|
||||
import { useBuild } from "@/features/build-tools/store";
|
||||
import { activate as activateDebugger } from "@/features/debugger";
|
||||
import { addBreakpoint } from "@/features/debugger/breakpoints/store";
|
||||
import { activeSession, evaluate, sessionSupports, useDebug } from "@/features/debugger/state";
|
||||
import { activeSession, evaluate, rootOf, sessionSupports, useDebug } from "@/features/debugger/state";
|
||||
import { activate as activateRun } from "@/features/run";
|
||||
import { resetRuns, useRun } from "@/features/run/store";
|
||||
import { activateWorkbench } from "@/workbench/activate";
|
||||
@@ -33,33 +33,56 @@ interface Case {
|
||||
fixture: string;
|
||||
/** Runs in the project copy first (installs its dependencies). */
|
||||
setup?: (root: string) => void;
|
||||
/** The IDE's tool that debugs it. */
|
||||
debugger: string;
|
||||
/** A system tool that ships with the toolchain (the IDE does not install it). */
|
||||
/** The IDE's tools that debug it, installed unless found. */
|
||||
tools: string[];
|
||||
/** The adapter of the session Debug starts. */
|
||||
adapter: string;
|
||||
/** A system tool that ships with the toolchain (the IDE does not install it): `adapter` is run to check it. */
|
||||
system?: boolean;
|
||||
/** A saved configuration to debug (the debugger is its explicit choice), instead of the file's context. */
|
||||
configId?: string;
|
||||
/** Global settings (key: value) written before the project opens. */
|
||||
settings?: Record<string, unknown>;
|
||||
/** The title of a notification Debug shows. */
|
||||
notice?: string;
|
||||
/** Instances, fields and referrers may answer `timedOut` while the adapter is still busy after a stop. */
|
||||
retryTimedOut?: boolean;
|
||||
/** The entry point, debugged from its context. */
|
||||
file: string;
|
||||
/** A variable of the paused frame. */
|
||||
variable: string;
|
||||
/** Its value once the adapter has filled in a placeholder (`invalidated`), as the Variables pane shows it. */
|
||||
filledValue?: RegExp;
|
||||
/** An expression evaluated there (Evaluate Expression), and its value. */
|
||||
evaluate: [string, RegExp];
|
||||
/** A server: the breakpoint is in this request's handler, and the session is stopped at the end. */
|
||||
request?: string;
|
||||
/** JVM languages: the live instances of a class the paused program holds (Memory tab). */
|
||||
memory?: { className: string; instances: number };
|
||||
/** JVM languages: a class of the heap snapshot captured there and its instance count. */
|
||||
heap?: { className: string; instances: number };
|
||||
/** JVM languages: that class's instances, a field of the first one and its referrers (Show Instances). */
|
||||
instances?: { className: string; count: number; field: string };
|
||||
/** A server: the breakpoint is in this request's handler, and the session is stopped at the end. */
|
||||
request?: string;
|
||||
}
|
||||
|
||||
/** Debugging the Kotlin fixture, with either debugger. */
|
||||
const kotlin = {
|
||||
fixture: "kotlin-gradle",
|
||||
file: "src/main/kotlin/com/example/library/App.kt",
|
||||
variable: "library",
|
||||
evaluate: ["library", /Library/] as [string, RegExp],
|
||||
// Gradle forks the JVM and the debugger attaches to it: the attach-session path.
|
||||
memory: { className: "com.example.library.Book", instances: 3 },
|
||||
heap: { className: "com.example.library.Book", instances: 3 },
|
||||
instances: { className: "com.example.library.Book", count: 3, field: "title" },
|
||||
};
|
||||
|
||||
const CASES: Record<string, Case> = {
|
||||
typescript: {
|
||||
fixture: "ts-app",
|
||||
setup: (root) => execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "js-debug",
|
||||
tools: ["js-debug"],
|
||||
adapter: "js-debug",
|
||||
file: "src/index.ts",
|
||||
variable: "cart",
|
||||
evaluate: ["cart.items.length", /^2$/],
|
||||
@@ -67,21 +90,24 @@ const CASES: Record<string, Case> = {
|
||||
python: {
|
||||
fixture: "python-app",
|
||||
setup: (root) => execFileSync("python3", ["-m", "venv", ".venv"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "debugpy",
|
||||
tools: ["debugpy"],
|
||||
adapter: "debugpy",
|
||||
file: "src/tasks/cli.py",
|
||||
variable: "tasks",
|
||||
evaluate: ["len(tasks.pending())", /^3$/],
|
||||
},
|
||||
rust: {
|
||||
fixture: "rust-app",
|
||||
debugger: "codelldb",
|
||||
tools: ["codelldb"],
|
||||
adapter: "codelldb",
|
||||
file: "src/main.rs",
|
||||
variable: "inventory",
|
||||
evaluate: ["inventory", /\S/],
|
||||
},
|
||||
go: {
|
||||
fixture: "go-app",
|
||||
debugger: "delve",
|
||||
tools: ["delve"],
|
||||
adapter: "delve",
|
||||
file: "cmd/server/main.go",
|
||||
variable: "r",
|
||||
evaluate: ["r.Method", /^"GET"$/],
|
||||
@@ -89,7 +115,8 @@ const CASES: Record<string, Case> = {
|
||||
},
|
||||
java: {
|
||||
fixture: "java-app",
|
||||
debugger: "java-debug",
|
||||
tools: ["java-debug"],
|
||||
adapter: "java-debug",
|
||||
file: "src/main/java/com/example/orders/App.java",
|
||||
variable: "book",
|
||||
evaluate: ["book.size()", /^3$/],
|
||||
@@ -98,22 +125,28 @@ const CASES: Record<string, Case> = {
|
||||
instances: { className: "com.example.orders.OrderBook", count: 1, field: "orders" },
|
||||
},
|
||||
kotlin: {
|
||||
fixture: "kotlin-gradle",
|
||||
debugger: "kotlin-debug-adapter",
|
||||
file: "src/main/kotlin/com/example/library/App.kt",
|
||||
variable: "library",
|
||||
evaluate: ["library", /Library/],
|
||||
// Gradle forks the JVM and the debugger attaches to it: the attach-session path.
|
||||
memory: { className: "com.example.library.Book", instances: 3 },
|
||||
heap: { className: "com.example.library.Book", instances: 3 },
|
||||
instances: { className: "com.example.library.Book", count: 3, field: "title" },
|
||||
...kotlin,
|
||||
tools: ["kotlin-lsp"],
|
||||
adapter: "kotlin-lsp",
|
||||
// kotlin-lsp evaluates for itself after each stop, which the inspector's link waits out.
|
||||
retryTimedOut: true,
|
||||
// First "Collecting data…", then the `toString` kotlin-lsp invokes.
|
||||
filledValue: /Library@/,
|
||||
},
|
||||
"kotlin-fwcd": {
|
||||
...kotlin,
|
||||
tools: ["kotlin-debug-adapter"],
|
||||
adapter: "kotlin-debug-adapter",
|
||||
settings: { languageServers: { "kotlin-lsp": { enabled: false } } },
|
||||
notice: "Debugging Kotlin with kotlin-debug-adapter",
|
||||
},
|
||||
// GDB's own DAP interpreter (GDB 14+), the configuration's explicit debugger choice:
|
||||
// the C/C++ default stays lldb-dap. GDB 15.0.50.20240403-0ubuntu1 says `15`.
|
||||
c: {
|
||||
fixture: "c-app",
|
||||
setup: (root) => execFileSync("make", ["app-c"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "gdb",
|
||||
tools: [],
|
||||
adapter: "gdb",
|
||||
system: true,
|
||||
configId: "user:app-c",
|
||||
file: "src/main.c",
|
||||
@@ -123,7 +156,8 @@ const CASES: Record<string, Case> = {
|
||||
cpp: {
|
||||
fixture: "c-app",
|
||||
setup: (root) => execFileSync("make", ["app-cpp"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "gdb",
|
||||
tools: [],
|
||||
adapter: "gdb",
|
||||
system: true,
|
||||
configId: "user:app-cpp",
|
||||
file: "src/main.cpp",
|
||||
@@ -134,7 +168,8 @@ const CASES: Record<string, Case> = {
|
||||
fixture: "php-app",
|
||||
setup: (root) =>
|
||||
execFileSync("composer", ["install", "--no-interaction", "--no-progress"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "php-debug",
|
||||
tools: ["php-debug"],
|
||||
adapter: "php-debug",
|
||||
file: "bin/quote.php",
|
||||
variable: "$shipment",
|
||||
evaluate: ["count($shipment)", /^3$/],
|
||||
@@ -149,7 +184,15 @@ let base = "";
|
||||
/** Backend events received, for failure messages. */
|
||||
const events: string[] = [];
|
||||
beforeAll(() => {
|
||||
onIdeEvent("*", (e) => events.push(e.type === "debug" ? `debug ${e.session} ${e.event.kind}` : e.type));
|
||||
onIdeEvent("*", (e) =>
|
||||
events.push(
|
||||
e.type === "debug"
|
||||
? `debug ${e.session} ${e.event.kind}`
|
||||
: e.type === "task"
|
||||
? `task ${e.title}${e.done ? " (done)" : ""}`
|
||||
: e.type,
|
||||
),
|
||||
);
|
||||
const disposers = [activateWorkbench(), activateBuildTools(), activateRun(), activateDebugger()];
|
||||
deactivate = () => disposers.reverse().forEach((d) => d());
|
||||
});
|
||||
@@ -171,6 +214,8 @@ async function open(c: Case): Promise<string> {
|
||||
c.setup?.(root);
|
||||
server = await Server.start(join(base, "home"));
|
||||
disconnect = connectDesktop(server);
|
||||
for (const [key, value] of Object.entries(c.settings ?? {}))
|
||||
await call(commands.settingsSet("global", key, JSON.stringify(value)));
|
||||
await openProject(root);
|
||||
const trusted = await commands.projectTrustSet(root, true, false);
|
||||
if (trusted.status !== "ok") throw new Error(trusted.error.message);
|
||||
@@ -190,7 +235,9 @@ async function open(c: Case): Promise<string> {
|
||||
|
||||
async function install(tool: string) {
|
||||
const tools = await call(commands.toolsList());
|
||||
if (tools.find((t) => t.name === tool)?.status === "installed") return;
|
||||
// CI puts its pinned kotlin-lsp on `PATH`: that one is tested, not the latest release.
|
||||
const status = tools.find((t) => t.name === tool)?.status;
|
||||
if (status === "installed" || status === "onPath") return;
|
||||
const channel = new Channel<InstallEvent>();
|
||||
const info = await call(commands.toolsInstall(tool, nextRequestId(), channel));
|
||||
expect(info.status, `${tool} installs`).toBe("installed");
|
||||
@@ -255,12 +302,9 @@ const pausedOrEnded = () => {
|
||||
async function smoke(language: string) {
|
||||
const c = CASES[language]!;
|
||||
const root = await open(c);
|
||||
if (c.system) {
|
||||
// GDB ships with the toolchain (14+ for its DAP interpreter); the IDE does not install it.
|
||||
execFileSync(c.debugger, ["--version"], { stdio: "pipe" });
|
||||
} else {
|
||||
await install(c.debugger);
|
||||
}
|
||||
// GDB ships with the toolchain (14+ for its DAP interpreter); the IDE does not install it.
|
||||
if (c.system) execFileSync(c.adapter, ["--version"], { stdio: "pipe" });
|
||||
for (const tool of c.tools) await install(tool);
|
||||
|
||||
const path = join(root, c.file);
|
||||
const content = readFileSync(path, "utf8");
|
||||
@@ -268,6 +312,8 @@ async function smoke(language: string) {
|
||||
const line = marker + 1;
|
||||
addBreakpoint(path, line);
|
||||
|
||||
const started = Date.now();
|
||||
const begun = events.length;
|
||||
if (c.configId) {
|
||||
const config = (await call(commands.runConfigs())).find((cfg) => cfg.id === c.configId);
|
||||
expect(config, c.configId).toBeTruthy();
|
||||
@@ -277,24 +323,62 @@ async function smoke(language: string) {
|
||||
}
|
||||
if (c.request) void requestWhenListening(c.request);
|
||||
const s = await until("the breakpoint", pausedOrEnded, 5 * 60_000);
|
||||
const firstStop = Date.now() - started;
|
||||
expect(s.stopReason, `${s.stopDescription}\n${shown()}`).toBe("breakpoint");
|
||||
expect(rootOf(s).adapter, shown()).toBe(c.adapter);
|
||||
if (c.notice) {
|
||||
const titles = useNotifications.getState().items.map((n) => n.title);
|
||||
expect(titles, shown()).toContain(c.notice);
|
||||
}
|
||||
const top = s.frames[0]!;
|
||||
expect(top.path).toBe(path);
|
||||
expect(top.line).toBe(line);
|
||||
|
||||
const scopes = await call(commands.debugScopes(s.id, top.id));
|
||||
const locals = await call(commands.debugVariables(s.id, scopes[0]!.variablesReference));
|
||||
let locals = await call(commands.debugVariables(s.id, scopes[0]!.variablesReference));
|
||||
expect(locals.map((v) => v.name)).toContain(c.variable);
|
||||
let filled = "";
|
||||
if (c.filledValue) {
|
||||
const since = Date.now();
|
||||
let epoch: number | null = null;
|
||||
let last = locals.find((v) => v.name === c.variable)?.value;
|
||||
while (!c.filledValue.test(last ?? "")) {
|
||||
if (Date.now() - since > 10_000) throw new Error(`${c.variable} stayed ${JSON.stringify(last)}\n${shown()}`);
|
||||
const now = useDebug.getState().variablesEpoch;
|
||||
if (now === epoch) {
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
continue;
|
||||
}
|
||||
// What the Variables pane does on each `invalidated`: pull the frame's locals again.
|
||||
epoch = now;
|
||||
const again = await call(commands.debugScopes(s.id, top.id));
|
||||
locals = await call(commands.debugVariables(s.id, again.find((sc) => !sc.expensive)!.variablesReference));
|
||||
last = locals.find((v) => v.name === c.variable)?.value;
|
||||
}
|
||||
filled = ` (filled in after ${((Date.now() - since) / 1000).toFixed(1)} s)`;
|
||||
}
|
||||
|
||||
// The value, not kotlin-lsp's "Collecting data…" placeholder.
|
||||
const value = await evaluate(c.evaluate[0], "repl", s);
|
||||
expect(value.value, c.evaluate[0]).toMatch(c.evaluate[1]);
|
||||
if (c.debugger === "gdb") {
|
||||
if (c.adapter === "gdb") {
|
||||
const expression = await evaluate(c.variable, "watch", s);
|
||||
expect(expression.value).toBeTruthy();
|
||||
const environment = await evaluate("environment_ok", "watch", s);
|
||||
expect(environment.value).toBe("1");
|
||||
}
|
||||
|
||||
const filters = (await call(commands.debugExceptionFilters())).find((f) => f.session === rootOf(s).id);
|
||||
const filterIds = filters?.filters.map((f) => f.filter) ?? [];
|
||||
// The JVM debuggers offer caught / uncaught exceptions; Delve offers none.
|
||||
if (c.memory) expect(filterIds, `exception filters of ${c.adapter}`).not.toHaveLength(0);
|
||||
const waits = events.slice(begun).filter((e) => e.startsWith("task Waiting for")).length;
|
||||
console.info(
|
||||
`${language}: ${c.adapter} stopped after ${(firstStop / 1000).toFixed(1)} s (${waits} wait task events); ` +
|
||||
`${c.variable} = ${locals.find((v) => v.name === c.variable)?.value}${filled}; evaluated ${value.value}; ` +
|
||||
`exception filters [${filterIds.join(", ")}]`,
|
||||
);
|
||||
|
||||
if (c.memory) {
|
||||
const memory = await call(commands.debugJvmMemoryClasses(s.id));
|
||||
if (memory.status === "ready") {
|
||||
@@ -364,6 +448,7 @@ async function smoke(language: string) {
|
||||
}
|
||||
}
|
||||
|
||||
let timedOutRetries = 0;
|
||||
if (c.instances) {
|
||||
const { className, count, field } = c.instances;
|
||||
// The inspector comes up beside the session (jdtls bundle, Kotlin JDWP link).
|
||||
@@ -373,24 +458,35 @@ async function smoke(language: string) {
|
||||
if (backend && backend.kind !== "ready") throw new Error(`JVM inspector ${JSON.stringify(backend)}\n${shown()}`);
|
||||
return sessionSupports("jvmInstances", session);
|
||||
});
|
||||
const listed = await call(commands.debugJvmMemoryInstances(s.id, className, 1000));
|
||||
expect(listed.status, `instances: ${JSON.stringify(listed)}\n${shown()}`).toBe("ready");
|
||||
if (listed.status !== "ready") return;
|
||||
type Answer = { status: "ready" } | { status: "unavailable"; reason: { kind: string } };
|
||||
const ready = async <T extends Answer>(what: string, ask: () => Promise<T>) => {
|
||||
let r = await ask();
|
||||
for (let retry = 0; c.retryTimedOut && retry < 5; retry++) {
|
||||
if (r.status !== "unavailable" || r.reason.kind !== "timedOut") break;
|
||||
timedOutRetries++;
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
r = await ask();
|
||||
}
|
||||
expect(r.status, `${what}: ${JSON.stringify(r)}\n${shown()}`).toBe("ready");
|
||||
return r as Extract<T, { status: "ready" }>;
|
||||
};
|
||||
const listed = await ready("instances", () => call(commands.debugJvmMemoryInstances(s.id, className, 1000)));
|
||||
expect(listed.instances, `${className} instances`).toHaveLength(count);
|
||||
const first = listed.instances[0]!;
|
||||
if (!("id" in first)) throw new Error(`${className} instance without an id: ${JSON.stringify(first)}`);
|
||||
const object = { generation: listed.generation, id: first.id };
|
||||
const fields = await call(commands.debugJvmMemoryFields(s.id, object));
|
||||
if (fields.status !== "ready") throw new Error(`fields: ${JSON.stringify(fields)}\n${shown()}`);
|
||||
const fields = await ready("fields", () => call(commands.debugJvmMemoryFields(s.id, object)));
|
||||
const held = fields.fields.find((f) => f.name === field)?.value;
|
||||
if (!held || !("id" in held)) throw new Error(`${className}.${field}: ${JSON.stringify(fields.fields)}`);
|
||||
// Only objects count as referrers, not stack frames: Java's `OrderBook` is held by a local alone.
|
||||
await ready("referrers", () => call(commands.debugJvmMemoryReferrers(s.id, object, 50)));
|
||||
const heldRef = { generation: listed.generation, id: held.id };
|
||||
const referrers = await call(commands.debugJvmMemoryReferrers(s.id, heldRef, 50));
|
||||
if (referrers.status !== "ready") throw new Error(`referrers: ${JSON.stringify(referrers)}\n${shown()}`);
|
||||
const referrers = await ready("referrers", () => call(commands.debugJvmMemoryReferrers(s.id, heldRef, 50)));
|
||||
const back = referrers.referrers.find((r) => "id" in r.value && r.value.id === first.id);
|
||||
expect(back?.via, `referrers of ${className}.${field}: ${JSON.stringify(referrers)}`).toContain(field);
|
||||
}
|
||||
|
||||
const stepped = events.length;
|
||||
// Python 3.12 reports a conditional expression's line twice: Step Over may stop on it
|
||||
// (and its breakpoint) again.
|
||||
for (let step = 0; step < 3 && paused()!.frames[0]!.line === line; step++) {
|
||||
@@ -402,6 +498,13 @@ async function smoke(language: string) {
|
||||
expect(after.stopReason, shown()).toBe("step");
|
||||
expect(after.frames[0]!.line, shown()).toBeGreaterThan(line);
|
||||
|
||||
const invalidated = (from: number, to = events.length) =>
|
||||
events.slice(from, to).filter((e) => e.endsWith(" invalidated")).length;
|
||||
console.info(
|
||||
`${language}: invalidated ${invalidated(begun, stepped)} at the breakpoint, ${invalidated(stepped)} after Step Over; ` +
|
||||
`${timedOutRetries} timedOut retries`,
|
||||
);
|
||||
|
||||
await executeAction("debug.resume");
|
||||
if (c.request) {
|
||||
await until("the request to be served", () => useDebug.getState().sessions[s.id]?.status === "running");
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
//! File › Invalidate Caches… and restarting the IDE.
|
||||
|
||||
use crate::state::AppState;
|
||||
use crate::windows::WindowsState;
|
||||
use ide_core::IdeResult;
|
||||
use ide_host::data_dirs;
|
||||
use ide_workspace::caches::{self, InvalidateCachesOptions};
|
||||
use serde::Serialize;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
|
||||
/// Schedules the invalidation for the next start (`None` cancels a pending one).
|
||||
@@ -26,3 +30,52 @@ pub fn app_restart(app: AppHandle, windows: State<'_, WindowsState>) {
|
||||
windows.set_restart();
|
||||
super::window::app_quit(app, windows);
|
||||
}
|
||||
|
||||
/// Settings › System Settings › Caches: where the local data lives.
|
||||
#[derive(Debug, Clone, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LocalDataInfo {
|
||||
/// The directory in use by this run.
|
||||
pub current: String,
|
||||
/// The OS default (what clearing the custom directory returns to).
|
||||
pub default_dir: String,
|
||||
/// The custom root stored by Settings, if any (`current` is `<root>/<identifier>`).
|
||||
pub custom_root: Option<String>,
|
||||
/// `OPENIDEA_LOCAL_DATA_DIR` is set and wins over everything Settings stores.
|
||||
pub env_override: bool,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn caches_local_data_info(app: AppHandle, state: State<'_, AppState>) -> IdeResult<LocalDataInfo> {
|
||||
let identifier = app.config().identifier.clone();
|
||||
let stringify = |path: PathBuf| path.display().to_string();
|
||||
Ok(LocalDataInfo {
|
||||
current: stringify(state.host.local_data_dir.clone()),
|
||||
default_dir: stringify(data_dirs::default_local_data_dir(&identifier).map_err(ide_core::IdeError::internal)?),
|
||||
custom_root: data_dirs::stored_override(&identifier).map(stringify),
|
||||
env_override: std::env::var_os(data_dirs::LOCAL_DATA_ENV).is_some_and(|v| !v.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stores (`Some`) or clears (`None`, an empty string counts) the custom
|
||||
/// local-data root; with `migrate`, the current tree moves at the next start.
|
||||
/// Returns the directory that takes effect after a restart. The caller
|
||||
/// restarts the IDE (see `app_restart`).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn caches_set_local_data_dir(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
path: Option<String>,
|
||||
migrate: bool,
|
||||
) -> IdeResult<String> {
|
||||
let identifier = app.config().identifier.clone();
|
||||
let current = state.host.local_data_dir.clone();
|
||||
let root = path.filter(|s| !s.trim().is_empty()).map(PathBuf::from);
|
||||
let next = data_dirs::set_override(&identifier, root.as_deref()).map_err(ide_core::IdeError::internal)?;
|
||||
if migrate {
|
||||
data_dirs::schedule_custom_migration(&identifier, ¤t, &next).map_err(ide_core::IdeError::internal)?;
|
||||
}
|
||||
Ok(next.display().to_string())
|
||||
}
|
||||
@@ -128,6 +128,19 @@ pub async fn remote_mkdir(state: State<'_, AppState>, connection: FsConnection,
|
||||
ide_host::ops::deploy::remote_mkdir(&state.host, connection, path).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn remote_download_into(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
connection: FsConnection,
|
||||
paths: Vec<String>,
|
||||
target: IpcPath,
|
||||
request: RequestId,
|
||||
) -> IdeResult<TransferReport> {
|
||||
ide_host::ops::deploy::remote_download_into(window.label(), &state.host, connection, paths, target, request).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn remote_rename(
|
||||
|
||||
@@ -224,6 +224,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
refactor::refactor_undo_file_move,
|
||||
refactor::refactor_can_undo_file_move,
|
||||
caches::caches_schedule_invalidation,
|
||||
caches::caches_local_data_info,
|
||||
caches::caches_set_local_data_dir,
|
||||
caches::app_restart,
|
||||
nav::index_status,
|
||||
nav::index_file_extensions,
|
||||
@@ -683,6 +685,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
deploy::remote_of,
|
||||
deploy::remote_delete,
|
||||
deploy::remote_mkdir,
|
||||
deploy::remote_download_into,
|
||||
deploy::remote_rename,
|
||||
crate::remote_dev::remote_bootstrap_list,
|
||||
crate::remote_dev::remote_connect,
|
||||
|
||||
@@ -90,7 +90,9 @@ pub fn run() {
|
||||
linux_webkit::configure();
|
||||
|
||||
let refresh_shell_path = ide_host::shell_env::inherit_login_shell_path(&context.config().identifier);
|
||||
let local_data_dir = ide_host::data_dirs::local_data_dir(&context.config().identifier);
|
||||
// A custom directory from Settings › System Settings › Caches applies here too
|
||||
// (`OPENIDEA_LOCAL_DATA_DIR` still wins), so tools resolve against the new root.
|
||||
let local_data_dir = ide_host::data_dirs::startup_local_data_dir(&context.config().identifier);
|
||||
// Managed LSP/DAP installs; must run before other threads start and before PATH is cached.
|
||||
match &local_data_dir {
|
||||
Ok(data) => {
|
||||
|
||||
@@ -75,6 +75,11 @@ impl AppState {
|
||||
tracing::info!(?data_dir, ?local_data_dir, "application data directories");
|
||||
// Saved git HTTPS credentials (askpass answers them silently).
|
||||
ide_ssh::git_creds::init(data_dir.join("git-credentials.json"));
|
||||
// A newly chosen local-data directory from Settings › System Settings ›
|
||||
// Caches: the previous tree moves first, so a pending invalidation still
|
||||
// wipes what was just moved.
|
||||
let identifier = app.config().identifier.clone();
|
||||
ide_host::data_dirs::apply_custom_migration(&identifier, &local_data_dir);
|
||||
// File › Invalidate Caches… requested at the last run.
|
||||
let removed = ide_workspace::caches::apply_pending(&data_dir, &local_data_dir);
|
||||
if !removed.is_empty() {
|
||||
|
||||
+27
-1
@@ -406,6 +406,14 @@ export const commands = {
|
||||
/** Build tool sync results (Maven / Gradle) and other per-project caches. */
|
||||
buildCaches?: boolean,
|
||||
} | null) => typedError<null, IdeError>(__TAURI_INVOKE("caches_schedule_invalidation", { options })),
|
||||
cachesLocalDataInfo: () => typedError<LocalDataInfo, IdeError>(__TAURI_INVOKE("caches_local_data_info")),
|
||||
/**
|
||||
* Stores (`Some`) or clears (`None`, an empty string counts) the custom
|
||||
* local-data root; with `migrate`, the current tree moves at the next start.
|
||||
* Returns the directory that takes effect after a restart. The caller
|
||||
* restarts the IDE (see `app_restart`).
|
||||
*/
|
||||
cachesSetLocalDataDir: (path: string | null, migrate: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("caches_set_local_data_dir", { path, migrate })),
|
||||
/** Quits through every window's unsaved-changes check, then starts again. */
|
||||
appRestart: () => __TAURI_INVOKE<void>("app_restart"),
|
||||
indexStatus: () => typedError<IndexStatus, IdeError>(__TAURI_INVOKE("index_status")),
|
||||
@@ -1563,6 +1571,7 @@ export const commands = {
|
||||
remoteOf: (path: IpcPath) => __TAURI_INVOKE<[FsConnection, string] | null>("remote_of", { path }),
|
||||
remoteDelete: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_delete", { connection, path })),
|
||||
remoteMkdir: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_mkdir", { connection, path })),
|
||||
remoteDownloadInto: (connection: FsConnection, paths: string[], target: IpcPath, request: RequestId) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_download_into", { connection, paths, target, request })),
|
||||
remoteRename: (connection: FsConnection, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_rename", { connection, from, to })),
|
||||
/** Browse before connecting, using the desktop's SSH configuration even in a remote window. */
|
||||
remoteBootstrapList: (ssh: string, path: string) => typedError<RemoteEntry[], IdeError>(__TAURI_INVOKE("remote_bootstrap_list", { ssh, path })),
|
||||
@@ -3689,7 +3698,12 @@ export type DebugEvent =
|
||||
*/
|
||||
{ kind: "hotCodeReplace"; changeType: string; message: string } |
|
||||
/** The session's capabilities changed after it started: fetch them again. */
|
||||
{ kind: "capabilities" } | { kind: "jvmBackend"; state: JvmBackendState };
|
||||
{ kind: "capabilities" } |
|
||||
/**
|
||||
* The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`,
|
||||
* `variables`; empty means all) is stale and has to be fetched again.
|
||||
*/
|
||||
{ kind: "invalidated"; areas: string[] } | { kind: "jvmBackend"; state: JvmBackendState };
|
||||
|
||||
/** A debug adapter session. */
|
||||
export type DebugSessionId = number;
|
||||
@@ -6473,6 +6487,18 @@ export type LineMatch = {
|
||||
textOffset: number,
|
||||
};
|
||||
|
||||
/** Settings › System Settings › Caches: where the local data lives. */
|
||||
export type LocalDataInfo = {
|
||||
/** The directory in use by this run. */
|
||||
current: string,
|
||||
/** The OS default (what clearing the custom directory returns to). */
|
||||
defaultDir: string,
|
||||
/** The custom root stored by Settings, if any (`current` is `<root>/<identifier>`). */
|
||||
customRoot: string | null,
|
||||
/** `OPENIDEA_LOCAL_DATA_DIR` is set and wins over everything Settings stores. */
|
||||
envOverride: boolean,
|
||||
};
|
||||
|
||||
/** What a local definition declares (nvim-treesitter `@local.definition.<kind>`). */
|
||||
export type LocalKind = "var" | "parameter" | "function" | "type" | "import" | "macro" | "label" |
|
||||
/** Plain `@local.definition` or a kind without a better mapping. */
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { LaunchConfig } from "@/platform/ipc";
|
||||
import {
|
||||
provideNotificationService,
|
||||
provideToolWindowService,
|
||||
type ToolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import { handleDebugEvent, startSession, useDebug } from "../state";
|
||||
|
||||
const ipc = vi.hoisted(() => ({ debugStart: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
|
||||
const kotlin: LaunchConfig = {
|
||||
name: "AppKt",
|
||||
adapter: "kotlin-debug-adapter",
|
||||
request: "launch",
|
||||
program: null,
|
||||
args: [],
|
||||
cwd: "/p",
|
||||
env: {},
|
||||
extraJson: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
useDebug.setState({ sessions: {}, active: null, console: {} });
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
provideNotificationService({ notify: vi.fn() });
|
||||
provideToolWindowService({ show: vi.fn() } as unknown as ToolWindowService);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("keeps the adapter the backend chose, and the one asked for to start again", async () => {
|
||||
ipc.debugStart.mockImplementation(async () => {
|
||||
handleDebugEvent(7, { kind: "started", name: "AppKt", adapter: "kotlin-lsp", parent: null });
|
||||
return { status: "ok", data: 7 };
|
||||
});
|
||||
expect(await startSession(kotlin)).toBe(7);
|
||||
const session = useDebug.getState().sessions[7]!;
|
||||
expect(session.adapter).toBe("kotlin-lsp");
|
||||
expect(session.launch?.adapter).toBe("kotlin-debug-adapter");
|
||||
});
|
||||
|
||||
it("takes the requested adapter when the backend reported none", async () => {
|
||||
ipc.debugStart.mockResolvedValue({ status: "ok", data: 8 });
|
||||
expect(await startSession(kotlin)).toBe(8);
|
||||
expect(useDebug.getState().sessions[8]!.adapter).toBe("kotlin-debug-adapter");
|
||||
});
|
||||
@@ -50,7 +50,7 @@ function deferred<T>() {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useDebug.setState({ sessions: {}, active: null, stopSeq: 0 });
|
||||
useDebug.setState({ sessions: {}, active: null, stopSeq: 0, variablesEpoch: 0 });
|
||||
useExecutionPoint.setState({ path: null, line: 0, top: true, values: {} });
|
||||
adoptSession(1, { adapter: "java-debug" });
|
||||
ipc.debugStackTrace.mockResolvedValue(ipc.ok([frame(6840)]));
|
||||
@@ -74,6 +74,17 @@ describe("execution point state", () => {
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 });
|
||||
});
|
||||
|
||||
it("counts stops per session", async () => {
|
||||
adoptSession(2, { adapter: "java-debug" });
|
||||
expect(useDebug.getState().sessions[1]!.stops).toBe(0);
|
||||
stopped();
|
||||
stopped();
|
||||
handleDebugEvent(2, { kind: "stopped", threadId: 1, allThreadsStopped: false, reason: "step", description: null });
|
||||
expect(useDebug.getState().sessions[1]!.stops).toBe(2);
|
||||
expect(useDebug.getState().sessions[2]!.stops).toBe(1);
|
||||
await settle();
|
||||
});
|
||||
|
||||
it("clears the old point while a new stack or selected thread is loading", async () => {
|
||||
stopped();
|
||||
await settle();
|
||||
@@ -200,3 +211,54 @@ describe("execution point state", () => {
|
||||
expect(useExecutionPoint.getState().values.count).toBe("42");
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalidated variables", () => {
|
||||
const library = (value: string): Variable => ({
|
||||
name: "library",
|
||||
value,
|
||||
typeName: null,
|
||||
variablesReference: 0,
|
||||
evaluateName: "library",
|
||||
});
|
||||
|
||||
it("reloads the selected frame's variables without counting a stop", async () => {
|
||||
ipc.debugVariables.mockResolvedValue(ipc.ok([library("Collecting data…")]));
|
||||
stopped();
|
||||
await settle();
|
||||
expect(useExecutionPoint.getState().values.library).toBe("Collecting data…");
|
||||
const before = useDebug.getState();
|
||||
ipc.debugVariables.mockResolvedValue(ipc.ok([library("Library@1")]));
|
||||
handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] });
|
||||
await settle();
|
||||
expect(useDebug.getState().variablesEpoch).toBe(1);
|
||||
expect(useExecutionPoint.getState().values.library).toBe("Library@1");
|
||||
// A stop would mark every value changed and make the Memory view ask again.
|
||||
expect(useDebug.getState().stopSeq).toBe(before.stopSeq);
|
||||
expect(useDebug.getState().sessions[1]!.stops).toBe(before.sessions[1]!.stops);
|
||||
});
|
||||
|
||||
it.each([[[]], [["all"]], [["variables", "threads"]]])("reloads for areas %j", async (areas) => {
|
||||
stopped();
|
||||
await settle();
|
||||
ipc.debugScopes.mockClear();
|
||||
handleDebugEvent(1, { kind: "invalidated", areas });
|
||||
await settle();
|
||||
expect(useDebug.getState().variablesEpoch).toBe(1);
|
||||
expect(ipc.debugScopes).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("changes nothing while the program runs or for other areas", async () => {
|
||||
handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] });
|
||||
stopped();
|
||||
await settle();
|
||||
ipc.debugScopes.mockClear();
|
||||
handleDebugEvent(1, { kind: "invalidated", areas: ["threads", "stacks"] });
|
||||
await settle();
|
||||
expect(ipc.debugScopes).not.toHaveBeenCalled();
|
||||
await resumeExecution(1, async () => {});
|
||||
handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] });
|
||||
await settle();
|
||||
expect(ipc.debugScopes).not.toHaveBeenCalled();
|
||||
expect(useDebug.getState().variablesEpoch).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,19 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const adapterData = vi.hoisted(() => ({
|
||||
/** Value of a `library` variable the adapter computes asynchronously; null leaves it out. */
|
||||
library: null as string | null,
|
||||
scopes: vi.fn(),
|
||||
memoryClasses: vi.fn(),
|
||||
/** Value the adapter answers a watch with. */
|
||||
watch: "Collecting data…",
|
||||
}));
|
||||
|
||||
const debugEvaluateIn = vi.hoisted(() =>
|
||||
vi.fn(async () => ({
|
||||
vi.fn(async (..._args: unknown[]) => ({
|
||||
status: "ok" as const,
|
||||
data: { name: "result", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
|
||||
data: { name: "result", value: "4", typeName: "int" as string | null, variablesReference: 0, evaluateName: null },
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -15,11 +24,30 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
debugJvmMemoryClasses: () => ok({ status: "unavailable", reason: { kind: "programExited" } }),
|
||||
debugJvmMemoryClasses: () => {
|
||||
adapterData.memoryClasses();
|
||||
return ok({ status: "unavailable", reason: { kind: "programExited" } });
|
||||
},
|
||||
debugEvaluateIn,
|
||||
debugScopes: () => ok([{ name: "Locals", variablesReference: 1, expensive: false }]),
|
||||
debugSetVariable: () =>
|
||||
ok({ name: "count", value: "4", typeName: "int", variablesReference: 0, evaluateName: "count" }),
|
||||
debugScopes: () => {
|
||||
adapterData.scopes();
|
||||
return ok([{ name: "Locals", variablesReference: 1, expensive: false }]);
|
||||
},
|
||||
debugVariables: () =>
|
||||
ok([
|
||||
...(adapterData.library == null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
name: "library",
|
||||
value: adapterData.library,
|
||||
typeName: "Library",
|
||||
variablesReference: 0,
|
||||
evaluateName: "library",
|
||||
},
|
||||
]),
|
||||
{ name: "count", value: "3", typeName: "int", variablesReference: 0, evaluateName: "count" },
|
||||
{ name: "label", value: "'hi'", typeName: "str", variablesReference: 0, evaluateName: "label" },
|
||||
{
|
||||
@@ -39,7 +67,7 @@ vi.mock("@/workbench/confirmTerminate", () => ({ confirmTerminate }));
|
||||
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { useDebug, type DebugSession } from "../state";
|
||||
import { handleDebugEvent, setVariableValue, useDebug, type DebugSession } from "../state";
|
||||
import { DebugTabs, DebugToolWindow } from "../ui/DebugToolWindow";
|
||||
import { DebuggerOverlays } from "../ui/Overlays";
|
||||
import { useOverlays } from "../ui/popoverStore";
|
||||
@@ -264,3 +292,87 @@ describe("debug tool window", () => {
|
||||
expect(useDebug.getState().sessions).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("variables the adapter computes after the stop", () => {
|
||||
const tick = () => act(() => new Promise((resolve) => setTimeout(resolve, 0)));
|
||||
const setup = () => {
|
||||
adapterData.library = "Collecting data…";
|
||||
adapterData.scopes.mockClear();
|
||||
useDebug.setState({ sessions: { 1: session }, active: 1, stopSeq: 1, variablesEpoch: 0 });
|
||||
return render(<DebugToolWindow />);
|
||||
};
|
||||
|
||||
it("shows the value sent after an invalidation, unmarked as changed", async () => {
|
||||
setup();
|
||||
expect(await screen.findByText("Collecting data…")).toBeTruthy();
|
||||
adapterData.library = "com.example.library.Library@1";
|
||||
act(() => handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] }));
|
||||
const value = await screen.findByText("com.example.library.Library@1");
|
||||
expect(screen.queryByText("Collecting data…")).toBeNull();
|
||||
expect(value.closest("[role=treeitem]")?.querySelector("[class*=changed]")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the watch value the adapter computes after an invalidation", async () => {
|
||||
adapterData.watch = "Collecting data…";
|
||||
const answer = async (...args: unknown[]) => ({
|
||||
status: "ok" as const,
|
||||
data: {
|
||||
name: String(args[2]),
|
||||
value: adapterData.watch,
|
||||
typeName: null as string | null,
|
||||
variablesReference: 0,
|
||||
evaluateName: null,
|
||||
},
|
||||
});
|
||||
debugEvaluateIn.mockImplementation(answer);
|
||||
useDebug.setState({ watches: ['library.search("java").size'] });
|
||||
try {
|
||||
setup();
|
||||
const watch = () => screen.getByText('library.search("java").size').closest("[role=treeitem]")!;
|
||||
await waitFor(() => expect(watch().textContent).toContain("Collecting data…"));
|
||||
adapterData.watch = "1";
|
||||
act(() => handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] }));
|
||||
await waitFor(() => expect(watch().textContent).not.toContain("Collecting data…"));
|
||||
expect(watch().textContent).toContain("1");
|
||||
} finally {
|
||||
debugEvaluateIn.mockImplementation(async () => ({
|
||||
status: "ok" as const,
|
||||
data: { name: "result", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
|
||||
}));
|
||||
useDebug.setState({ watches: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it("reloads after Set Value", async () => {
|
||||
setup();
|
||||
await screen.findByText("Collecting data…");
|
||||
adapterData.library = "Library@2";
|
||||
await act(() => setVariableValue({ container: 1, name: "count", evaluateName: "count" }, "4", session));
|
||||
expect(await screen.findByText("Library@2")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does nothing for an invalidation while the program runs", async () => {
|
||||
setup();
|
||||
await screen.findByText("Collecting data…");
|
||||
act(() => useDebug.setState({ sessions: { 1: { ...session, status: "running" } } }));
|
||||
adapterData.scopes.mockClear();
|
||||
adapterData.library = "Library@3";
|
||||
act(() => handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] }));
|
||||
await tick();
|
||||
expect(adapterData.scopes).not.toHaveBeenCalled();
|
||||
expect(useDebug.getState().variablesEpoch).toBe(0);
|
||||
});
|
||||
|
||||
it("does not ask the Memory view again", async () => {
|
||||
const caps = { jvmMemory: true } as DebugSession["caps"];
|
||||
useDebug.setState({ sessions: { 1: { ...session, caps } }, active: 1, variablesEpoch: 0 });
|
||||
render(<DebugToolWindow />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Memory" }));
|
||||
expect(await screen.findByText("The program has exited.")).toBeTruthy();
|
||||
adapterData.memoryClasses.mockClear();
|
||||
act(() => handleDebugEvent(1, { kind: "invalidated", areas: ["variables"] }));
|
||||
await tick();
|
||||
expect(useDebug.getState().variablesEpoch).toBe(1);
|
||||
expect(adapterData.memoryClasses).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -97,6 +97,11 @@ interface DebugState {
|
||||
watches: string[];
|
||||
/** Incremented on every stop; views re-pull data when it changes. */
|
||||
stopSeq: number;
|
||||
/**
|
||||
* Incremented when the adapter says it has new values for the suspended frame (`invalidated`).
|
||||
* Separate from `stopSeq`: no stop happened, so nothing may count as changed and the Memory view stays put.
|
||||
*/
|
||||
variablesEpoch: number;
|
||||
}
|
||||
|
||||
export const useDebug = create<DebugState>(() => ({
|
||||
@@ -105,6 +110,7 @@ export const useDebug = create<DebugState>(() => ({
|
||||
console: {},
|
||||
watches: [],
|
||||
stopSeq: 0,
|
||||
variablesEpoch: 0,
|
||||
}));
|
||||
|
||||
/** Execution point of the selected frame, plus the frame's locals for inline values. */
|
||||
@@ -1164,6 +1170,12 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
case "jvmBackend":
|
||||
patch(id, { jvmBackend: event.state });
|
||||
break;
|
||||
case "invalidated":
|
||||
if (s.status !== "paused") break;
|
||||
if (event.areas.length && !event.areas.some((a) => a === "variables" || a === "all")) break;
|
||||
useDebug.setState((st) => ({ variablesEpoch: st.variablesEpoch + 1 }));
|
||||
if (s.selectedFrame != null) void loadLocals(id, s.selectedFrame);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1176,7 +1188,7 @@ export function resetSessions() {
|
||||
cancelOutputFlush();
|
||||
ansiStreams.clear();
|
||||
announcedPorts.clear();
|
||||
useDebug.setState({ sessions: {}, active: null, console: {}, stopSeq: 0 });
|
||||
useDebug.setState({ sessions: {}, active: null, console: {}, stopSeq: 0, variablesEpoch: 0 });
|
||||
useExecutionPoint.setState({ path: null, line: 0, top: true, values: {}, variables: {} });
|
||||
publishContext();
|
||||
}
|
||||
|
||||
@@ -403,6 +403,7 @@ interface EvalRow {
|
||||
function VariablesPane({ session }: { session: DebugSession }) {
|
||||
const watches = useDebug((s) => s.watches);
|
||||
const stopSeq = useDebug((s) => s.stopSeq);
|
||||
const variablesEpoch = useDebug((s) => s.variablesEpoch);
|
||||
const [expression, setExpression] = useState("");
|
||||
const evalField = useRef<HTMLInputElement>(null);
|
||||
const completion = useExpressionCompletion(evalField, expression, setExpression, session);
|
||||
@@ -443,9 +444,10 @@ function VariablesPane({ session }: { session: DebugSession }) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [session.id, frame, stopSeq]);
|
||||
}, [session.id, frame, stopSeq, variablesEpoch]);
|
||||
|
||||
// Watches are re-evaluated on every stop / frame change.
|
||||
// Watches are re-evaluated on every stop / frame change, and when the adapter has new values (kotlin-lsp first
|
||||
// answers "Collecting data…").
|
||||
useEffect(() => {
|
||||
if (frame == null || !watches.length) return;
|
||||
let cancelled = false;
|
||||
@@ -466,7 +468,7 @@ function VariablesPane({ session }: { session: DebugSession }) {
|
||||
};
|
||||
// `session` identity changes on every patch; frame/stopSeq capture what matters.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [session.id, frame, stopSeq, watches]);
|
||||
}, [session.id, frame, stopSeq, variablesEpoch, watches]);
|
||||
|
||||
const roots = useMemo<VarRoot[]>(() => {
|
||||
const out: VarRoot[] = [];
|
||||
@@ -583,7 +585,7 @@ function VariablesPane({ session }: { session: DebugSession }) {
|
||||
<VariablesView
|
||||
roots={roots}
|
||||
session={session.id}
|
||||
generation={stopSeq * 100000 + (frame ?? 0)}
|
||||
generation={(stopSeq * 1000 + (variablesEpoch % 1000)) * 100000 + (frame ?? 0)}
|
||||
changes={{ epoch: stopSeq, scope: changeScope }}
|
||||
aria-label="Variables"
|
||||
/>
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
IconButton,
|
||||
Select,
|
||||
Spinner,
|
||||
REMOTE_FILES_DRAG,
|
||||
T,
|
||||
Tree,
|
||||
fileIconName,
|
||||
@@ -20,6 +21,7 @@ import { resolveServer, serverLabel } from "./model";
|
||||
import {
|
||||
copyRemotePath,
|
||||
deleteEntries,
|
||||
downloadTo,
|
||||
downloadToProject,
|
||||
ensureRoot,
|
||||
loadFolder,
|
||||
@@ -87,6 +89,12 @@ export function RemoteHostView() {
|
||||
disabled: !entries.length,
|
||||
run: () => void downloadToProject(server, entries),
|
||||
},
|
||||
{
|
||||
id: "downloadTo",
|
||||
label: "Download to…",
|
||||
disabled: !entries.length,
|
||||
run: () => void downloadTo(server, entries),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
id: "newFolder",
|
||||
@@ -181,6 +189,10 @@ export function RemoteHostView() {
|
||||
speedSearch
|
||||
onActivate={(e) => !e.isDir && void openRemote(server, e)}
|
||||
onContextMenu={(node, selection, e) => showContextMenu(e, menuFor(node, selection))}
|
||||
getDragData={(nodes) => ({
|
||||
type: REMOTE_FILES_DRAG,
|
||||
payload: JSON.stringify({ server: server.id, paths: nodes.map((n) => n.path) }),
|
||||
})}
|
||||
empty={<T>Empty folder</T>}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import { tx, txTemplate, useTxTemplate } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import type { AutoUploadValid, DeploymentServerValid } from "@/platform/remoteSettings";
|
||||
import { deploymentConnection, type AutoUploadValid, type DeploymentServerValid } from "@/platform/remoteSettings";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifications, projectViewSelection, toolWindowService } from "@/workbench/contributions";
|
||||
import { chooseItem } from "@/workbench/inputDialogs";
|
||||
@@ -190,6 +190,21 @@ async function transfer(direction: "upload" | "download", server: DeploymentServ
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads remote files and folders into local folder `target`, each under its own name
|
||||
* (Remote Host › Download to…, or a drag onto the Project view). */
|
||||
export async function downloadRemoteInto(server: DeploymentServerValid, paths: string[], target: string) {
|
||||
if (!paths.length) return;
|
||||
const request = nextRequestId();
|
||||
try {
|
||||
const report = await withSsh(server.kind === "sftp" ? server.sshConfig : "", () =>
|
||||
call(commands.remoteDownloadInto(deploymentConnection(server), paths, target, request)),
|
||||
);
|
||||
showReport(report, "download", server);
|
||||
} catch (e) {
|
||||
showFailure("Cannot download from {server}", server, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads the remote counterparts of `paths` (Remote Host › Download to Project). */
|
||||
export function downloadPaths(server: DeploymentServerValid, paths: string[]) {
|
||||
return transfer("download", server, paths);
|
||||
@@ -433,6 +448,18 @@ export function registerDeploymentActions(): () => void {
|
||||
keywords: ["deploy", "sftp", "upload", "remote"],
|
||||
run: withTargets(async (paths) => transfer("upload", await pickServer("Upload to", paths), paths)),
|
||||
},
|
||||
{
|
||||
id: "deployment.downloadRemoteInto",
|
||||
title: "Download Remote Files Into Folder",
|
||||
category: CATEGORY,
|
||||
hidden: true,
|
||||
description: "Download Remote Host files into a local folder (arg: { server, paths, target })",
|
||||
run: async ({ arg }) => {
|
||||
const a = arg as { server: string; paths: string[]; target: string } | undefined;
|
||||
const server = a && resolveServer(deployment(), a.server);
|
||||
if (server) await downloadRemoteInto(server, a.paths, a.target);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "deployment.downloadFromDefault",
|
||||
title: "Download from Default Server",
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/** Remote Host tool window operations: list, open, create, rename, delete and download remote files. */
|
||||
import { txTemplate } from "@/platform/i18n";
|
||||
import { tx, txTemplate } from "@/platform/i18n";
|
||||
import { call, commands, type RemoteEntry } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { deploymentConnection, type DeploymentServerValid } from "@/platform/remoteSettings";
|
||||
import { copyText } from "@/ui";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { editorService, notifications, projectViewSelection } from "@/workbench/contributions";
|
||||
import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { downloadPaths } from "./actions";
|
||||
import { downloadPaths, downloadRemoteInto } from "./actions";
|
||||
import { joinRemote, localPathForRemote, remoteName, remoteParent } from "./model";
|
||||
import { withSsh } from "./ssh";
|
||||
import { EMPTY_TREE, patchTree, useDeployment } from "./store";
|
||||
@@ -181,4 +181,33 @@ export async function downloadToProject(server: DeploymentServerValid, entries:
|
||||
if (locals.length) await downloadPaths(server, locals);
|
||||
}
|
||||
|
||||
/** Download to…: the entries into a chosen local folder (the Project view's selected folder, or
|
||||
* the project root, preselected), without the server path above them. */
|
||||
export async function downloadTo(server: DeploymentServerValid, entries: RemoteEntry[]) {
|
||||
if (!entries.length) return;
|
||||
const { open } = await import("@/platform/dialog");
|
||||
const target = await open({
|
||||
directory: true,
|
||||
multiple: false,
|
||||
title: tx("Download to"),
|
||||
defaultPath: (await defaultDownloadFolder()) ?? undefined,
|
||||
});
|
||||
if (typeof target !== "string") return;
|
||||
await downloadRemoteInto(
|
||||
server,
|
||||
entries.map((e) => e.path),
|
||||
target,
|
||||
);
|
||||
}
|
||||
|
||||
async function defaultDownloadFolder(): Promise<string | null> {
|
||||
const selected = projectViewSelection()[0];
|
||||
if (selected) {
|
||||
const kind = await call(commands.fsEntryKind(selected)).catch(() => null);
|
||||
if (kind === "dir") return selected;
|
||||
if (kind === "file") return selected.replace(/[\\/][^\\/]*$/, "");
|
||||
}
|
||||
return useProject.getState().project?.root ?? null;
|
||||
}
|
||||
|
||||
export const copyRemotePath = (entry: RemoteEntry) => void copyText(entry.path);
|
||||
@@ -34,10 +34,12 @@ import {
|
||||
} from "@/workbench/contributions";
|
||||
import {
|
||||
FILES_DRAG,
|
||||
REMOTE_FILES_DRAG,
|
||||
HighlightedText,
|
||||
Icon,
|
||||
Popup,
|
||||
dragSession,
|
||||
registerDropTarget,
|
||||
Tree,
|
||||
acquirePopup,
|
||||
fileIconName,
|
||||
@@ -729,6 +731,24 @@ export function ProjectView() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Files and folders dragged from Remote Host download into the folder they are dropped on.
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
return registerDropTarget(el, {
|
||||
accepts: (type) => type === REMOTE_FILES_DRAG,
|
||||
over: (_, x, y) => setDropTarget(folderAt(el, x, y)?.key ?? null),
|
||||
leave: () => setDropTarget(null),
|
||||
drop: (data, x, y) => {
|
||||
setDropTarget(null);
|
||||
const target = folderAt(el, x, y);
|
||||
if (!target) return;
|
||||
const { server, paths } = JSON.parse(data.payload) as { server: string; paths: string[] };
|
||||
void executeAction("deployment.downloadRemoteInto", { server, paths, target: target.path });
|
||||
},
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Reconcile external files and expired Copy/Cut state when returning from another app.
|
||||
useEffect(() => {
|
||||
void refreshOsClipboard();
|
||||
|
||||
@@ -60,7 +60,7 @@ import styles from "./Run.module.css";
|
||||
const ADAPTERS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: "netcoredbg", label: "netcoredbg (.NET)" },
|
||||
{ id: "java-debug", label: "java-debug (Java)" },
|
||||
{ id: "kotlin-debug-adapter", label: "kotlin-debug-adapter (Kotlin)" },
|
||||
{ id: "kotlin-debug-adapter", label: "kotlin-lsp or kotlin-debug-adapter (Kotlin)" },
|
||||
{ id: "debugpy", label: "debugpy (Python)" },
|
||||
{ id: "js-debug", label: "js-debug (Node.js / TypeScript)" },
|
||||
{ id: "delve", label: "Delve (Go)" },
|
||||
|
||||
@@ -10,11 +10,13 @@ import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "rea
|
||||
import clsx from "clsx";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import type { LocalDataInfo } from "@/bindings";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ZOOM_LIMITS } from "@/platform/zoom";
|
||||
import { SCHEMES as EDITOR_SCHEMES, listSchemes, customSchemes } from "@/platform/colorScheme";
|
||||
import { formatTimestamp } from "@/platform/dateFormat";
|
||||
import { Checkbox, IconButton, Input, Popup, type SelectOption, T } from "@/ui";
|
||||
import { Button, Checkbox, IconButton, Input, Popup, type SelectOption, T } from "@/ui";
|
||||
import { NOTIFICATION_GROUPS } from "@/workbench/notificationStore";
|
||||
import { ColorSwatches, FormGroup, NumberInput, Row, SearchLabel, Select, Toggle } from "../components/Form";
|
||||
import { useLabelMatch, useSetting } from "../components/context";
|
||||
@@ -467,6 +469,124 @@ function DefaultDirectoryRow() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings › System Settings › Caches: where tools, language servers, indexes
|
||||
* and caches live (the C: problem of #1722). A custom directory takes effect
|
||||
* after a restart; the previous tree moves along when asked.
|
||||
*/
|
||||
function LocalDataDirRow() {
|
||||
const [info, setInfo] = useState<LocalDataInfo | null>(null);
|
||||
const [root, setRoot] = useState("");
|
||||
const [move, setMove] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const id = useId();
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return;
|
||||
let live = true;
|
||||
void call(commands.cachesLocalDataInfo()).then(
|
||||
(v) => {
|
||||
if (!live) return;
|
||||
setInfo(v);
|
||||
setRoot(v.customRoot ?? "");
|
||||
},
|
||||
() => {},
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
const browse = async () => {
|
||||
const { open } = await import("@/platform/dialog");
|
||||
const picked = await open({
|
||||
directory: true,
|
||||
multiple: false,
|
||||
title: "Local data directory",
|
||||
defaultPath: root || undefined,
|
||||
});
|
||||
const path = Array.isArray(picked) ? picked[0] : picked;
|
||||
if (path) setRoot(path);
|
||||
};
|
||||
const apply = async (next: string | null) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await call(commands.cachesSetLocalDataDir(next, move));
|
||||
await commands.appRestart();
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Could not change the local data directory",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: "app.localDataDir",
|
||||
});
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
if (!isTauri()) {
|
||||
return (
|
||||
<p className={styles.note}>
|
||||
<T>Restart is only available in the desktop app</T>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const locked = busy || info?.envOverride === true;
|
||||
return (
|
||||
<>
|
||||
<Row label="Current location">
|
||||
<Input className={styles.pathInput} value={info?.current ?? ""} readOnly />
|
||||
</Row>
|
||||
<Row
|
||||
label="Custom directory"
|
||||
htmlFor={id}
|
||||
hint="Tools, language servers, indexes and caches live here. Empty means the OS default. Changing it restarts the IDE."
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.pathInput}
|
||||
value={root}
|
||||
placeholder="System default"
|
||||
disabled={locked}
|
||||
onChange={(e) => setRoot(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
aria-label="Browse"
|
||||
disabled={locked}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
</Row>
|
||||
{info?.envOverride === true && (
|
||||
<p role="note" className={styles.note}>
|
||||
<T>The OPENIDEA_LOCAL_DATA_DIR environment variable is set and takes precedence.</T>
|
||||
</p>
|
||||
)}
|
||||
<div className={styles.fontRow}>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="small"
|
||||
disabled={locked}
|
||||
onClick={() => void apply(root.trim() ? root.trim() : null)}
|
||||
>
|
||||
Apply and Restart
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={locked || (!root && !info?.customRoot)}
|
||||
onClick={() => {
|
||||
setRoot("");
|
||||
void apply(null);
|
||||
}}
|
||||
>
|
||||
Reset to default
|
||||
</Button>
|
||||
<Checkbox label="Move existing data to the new location" checked={move} onChange={setMove} disabled={locked} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function IdleSaveRow() {
|
||||
const [on, setOn] = useSetting<boolean>("general.saveOnIdle");
|
||||
const [seconds, setSeconds] = useSetting<number>("general.idleSeconds");
|
||||
@@ -715,6 +835,17 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
{ kind: "custom", label: "Default directory", component: DefaultDirectoryRow },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Caches",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Local data directory",
|
||||
keywords: ["cache", "local data", "data directory", "C盘", "缓存", "目录"],
|
||||
component: LocalDataDirRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Autosave",
|
||||
options: [
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
{
|
||||
"Debugging Kotlin with kotlin-debug-adapter": "Debugging Kotlin with kotlin-debug-adapter",
|
||||
"Waiting for kotlin-lsp to import the project": "Waiting for kotlin-lsp to import the project",
|
||||
"kotlin-lsp is not the Kotlin language server of this project.": "kotlin-lsp is not the Kotlin language server of this project.",
|
||||
"kotlin-lsp is not installed.": "kotlin-lsp is not installed.",
|
||||
"kotlin-lsp did not start: {detail}": "kotlin-lsp did not start: {detail}",
|
||||
"kotlin-lsp is still importing the project. Debug again once the import has finished to use its debugger.": "kotlin-lsp is still importing the project. Debug again once the import has finished to use its debugger.",
|
||||
"kotlin-lsp could not import the project.": "kotlin-lsp could not import the project.",
|
||||
"kotlin-lsp could not start its debugger: {detail}": "kotlin-lsp could not start its debugger: {detail}",
|
||||
"kotlin-lsp or kotlin-debug-adapter (Kotlin)": "kotlin-lsp or kotlin-debug-adapter (Kotlin)",
|
||||
"Black": "Black",
|
||||
"Bright blue": "Bright blue",
|
||||
"Bright cyan": "Bright cyan",
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
{
|
||||
"Debugging Kotlin with kotlin-debug-adapter": "使用 kotlin-debug-adapter 调试 Kotlin",
|
||||
"Waiting for kotlin-lsp to import the project": "正在等待 kotlin-lsp 导入项目",
|
||||
"kotlin-lsp is not the Kotlin language server of this project.": "kotlin-lsp 不是此项目的 Kotlin 语言服务器。",
|
||||
"kotlin-lsp is not installed.": "未安装 kotlin-lsp。",
|
||||
"kotlin-lsp did not start: {detail}": "kotlin-lsp 未能启动:{detail}",
|
||||
"kotlin-lsp is still importing the project. Debug again once the import has finished to use its debugger.": "kotlin-lsp 仍在导入项目。导入完成后再次调试即可使用其调试器。",
|
||||
"kotlin-lsp could not import the project.": "kotlin-lsp 无法导入项目。",
|
||||
"kotlin-lsp could not start its debugger: {detail}": "kotlin-lsp 无法启动其调试器:{detail}",
|
||||
"kotlin-lsp or kotlin-debug-adapter (Kotlin)": "kotlin-lsp 或 kotlin-debug-adapter(Kotlin)",
|
||||
"Black": "黑色",
|
||||
"Bright blue": "亮蓝色",
|
||||
"Bright cyan": "亮青色",
|
||||
@@ -7673,7 +7682,21 @@
|
||||
"Featured": "精选",
|
||||
"All Plugins": "全部插件",
|
||||
"Examples": "示例插件",
|
||||
"Caches": "缓存",
|
||||
"Local data directory": "本地数据目录",
|
||||
"Current location": "当前位置",
|
||||
"Custom directory": "自定义目录",
|
||||
"Tools, language servers, indexes and caches live here. Empty means the OS default. Changing it restarts the IDE.": "工具、语言服务器、索引和缓存存放在此。留空则使用系统默认位置。修改后将重启 IDE。",
|
||||
"The OPENIDEA_LOCAL_DATA_DIR environment variable is set and takes precedence.": "已设置 OPENIDEA_LOCAL_DATA_DIR 环境变量,其优先级更高。",
|
||||
"Apply and Restart": "应用并重启",
|
||||
"Reset to default": "恢复默认",
|
||||
"Move existing data to the new location": "将现有数据移动到新位置",
|
||||
"Could not change the local data directory": "无法更改本地数据目录",
|
||||
"Settings › Tools › SSH Configurations": "设置 › 工具 › SSH 配置",
|
||||
"Edit SSH Configurations": "编辑 SSH 配置",
|
||||
"Docker over SSH uses the system ssh: choose a configuration with OpenSSH config authentication.": "通过 SSH 连接 Docker 使用系统 ssh:请选择认证方式为“OpenSSH 配置和身份验证代理”的 SSH 配置。"
|
||||
"Docker over SSH uses the system ssh: choose a configuration with OpenSSH config authentication.": "通过 SSH 连接 Docker 使用系统 ssh:请选择认证方式为“OpenSSH 配置和身份验证代理”的 SSH 配置。",
|
||||
"Download to…": "下载到…",
|
||||
"Download to": "下载到",
|
||||
"Download Remote Files Into Folder": "将远程文件下载到文件夹",
|
||||
"Download Remote Host files into a local folder (arg: { server, paths, target })": "将远程主机中的文件下载到本地文件夹(参数:{ server, paths, target })"
|
||||
}
|
||||
@@ -161,7 +161,6 @@ const UNTRANSLATED = new Set<string>([
|
||||
"Greenplum",
|
||||
"Java",
|
||||
"java-debug (Java)",
|
||||
"kotlin-debug-adapter (Kotlin)",
|
||||
"js-debug (Node.js / TypeScript)",
|
||||
"JSON",
|
||||
"lldb-dap (C, C++, Swift)",
|
||||
|
||||
+17
-1
@@ -33,6 +33,7 @@ import { T } from "./T";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useGivenTx } from "@/platform/i18n";
|
||||
import { useTreeReorder, type TreeReorder } from "./treeReorder";
|
||||
import { startPointerDrag, type DragData } from "./pointerDrag";
|
||||
import { useTreeDirectoryContext } from "./treeDirectoryContext";
|
||||
import { useIconRowHeight } from "./iconAppearance";
|
||||
|
||||
@@ -129,6 +130,9 @@ export interface TreeProps<T> {
|
||||
horizontalScroll?: boolean;
|
||||
/** Optional display reordering between siblings; the caller owns the order. */
|
||||
reorder?: TreeReorder<T>;
|
||||
/** Rows can be dragged to other components: what dragging `nodes` (the pressed row, or the
|
||||
* selection containing it) carries, or null when they can't be dragged. */
|
||||
getDragData?: (nodes: T[]) => DragData | null;
|
||||
}
|
||||
|
||||
/** Remember intrinsic widths by identity, including rows outside the virtual window. */
|
||||
@@ -737,7 +741,19 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
reordering.drop?.key === row.key && styles[reordering.drop.position],
|
||||
)}
|
||||
style={style}
|
||||
onPointerDown={props.reorder ? (e) => reordering.start(e, row) : undefined}
|
||||
onPointerDown={
|
||||
props.reorder
|
||||
? (e) => reordering.start(e, row)
|
||||
: props.getDragData
|
||||
? (e) => {
|
||||
const nodes = selected.has(row.key)
|
||||
? rows.filter((r) => selected.has(r.key)).map((r) => r.node)
|
||||
: [row.node];
|
||||
const data = props.getDragData!(nodes);
|
||||
if (data) startPointerDrag(e, e.currentTarget, data, { always: true });
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onMouseDown={(e) => onRowMouseDown(e, v.index)}
|
||||
onDoubleClick={(e) => {
|
||||
if (!props.reorder || !reordering.suppressActivation.current) activate(row, e);
|
||||
|
||||
@@ -10,6 +10,7 @@ export * from "./Select";
|
||||
export * from "./Tabs";
|
||||
export {
|
||||
FILES_DRAG,
|
||||
REMOTE_FILES_DRAG,
|
||||
dragRequiresAlt,
|
||||
dragSession,
|
||||
dropZoneAt,
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface DragData {
|
||||
|
||||
/** Project files dragged from the Project view: `payload` is the paths joined by `\n`, folders ending with `/`. */
|
||||
export const FILES_DRAG = "application/x-openidea-files";
|
||||
/** Files and folders dragged from Remote Host: `payload` is JSON `{ server, paths }` (remote paths). */
|
||||
export const REMOTE_FILES_DRAG = "application/x-openidea-remote-files";
|
||||
|
||||
export interface DropTarget {
|
||||
accepts(type: string): boolean;
|
||||
@@ -138,9 +140,14 @@ export function startPointerDrag(
|
||||
e: { button: number; clientX: number; clientY: number; altKey: boolean },
|
||||
source: HTMLElement,
|
||||
data: DragData,
|
||||
opts: { onStart?: () => void; onEnd?: (dragged: boolean, drop?: PointerDrop) => void } = {},
|
||||
opts: {
|
||||
onStart?: () => void;
|
||||
onEnd?: (dragged: boolean, drop?: PointerDrop) => void;
|
||||
/** Not subject to "Drag-and-drop with Alt pressed only" (tabs and stripe buttons). */
|
||||
always?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
if (e.button !== 0 || (requiresAlt() && !e.altKey)) return;
|
||||
if (e.button !== 0 || (!opts.always && requiresAlt() && !e.altKey)) return;
|
||||
const start = { x: e.clientX, y: e.clientY };
|
||||
let ghost: HTMLElement | null = null;
|
||||
const session = dragSession(data);
|
||||
|
||||
Reference in new issue
Заблокувати користувача