дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
92da1a76ff | ||
|
|
e4981055fe | ||
|
|
565ada6b86 |
No files matched your search
@@ -55,8 +55,9 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [typescript, python, rust, go, java, kotlin, php]
|
||||
runs-on: ubuntu-22.04
|
||||
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
|
||||
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
|
||||
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -75,6 +76,12 @@ jobs:
|
||||
- if: matrix.language == 'typescript'
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gdb
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
with: { python-version: "3.12" }
|
||||
|
||||
@@ -103,6 +103,14 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
|
||||
"lldb-dap" => {
|
||||
cfg("lldb-dap", &[], "stdio", "Install LLVM's lldb-dap (brew install llvm; on macOS `xcrun -f lldb-dap`)")
|
||||
}
|
||||
// GDB's own DAP interpreter, stdio transport. The DAP support it needs shipped in GDB 14
|
||||
// (`prepare_gdb` refuses older ones with the required version in the message).
|
||||
"gdb" => cfg(
|
||||
"gdb",
|
||||
&["-i", "dap"],
|
||||
"stdio",
|
||||
"Install GDB 14 or newer (apt install gdb, dnf install gdb, brew install gdb)",
|
||||
),
|
||||
"rdbg" => cfg("rdbg", &["-O", "--port", PORT_PLACEHOLDER, "-c"], "tcp", "gem install debug"),
|
||||
// A jdtls bundle: the session is started through jdtls and reached via `debugServer`.
|
||||
"java-debug" => cfg(
|
||||
@@ -129,6 +137,7 @@ pub fn default_type(adapter: &str) -> Option<&'static str> {
|
||||
"delve" => "go",
|
||||
"netcoredbg" => "coreclr",
|
||||
"lldb-dap" => "lldb-dap",
|
||||
"gdb" => "gdb",
|
||||
"java-debug" => "java",
|
||||
_ => return None,
|
||||
})
|
||||
@@ -335,6 +344,89 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
)))
|
||||
}
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
|
||||
/// `(major, minor)` of the first version number in the output of `gdb --version`
|
||||
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
|
||||
/// (GDB) 15.0.50.20240403-0ubuntu1`). `None` when no standalone version number is there.
|
||||
pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
|
||||
let line = output.lines().next()?;
|
||||
// Distribution names can contain versions, e.g. `(GDB; SUSE Linux Enterprise 15) 14.2`.
|
||||
let line = line.rsplit_once(')').map_or(line, |(_, version)| version);
|
||||
let b = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if !b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let start = i;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
let major: u32 = line[start..i].parse().ok()?;
|
||||
let mut minor = 0;
|
||||
if i + 1 < b.len() && b[i] == b'.' && b[i + 1].is_ascii_digit() {
|
||||
i += 1;
|
||||
let ms = i;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
minor = line[ms..i].parse().unwrap_or(0);
|
||||
}
|
||||
// A version stands alone: `mingw32-gdb13.exe`'s embedded digits are part of a word.
|
||||
if start > 0 && (b[start - 1].is_ascii_alphabetic() || b[start - 1] == b'_') {
|
||||
continue;
|
||||
}
|
||||
return Some((major, minor));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Probe the already resolved and verified executable with its launch environment.
|
||||
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
|
||||
let mut probe = Command::new(binary);
|
||||
if let Some(path) = adapter_path(&spec.env) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.current_dir(&spec.cwd)
|
||||
.envs(spec.env.iter().cloned())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
/// GDB 15 starts the inferior in launch; 14 and 16+ start it at configurationDone.
|
||||
async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
|
||||
let Some((major, minor)) = gdb_version(binary, spec).await? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if major >= GDB_MIN_MAJOR {
|
||||
return Ok(major == 15);
|
||||
}
|
||||
let mut msg = format!(
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)"
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
msg.push_str(". ");
|
||||
msg.push_str(hint);
|
||||
}
|
||||
Err(IdeError::unavailable(msg))
|
||||
}
|
||||
|
||||
/// An adapter that is a plugin of another program (java-debug, a jdtls bundle) rather
|
||||
/// than a program: it has no process of its own and is reached through `debugServer`.
|
||||
pub fn is_plugin_bundle(command: &str) -> bool {
|
||||
@@ -368,6 +460,8 @@ pub type BoxWriter = Box<dyn AsyncWrite + Unpin + Send>;
|
||||
|
||||
/// A connected adapter: byte streams plus the process (if we spawned one).
|
||||
pub struct AdapterIo {
|
||||
/// GDB 15 starts running inside `launch`; configure breakpoints before sending it.
|
||||
pub launch_after_configuration: bool,
|
||||
pub reader: BoxReader,
|
||||
pub writer: BoxWriter,
|
||||
pub child: Option<Child>,
|
||||
@@ -419,6 +513,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
let stream = connect_with_retries(host, port, None, timeout).await?;
|
||||
let (r, w) = stream.into_split();
|
||||
return Ok(AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(r),
|
||||
writer: Box::new(w),
|
||||
child: None,
|
||||
@@ -442,6 +537,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
let _ = stream.set_nodelay(true);
|
||||
let (r, w) = stream.into_split();
|
||||
return Ok(AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(r),
|
||||
writer: Box::new(w),
|
||||
child: None,
|
||||
@@ -470,9 +566,15 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
.ok_or_else(|| missing(&spec))?
|
||||
}
|
||||
};
|
||||
let launch_after_configuration =
|
||||
if spec.adapter == "gdb" && spec.target.is_none() { prepare_gdb(&spec, &binary).await? } else { false };
|
||||
let base_args = substitute_root(&spec.args, &spec.cwd);
|
||||
match spec.transport {
|
||||
Transport::Stdio => spawn_adapter(&spec, &binary, &base_args, None, CONNECT_TIMEOUT).await,
|
||||
Transport::Stdio => {
|
||||
let mut io = spawn_adapter(&spec, &binary, &base_args, None, CONNECT_TIMEOUT).await?;
|
||||
io.launch_after_configuration = launch_after_configuration;
|
||||
Ok(io)
|
||||
}
|
||||
Transport::Tcp => {
|
||||
// An embedded adapter started without `${port}` listens on its usual
|
||||
// address; every other TCP adapter gets a port chosen here so it can be
|
||||
@@ -489,7 +591,10 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
};
|
||||
let args = substitute_port(&base_args, port);
|
||||
match spawn_adapter(&spec, &binary, &args, Some(port), start_timeout).await {
|
||||
Ok(io) => return Ok(io),
|
||||
Ok(mut io) => {
|
||||
io.launch_after_configuration = launch_after_configuration;
|
||||
return Ok(io);
|
||||
}
|
||||
Err(e) => {
|
||||
if fixed.is_none() && attempt < PORT_ATTEMPTS && is_port_race(&e) {
|
||||
tracing::warn!(
|
||||
@@ -552,6 +657,7 @@ async fn spawn_adapter(
|
||||
let stdin = child.stdin.take().ok_or_else(|| IdeError::internal("adapter stdin unavailable"))?;
|
||||
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("adapter stdout unavailable"))?;
|
||||
Ok(AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(stdout),
|
||||
writer: Box::new(stdin),
|
||||
child: Some(child),
|
||||
@@ -583,6 +689,7 @@ async fn spawn_adapter(
|
||||
};
|
||||
let (r, w) = stream.into_split();
|
||||
Ok(AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(r),
|
||||
writer: Box::new(w),
|
||||
child: Some(child),
|
||||
@@ -740,15 +847,102 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn builtins_cover_common_adapters() {
|
||||
for name in ["codelldb", "debugpy", "js-debug", "delve", "netcoredbg", "java-debug"] {
|
||||
for name in ["codelldb", "debugpy", "js-debug", "delve", "netcoredbg", "java-debug", "gdb"] {
|
||||
let cfg = builtin(name).unwrap();
|
||||
assert!(cfg.install_hint.is_some());
|
||||
}
|
||||
let delve = resolve(&builtin("delve").unwrap(), PathBuf::from("/"));
|
||||
assert_eq!(delve.transport, Transport::Tcp);
|
||||
// GDB's own DAP interpreter over stdio, with the required version in its hint.
|
||||
let gdb = builtin("gdb").unwrap();
|
||||
assert_eq!(gdb.command, "gdb");
|
||||
assert_eq!(gdb.args, ["-i", "dap"]);
|
||||
assert_eq!(gdb.transport, "stdio");
|
||||
assert!(gdb.install_hint.as_deref().is_some_and(|h| h.contains("14")), "{gdb:?}");
|
||||
assert_eq!(default_type("gdb"), Some("gdb"));
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
|
||||
#[test]
|
||||
fn parses_gdb_versions() {
|
||||
for (out, want) in [
|
||||
("GNU gdb (GDB) 14.2\nCopyright (C) 2023 Free Software Foundation", Some((14, 2))),
|
||||
("GNU gdb (GDB) 15.0.50.20240403-0ubuntu1\n", Some((15, 0))),
|
||||
("GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1", Some((12, 1))),
|
||||
("GNU gdb (Debian 13.1-3) 13.1", Some((13, 1))),
|
||||
("GNU gdb (GDB) Fedora Linux 16.3-1.fc41", Some((16, 3))),
|
||||
("GNU gdb (GDB; SUSE Linux Enterprise 15) 14.2", Some((14, 2))),
|
||||
("GNU gdb (GDB; SUSE Linux Enterprise 15) 11.1", Some((11, 1))),
|
||||
("mingw32-gdb13.exe (GDB) 13.2", Some((13, 2))),
|
||||
("GNU gdb 14", Some((14, 0))),
|
||||
("no version here", None),
|
||||
("", None),
|
||||
] {
|
||||
assert_eq!(parse_gdb_version(out), want, "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gdb_probe_never_executes_a_changed_pinned_program() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fake = dir.path().join(if cfg!(windows) { "gdb.cmd" } else { "gdb" });
|
||||
std::fs::write(&fake, "approved").unwrap();
|
||||
let pin = ProgramPin::approve(&fake).unwrap();
|
||||
#[cfg(windows)]
|
||||
std::fs::write(&fake, "@echo off\r\necho ran>probe-ran\r\necho GNU gdb (GDB) 15.1\r\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::write(&fake, "#!/bin/sh\ntouch probe-ran\necho 'GNU gdb (GDB) 15.1'\n").unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_owned());
|
||||
spec.command = fake.to_string_lossy().into_owned();
|
||||
spec.pinned = Some(pin);
|
||||
let error = ProcessLauncher.launch(spec, None).await.err().expect("changed program is refused");
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::PermissionDenied);
|
||||
assert!(!dir.path().join("probe-ran").exists(), "the version probe executed an unapproved program");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gdb_probe_uses_the_verified_program_and_launch_environment_once() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fake = dir.path().join(if cfg!(windows) { "gdb.cmd" } else { "gdb" });
|
||||
#[cfg(windows)]
|
||||
std::fs::write(&fake, "@echo off\r\nif \"%~1\"==\"--version\" (\r\n echo probe>>probes\r\n echo GNU gdb ^(GDB^) %GDB_TEST_VERSION%\r\n) else (\r\n echo adapter\r\n)\r\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::write(&fake, "#!/bin/sh\nif [ \"$1\" = --version ]; then\n echo probe >> probes\n echo \"GNU gdb (GDB) $GDB_TEST_VERSION\"\nelse\n echo adapter\nfi\n").unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let pin = ProgramPin::approve(&fake).unwrap();
|
||||
for (version, deferred) in [("12.1", false), ("14.2", false), ("15.1", true), ("16.3", false)] {
|
||||
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_owned());
|
||||
// Only the approved path is executable; the symbolic command must never be probed.
|
||||
spec.command = "definitely-not-a-real-binary-openidea".into();
|
||||
spec.pinned = Some(pin.clone());
|
||||
spec.env.push(("GDB_TEST_VERSION".into(), version.into()));
|
||||
let result = ProcessLauncher.launch(spec, None).await;
|
||||
if version == "12.1" {
|
||||
let error = result.err().expect("GDB 12 has no DAP interpreter");
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("GDB 14 or newer"), "{}", error.message);
|
||||
assert!(error.message.contains("12.1"), "{}", error.message);
|
||||
} else {
|
||||
let mut io = result.unwrap();
|
||||
assert_eq!(io.launch_after_configuration, deferred, "{version}");
|
||||
let mut output = String::new();
|
||||
io.reader.read_to_string(&mut output).await.unwrap();
|
||||
assert_eq!(output.trim(), "adapter");
|
||||
io.child.as_mut().unwrap().wait().await.unwrap();
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("probes")).unwrap().lines().count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_port_is_nonzero() {
|
||||
assert_ne!(free_port().unwrap(), 0);
|
||||
|
||||
@@ -782,6 +782,18 @@ impl DebugManager {
|
||||
if let Some(server) = &debug_server {
|
||||
spec.server_host = server.host.clone();
|
||||
}
|
||||
if config.adapter == "gdb" && config.request == "launch" && debug_server.is_none() {
|
||||
// GDB's DAP env replaces the entire inferior environment. Ordinary run overrides
|
||||
// instead belong on the adapter process, which the inferior inherits. Explicit
|
||||
// launch JSON keeps GDB's replacement semantics.
|
||||
let explicit_env = config.extra_json.as_deref().is_some_and(|extra| {
|
||||
serde_json::from_str::<Value>(extra).is_ok_and(|extra| extra.get("env").is_some())
|
||||
});
|
||||
if !explicit_env {
|
||||
spec.env.extend(config.env.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
arguments.as_object_mut().unwrap().remove("env");
|
||||
}
|
||||
}
|
||||
if let Some(cargo) = arguments.as_object_mut().and_then(|o| o.remove("cargo")) {
|
||||
let cargo_args: Vec<String> = cargo
|
||||
.get("args")
|
||||
@@ -897,6 +909,7 @@ impl DebugManager {
|
||||
e
|
||||
}
|
||||
})?;
|
||||
let launch_after_configuration = io.launch_after_configuration && request == "launch";
|
||||
let stderr = io.stderr.clone();
|
||||
let (conn, incoming) = {
|
||||
let stderr = stderr.clone();
|
||||
@@ -939,7 +952,7 @@ impl DebugManager {
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = self.configure(&session, arguments) => result,
|
||||
result = self.configure(&session, arguments, launch_after_configuration) => result,
|
||||
};
|
||||
match configured {
|
||||
Ok(()) => Ok(id),
|
||||
@@ -980,7 +993,7 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fn configure(&self, s: &Arc<Session>, mut arguments: Value) -> IdeResult<()> {
|
||||
async fn configure(&self, s: &Arc<Session>, mut arguments: Value, launch_in_config: bool) -> IdeResult<()> {
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
let project = arguments
|
||||
.get("projectRoot")
|
||||
@@ -1046,16 +1059,28 @@ impl DebugManager {
|
||||
// Launch/attach may wait for a slow runtime or a remote target. Let the adapter report
|
||||
// failure; Stop cancels configuration and a closed connection fails the pending reply.
|
||||
// Many adapters answer only after `configurationDone`, so don't wait for the reply yet.
|
||||
let launch = s.conn.send_request(request, arguments)?;
|
||||
let mut launch = Box::pin(async move { launch.await.unwrap_or(Err(DapError::Closed)) });
|
||||
// GDB 15 is the exception: its `launch` starts the program itself (14 runs at
|
||||
// `configurationDone`, 16+ defers the launch there), so its launch waits below.
|
||||
let mut launch = if launch_in_config {
|
||||
None
|
||||
} else {
|
||||
let reply = s.conn.send_request(request, arguments.clone())?;
|
||||
Some(Box::pin(async move { reply.await.unwrap_or(Err(DapError::Closed)) }))
|
||||
};
|
||||
let mut initialized = s.initialized.subscribe();
|
||||
let mut launch_result = None;
|
||||
let got_initialized = tokio::select! {
|
||||
r = initialized.wait_for(|v| *v) => { r.map_err(|_| DapError::Closed)?; true }
|
||||
r = &mut launch => {
|
||||
r?;
|
||||
launch_result = Some(());
|
||||
false
|
||||
let got_initialized = match launch.as_mut() {
|
||||
Some(launch) => tokio::select! {
|
||||
r = initialized.wait_for(|v| *v) => { r.map_err(|_| DapError::Closed)?; true }
|
||||
r = launch => {
|
||||
r?;
|
||||
launch_result = Some(());
|
||||
false
|
||||
}
|
||||
},
|
||||
None => {
|
||||
initialized.wait_for(|v| *v).await.map_err(|_| DapError::Closed)?;
|
||||
true
|
||||
}
|
||||
};
|
||||
if !got_initialized {
|
||||
@@ -1113,8 +1138,17 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
s.configured.store(true, Ordering::Release);
|
||||
if launch_result.is_none() {
|
||||
launch.await?;
|
||||
match launch.as_mut() {
|
||||
Some(launch) => {
|
||||
if launch_result.is_none() {
|
||||
launch.await?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// GDB 15: the breakpoints are in, so its `run` cannot miss them.
|
||||
let reply = s.conn.send_request(request, arguments)?;
|
||||
reply.await.unwrap_or(Err(DapError::Closed))?;
|
||||
}
|
||||
}
|
||||
if let Some(relay) = s.kotlin_relay.lock().as_mut() {
|
||||
relay.release();
|
||||
|
||||
@@ -126,6 +126,10 @@ struct Script {
|
||||
pending_startup: Option<bool>,
|
||||
startup_error: Option<&'static str>,
|
||||
close_during_startup: bool,
|
||||
/// GDB 15 semantics: `initialized` right after `initialize`, the program starts at
|
||||
/// `launch`, and a `configurationDone` sent while it runs is refused with `notStopped`.
|
||||
gdb15_starts_at_launch: bool,
|
||||
launch_after_configuration: bool,
|
||||
}
|
||||
|
||||
impl Default for Script {
|
||||
@@ -145,6 +149,8 @@ impl Default for Script {
|
||||
pending_startup: None,
|
||||
startup_error: None,
|
||||
close_during_startup: false,
|
||||
gdb15_starts_at_launch: false,
|
||||
launch_after_configuration: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,10 +165,12 @@ impl AdapterLauncher for FakeLauncher {
|
||||
let (client, server) = tokio::io::duplex(1 << 16);
|
||||
let log = self.log.clone();
|
||||
let script = self.script.clone();
|
||||
let launch_after_configuration = script.launch_after_configuration;
|
||||
tokio::spawn(fake_adapter(server, log, script));
|
||||
let (r, w) = tokio::io::split(client);
|
||||
Box::pin(async move {
|
||||
Ok(AdapterIo {
|
||||
launch_after_configuration,
|
||||
reader: Box::new(r),
|
||||
writer: Box::new(w),
|
||||
child: None,
|
||||
@@ -180,6 +188,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 running = false;
|
||||
macro_rules! send {
|
||||
($v:expr) => {{
|
||||
let mut v: Value = $v;
|
||||
@@ -200,24 +209,37 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
continue;
|
||||
}
|
||||
match msg["command"].as_str().unwrap_or_default() {
|
||||
"initialize" => ok!(
|
||||
msg,
|
||||
json!({
|
||||
"supportsConfigurationDoneRequest": true,
|
||||
"supportsCompletionsRequest": true,
|
||||
"supportsTerminateRequest": script.supports_terminate,
|
||||
"supportsSetVariable": true,
|
||||
"supportsFunctionBreakpoints": true,
|
||||
"supportsDataBreakpoints": true,
|
||||
"supportsStepInTargetsRequest": true,
|
||||
"supportsRestartFrame": true,
|
||||
"exceptionBreakpointFilters": [
|
||||
{"filter": "raised", "label": "Raised"},
|
||||
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
|
||||
],
|
||||
})
|
||||
),
|
||||
"initialize" => {
|
||||
ok!(
|
||||
msg,
|
||||
json!({
|
||||
"supportsConfigurationDoneRequest": true,
|
||||
"supportsCompletionsRequest": true,
|
||||
"supportsTerminateRequest": script.supports_terminate,
|
||||
"supportsSetVariable": true,
|
||||
"supportsFunctionBreakpoints": true,
|
||||
"supportsDataBreakpoints": true,
|
||||
"supportsStepInTargetsRequest": true,
|
||||
"supportsRestartFrame": true,
|
||||
"exceptionBreakpointFilters": [
|
||||
{"filter": "raised", "label": "Raised"},
|
||||
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
|
||||
],
|
||||
})
|
||||
);
|
||||
if script.gdb15_starts_at_launch {
|
||||
// GDB 15 announces itself before it sees `launch` (which a client that
|
||||
// defers it sends late).
|
||||
send!(json!({"type": "event", "event": "initialized"}));
|
||||
}
|
||||
}
|
||||
"launch" | "attach" => {
|
||||
if script.gdb15_starts_at_launch {
|
||||
// GDB 15 starts the program here and answers `launch` right away.
|
||||
running = true;
|
||||
ok!(msg, Value::Null);
|
||||
continue;
|
||||
}
|
||||
if script.close_during_startup {
|
||||
return;
|
||||
}
|
||||
@@ -289,6 +311,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"value": format!("{}!", msg["arguments"]["value"].as_str().unwrap()), "type": "int"}))
|
||||
}
|
||||
"configurationDone" => {
|
||||
if script.gdb15_starts_at_launch && running {
|
||||
// GDB 15 answers `configurationDone` with `notStopped` while the program
|
||||
// it started at `launch` is still running.
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "configurationDone", "success": false, "message": "notStopped"})
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if !script.ignore_configuration_done {
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
@@ -510,6 +540,60 @@ async fn stop_cancels_pending_launch_and_attach() {
|
||||
}
|
||||
}
|
||||
|
||||
/// GDB 15 must receive breakpoints and configurationDone before launch.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn gdb_15_launch_waits_for_the_configuration() {
|
||||
for deferred in [false, true] {
|
||||
let h =
|
||||
harness(Script { gdb15_starts_at_launch: true, launch_after_configuration: deferred, ..Script::default() });
|
||||
let result = h.start(LaunchConfig { adapter: "gdb".into(), ..config() }).await;
|
||||
if deferred {
|
||||
let id = result.expect("GDB 15 defers its launch past the configuration");
|
||||
let commands = h.commands();
|
||||
let pos = |c: &str| commands.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("launch") > pos("configurationDone"), "{commands:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
assert!(error.message.contains("configurationDone failed: notStopped"), "{}", error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn gdb_attach_keeps_the_normal_configuration_order() {
|
||||
let h = harness(Script { launch_after_configuration: true, ..Script::default() });
|
||||
let id = h.start(LaunchConfig { adapter: "gdb".into(), request: "attach".into(), ..config() }).await.unwrap();
|
||||
let commands = h.commands();
|
||||
let pos = |c: &str| commands.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("attach") < pos("configurationDone"), "{commands:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn gdb_run_environment_overrides_preserve_inheritance() {
|
||||
for explicit in [None, Some(r#"{"env":{"ONLY":"explicit"}}"#)] {
|
||||
let h = harness(Script::default());
|
||||
let id = h
|
||||
.start(LaunchConfig { adapter: "gdb".into(), extra_json: explicit.map(str::to_owned), ..config() })
|
||||
.await
|
||||
.unwrap();
|
||||
let session = h.manager.session(id).unwrap();
|
||||
{
|
||||
let log = h.log.lock();
|
||||
let args = &log.iter().find(|m| m["command"] == "launch").unwrap()["arguments"];
|
||||
if explicit.is_some() {
|
||||
assert_eq!(args["env"], json!({"ONLY": "explicit"}));
|
||||
assert!(session.spec.env.is_empty());
|
||||
} else {
|
||||
assert!(args.get("env").is_none(), "GDB must inherit its process environment");
|
||||
assert!(session.spec.env.contains(&("A".into(), "1".into())));
|
||||
}
|
||||
}
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn startup_still_reports_adapter_failure_and_connection_closure() {
|
||||
for request in ["launch", "attach"] {
|
||||
@@ -517,7 +601,6 @@ async fn startup_still_reports_adapter_failure_and_connection_closure() {
|
||||
let error = h.start(LaunchConfig { request: request.into(), ..config() }).await.unwrap_err();
|
||||
assert_eq!(error.message, format!("{request} failed: interpreter could not start"));
|
||||
assert!(h.manager.sessions(None).is_empty());
|
||||
|
||||
let h = harness(Script { close_during_startup: true, ..Script::default() });
|
||||
let error = h.start(LaunchConfig { request: request.into(), ..config() }).await.unwrap_err();
|
||||
assert!(error.message.contains("debug adapter `debugpy` exited during startup"), "{error}");
|
||||
@@ -1962,6 +2045,7 @@ async fn rdbg_drains_test_output_after_dap_closes_before_killing_the_process() {
|
||||
});
|
||||
let (reader, writer) = tokio::io::split(client);
|
||||
Ok(AdapterIo {
|
||||
launch_after_configuration: false,
|
||||
reader: Box::new(reader),
|
||||
writer: Box::new(writer),
|
||||
child: Some(child),
|
||||
|
||||
@@ -151,6 +151,16 @@ fn cases(dir: &Path) -> Vec<Case> {
|
||||
field: None,
|
||||
config: launch("lldb-dap", &c.join("main"), &c, serde_json::json!({"env": ["OPENIDEA_FIXTURE=1"]})),
|
||||
},
|
||||
// GDB's own DAP interpreter needs GDB 14+; older ones are skipped by `installed`.
|
||||
Case {
|
||||
adapter: "gdb",
|
||||
source: c.join("main.c"),
|
||||
loop_line: 13,
|
||||
after_loop: 15,
|
||||
function: "parse",
|
||||
field: None,
|
||||
config: launch("gdb", &c.join("main"), &c, serde_json::json!({})),
|
||||
},
|
||||
]);
|
||||
out
|
||||
}
|
||||
@@ -230,6 +240,16 @@ fn installed(adapter: &str) -> bool {
|
||||
"js-debug" => "js-debug-adapter",
|
||||
"delve" => "dlv",
|
||||
"java-debug" => return true,
|
||||
// Only a GDB with the DAP interpreter (14+) counts as installed.
|
||||
"gdb" => {
|
||||
return std::process::Command::new("gdb").arg("--version").output().is_ok_and(|out| {
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(adapter::parse_gdb_version)
|
||||
.is_some_and(|(major, _)| major >= 14)
|
||||
});
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
adapter::resolve_binary(cmd, Path::new("/")).is_some()
|
||||
|
||||
@@ -13,6 +13,7 @@ something to show.
|
||||
| `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` |
|
||||
| `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` |
|
||||
| `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` |
|
||||
| `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — |
|
||||
| `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` |
|
||||
| `polyglot/` | Go, TS, Python, C, shell, SQL, TOML/YAML/JSON, proto, Terraform | `make` | `make test` | — | unused variable in `native/hash.c` |
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Debugging the entry points with GDB, picked in the configuration's Debug adapter
|
||||
# control (explicit choice: the C/C++ default stays lldb-dap). GDB 14+ has the
|
||||
# DAP interpreter; `make all` builds `bin/` first.
|
||||
|
||||
[[configurations]]
|
||||
id = "user:app-c"
|
||||
name = "app-c (GDB)"
|
||||
kind = "shell"
|
||||
command = "bin/app-c"
|
||||
debug-adapter = "gdb"
|
||||
env = { OPENIDEA_GDB_FIXTURE = "present" }
|
||||
|
||||
[[configurations]]
|
||||
id = "user:app-cpp"
|
||||
name = "app-cpp (GDB)"
|
||||
kind = "shell"
|
||||
command = "bin/app-cpp"
|
||||
debug-adapter = "gdb"
|
||||
env = { OPENIDEA_GDB_FIXTURE = "present" }
|
||||
@@ -0,0 +1,18 @@
|
||||
CFLAGS = -g -O0 -std=c11
|
||||
CXXFLAGS = -g -O0 -std=c++17
|
||||
|
||||
.PHONY: all app-c app-cpp clean
|
||||
|
||||
all: app-c app-cpp
|
||||
|
||||
app-c: bin
|
||||
$(CC) $(CFLAGS) -o bin/app-c src/main.c
|
||||
|
||||
app-cpp: bin
|
||||
$(CXX) $(CXXFLAGS) -o bin/app-cpp src/main.cpp
|
||||
|
||||
bin:
|
||||
mkdir -p bin
|
||||
|
||||
clean:
|
||||
rm -rf bin
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* FNV-1a 64-bit, one byte at a time: enough of a call stack to inspect. */
|
||||
static uint64_t mix(uint64_t h, unsigned char byte) {
|
||||
h ^= byte;
|
||||
h *= 1099511628211ULL;
|
||||
return h;
|
||||
}
|
||||
|
||||
static uint64_t hash(uint64_t h, const char *s) {
|
||||
for (; *s; s++) {
|
||||
h = mix(h, (unsigned char)*s);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const char *fixture = getenv("OPENIDEA_GDB_FIXTURE");
|
||||
int environment_ok = getenv("PATH") != NULL && fixture != NULL && strcmp(fixture, "present") == 0;
|
||||
const char *words[] = {"openidea", "gdb", "dap"};
|
||||
uint64_t hashes[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
hashes[i] = hash(1469598103934665603ULL, words[i]);
|
||||
}
|
||||
uint64_t value = hashes[0];
|
||||
// Set a breakpoint here (QA: debugger) and inspect `value`.
|
||||
value = hash(1469598103934665603ULL, words[2]);
|
||||
printf("%s %016llx\n", words[2], (unsigned long long)value);
|
||||
return environment_ok ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::string banner(const std::string &project, int n) {
|
||||
return project + " #" + std::to_string(n);
|
||||
}
|
||||
|
||||
int main() {
|
||||
const char *fixture = std::getenv("OPENIDEA_GDB_FIXTURE");
|
||||
int environment_ok = std::getenv("PATH") != nullptr && fixture != nullptr && std::strcmp(fixture, "present") == 0;
|
||||
std::vector<std::string> log;
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
log.push_back(banner("openidea", i));
|
||||
}
|
||||
std::string line;
|
||||
// Set a breakpoint here (QA: debugger) and inspect `line`.
|
||||
line = banner("openidea", 3);
|
||||
std::cout << line << "\n";
|
||||
return environment_ok ? 0 : 1;
|
||||
}
|
||||
+2
-3
@@ -17,9 +17,8 @@ const config: KnipConfig = {
|
||||
// Plugins' web pages are projects of their own (own package.json, checked by plugins/build.sh and CI).
|
||||
ignore: ["plugins/**/web-src/**"],
|
||||
ignoreExportsUsedInFile: true,
|
||||
// lint-staged formats Rust files with the toolchain's rustfmt; the PHP smoke tests install
|
||||
// their fixture with Composer.
|
||||
ignoreBinaries: ["rustfmt", "composer"],
|
||||
// System tools used by formatting and language smoke fixtures.
|
||||
ignoreBinaries: ["rustfmt", "composer", "make"],
|
||||
compilers: {
|
||||
// Fonts come in through `@import` in global.css.
|
||||
css: (text: string) => [...text.matchAll(/(?<=@)import[^;]+/g)].join("\n"),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
/**
|
||||
* Debugging each language's `fixtures/` project the way the editor does: a breakpoint on the
|
||||
* entry point's "Set a breakpoint here" line, Debug from the file's context, then the paused
|
||||
* frame, its variables, evaluation, Step Over and Resume, with the debugger the IDE installs.
|
||||
* entry point's "Set a breakpoint here" line, Debug from the file's context (or a saved
|
||||
* configuration, when the debugger is an explicit choice), then the paused frame, its
|
||||
* variables, evaluation, Step Over and Resume, with the debugger the IDE installs (GDB:
|
||||
* the toolchain's own, 14+ for its DAP interpreter).
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cpSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
||||
@@ -33,6 +35,10 @@ interface Case {
|
||||
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). */
|
||||
system?: boolean;
|
||||
/** A saved configuration to debug (the debugger is its explicit choice), instead of the file's context. */
|
||||
configId?: string;
|
||||
/** The entry point, debugged from its context. */
|
||||
file: string;
|
||||
/** A variable of the paused frame. */
|
||||
@@ -89,6 +95,28 @@ const CASES: Record<string, Case> = {
|
||||
variable: "library",
|
||||
evaluate: ["library", /Library/],
|
||||
},
|
||||
// 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",
|
||||
system: true,
|
||||
configId: "user:app-c",
|
||||
file: "src/main.c",
|
||||
variable: "value",
|
||||
evaluate: ["print value", / = [0-9]/],
|
||||
},
|
||||
cpp: {
|
||||
fixture: "c-app",
|
||||
setup: (root) => execFileSync("make", ["app-cpp"], { cwd: root, stdio: "ignore" }),
|
||||
debugger: "gdb",
|
||||
system: true,
|
||||
configId: "user:app-cpp",
|
||||
file: "src/main.cpp",
|
||||
variable: "line",
|
||||
evaluate: ["print line", / = /],
|
||||
},
|
||||
php: {
|
||||
fixture: "php-app",
|
||||
setup: (root) =>
|
||||
@@ -214,7 +242,12 @@ const pausedOrEnded = () => {
|
||||
async function smoke(language: string) {
|
||||
const c = CASES[language]!;
|
||||
const root = await open(c);
|
||||
await install(c.debugger);
|
||||
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);
|
||||
}
|
||||
|
||||
const path = join(root, c.file);
|
||||
const content = readFileSync(path, "utf8");
|
||||
@@ -222,7 +255,13 @@ async function smoke(language: string) {
|
||||
const line = marker + 1;
|
||||
addBreakpoint(path, line);
|
||||
|
||||
await executeAction("run.debugContext", { path, content });
|
||||
if (c.configId) {
|
||||
const config = (await call(commands.runConfigs())).find((cfg) => cfg.id === c.configId);
|
||||
expect(config, c.configId).toBeTruthy();
|
||||
await executeAction("debug.startConfig", config);
|
||||
} else {
|
||||
await executeAction("run.debugContext", { path, content });
|
||||
}
|
||||
if (c.request) void requestWhenListening(c.request);
|
||||
const s = await until("the breakpoint", pausedOrEnded, 5 * 60_000);
|
||||
expect(s.stopReason, `${s.stopDescription}\n${shown()}`).toBe("breakpoint");
|
||||
@@ -236,6 +275,12 @@ async function smoke(language: string) {
|
||||
|
||||
const value = await evaluate(c.evaluate[0], "repl", s);
|
||||
expect(value.value, c.evaluate[0]).toMatch(c.evaluate[1]);
|
||||
if (c.debugger === "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");
|
||||
}
|
||||
|
||||
// Python 3.12 reports a conditional expression's line twice: Step Over may stop on it
|
||||
// (and its breakpoint) again.
|
||||
|
||||
@@ -324,6 +324,30 @@ describe("build feature", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes Build Artifacts to the active file's module, or the whole project without one", async () => {
|
||||
provideEditorService({
|
||||
openFile,
|
||||
saveAll: () => Promise.resolve(),
|
||||
activePath: () => "/p/core/src/A.java",
|
||||
} as unknown as EditorService);
|
||||
await executeAction("build.buildArtifacts", { activate: false });
|
||||
expect(fake.calls.at(-1)).toMatchObject({ kind: "artifacts", file: "/p/core/src/A.java" });
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
});
|
||||
|
||||
provideEditorService({
|
||||
openFile,
|
||||
saveAll: () => Promise.resolve(),
|
||||
activePath: () => null,
|
||||
} as unknown as EditorService);
|
||||
await executeAction("build.buildArtifacts", { activate: false });
|
||||
expect(fake.calls.at(-1)).toMatchObject({ kind: "artifacts", file: null });
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a build without a workbench", async () => {
|
||||
show.mockImplementation(() => {
|
||||
throw new Error("No workbench");
|
||||
|
||||
@@ -102,14 +102,14 @@ export function activate(): () => void {
|
||||
{
|
||||
id: "build.buildArtifacts",
|
||||
title: "Build Artifacts",
|
||||
description: "Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
description: "Packages the current module's artifacts, or the whole project when no file is active",
|
||||
category: "Build",
|
||||
when: WHEN,
|
||||
keywords: ["package", "assemble", "jar", "release"],
|
||||
keywords: ["package", "assemble", "jar", "release", "module"],
|
||||
run: ({ arg }) => {
|
||||
const options = typeof arg === "object" && arg !== null ? arg : {};
|
||||
const activate = !("activate" in options && options.activate === false);
|
||||
const build = startBuild("artifacts", null, activate);
|
||||
const build = startBuild("artifacts", moduleTarget(arg), activate);
|
||||
if ("wait" in options && options.wait === true) return build.then(() => undefined);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -305,7 +305,7 @@ describe("run config → launch config", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("native programs under CodeLLDB / lldb-dap: program, args, cwd, env", () => {
|
||||
it("native programs under CodeLLDB / lldb-dap / GDB: program, args, cwd, env", () => {
|
||||
const run = rc({ command: "./build/app", args: ["-v"], cwd: "c", env: { K: "v" } });
|
||||
const lldb = launchConfigFor({ ...run, debugAdapter: "codelldb" }, "/p")!;
|
||||
expect(lldb).toMatchObject({
|
||||
@@ -320,6 +320,16 @@ describe("run config → launch config", () => {
|
||||
expect(dap).toMatchObject({ adapter: "lldb-dap", program: "/p/c/build/app" });
|
||||
// lldb-dap takes `KEY=VALUE` strings.
|
||||
expect(extra(dap)).toEqual({ env: ["K=v"] });
|
||||
// GDB's DAP launch takes the environment as an object, like the default flow.
|
||||
const gdb = launchConfigFor({ ...run, debugAdapter: "gdb" }, "/p")!;
|
||||
expect(gdb).toMatchObject({
|
||||
adapter: "gdb",
|
||||
program: "/p/c/build/app",
|
||||
args: ["-v"],
|
||||
cwd: "/p/c",
|
||||
env: { K: "v" },
|
||||
});
|
||||
expect(gdb.extraJson).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["native", "cmake-application"])(
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
|
||||
const debugEvaluateIn = vi.hoisted(() =>
|
||||
vi.fn(async () => ({
|
||||
status: "ok" as const,
|
||||
data: { name: "result", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
|
||||
})),
|
||||
);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
|
||||
@@ -8,6 +15,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
debugEvaluateIn,
|
||||
debugScopes: () => ok([{ name: "Locals", variablesReference: 1, expensive: false }]),
|
||||
debugVariables: () =>
|
||||
ok([
|
||||
@@ -31,6 +39,8 @@ vi.mock("@/workbench/confirmTerminate", () => ({ confirmTerminate }));
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useDebug, type DebugSession } from "../state";
|
||||
import { DebugTabs, DebugToolWindow } from "../ui/DebugToolWindow";
|
||||
import { DebuggerOverlays } from "../ui/Overlays";
|
||||
import { useOverlays } from "../ui/popoverStore";
|
||||
|
||||
const session: DebugSession = {
|
||||
id: 1,
|
||||
@@ -53,6 +63,26 @@ const session: DebugSession = {
|
||||
};
|
||||
|
||||
describe("debug tool window", () => {
|
||||
it.each(["gdb", "debugpy"])("evaluates expressions in the variable field and dialog under %s", async (adapter) => {
|
||||
debugEvaluateIn.mockClear();
|
||||
useDebug.setState({ sessions: { 1: { ...session, adapter } }, active: 1 });
|
||||
const { unmount } = render(<DebugToolWindow />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" }));
|
||||
const field = screen.getByPlaceholderText(/Evaluate expression/);
|
||||
fireEvent.change(field, { target: { value: "count + 1" } });
|
||||
fireEvent.keyDown(field, { key: "Enter" });
|
||||
const context = adapter === "gdb" ? "watch" : "repl";
|
||||
await vi.waitFor(() => expect(debugEvaluateIn).toHaveBeenCalledWith(1, 7, "count + 1", context));
|
||||
unmount();
|
||||
debugEvaluateIn.mockClear();
|
||||
useOverlays.setState({ evaluate: { expression: "count + 1" } });
|
||||
const dialog = render(<DebuggerOverlays />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Evaluate" }));
|
||||
await vi.waitFor(() => expect(debugEvaluateIn).toHaveBeenCalledWith(1, 7, "count + 1", context));
|
||||
dialog.unmount();
|
||||
useOverlays.setState({ evaluate: null });
|
||||
});
|
||||
|
||||
it("offers Hot Reload and Hot Restart for Dart and Flutter sessions only", () => {
|
||||
const hot = () => ["debug.hotReload", "debug.hotRestart"].map((name) => !!screen.queryByRole("button", { name }));
|
||||
useDebug.setState({ sessions: { 1: { ...session, status: "running" } }, active: 1 });
|
||||
|
||||
@@ -318,7 +318,7 @@ function godotLaunch(rc: RunConfig, cwd: string): LaunchConfig {
|
||||
return { ...base(rc, "godot", project), extraJson: JSON.stringify({ project, scene: godotScene(rc.args) }) };
|
||||
}
|
||||
|
||||
/** A native program under CodeLLDB or lldb-dap: program, args, cwd, env. */
|
||||
/** A native program under CodeLLDB, lldb-dap or GDB: program, args, cwd, env. */
|
||||
function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig {
|
||||
const out: LaunchConfig = { ...base(rc, adapter, cwd), program: resolveCommand(rc.command, cwd), args: [...rc.args] };
|
||||
// lldb-dap takes the environment as `KEY=VALUE` strings.
|
||||
@@ -420,7 +420,7 @@ export function launchConfigFor(rc: RunConfig, root: string, php: string | null
|
||||
if (adapter === "dart") {
|
||||
return rc.params?.request === "attach" ? flutterAttach(rc, cwd, adapter) : flutterLaunch(rc, cwd, adapter);
|
||||
}
|
||||
if (adapter === "codelldb" || adapter === "lldb-dap") {
|
||||
if (adapter === "codelldb" || adapter === "lldb-dap" || adapter === "gdb") {
|
||||
return rc.kind === "cargo" ? cargoLaunch(rc, cwd, adapter) : nativeLaunch(rc, cwd, adapter);
|
||||
}
|
||||
if (adapter === "debugpy") return debugpyLaunch(rc, cwd);
|
||||
|
||||
@@ -512,7 +512,11 @@ function VariablesPane({ session }: { session: DebugSession }) {
|
||||
const e = expression.trim();
|
||||
if (!e) return;
|
||||
try {
|
||||
setLastEval({ expression: e, result: await evaluate(e, "repl", session), error: null });
|
||||
setLastEval({
|
||||
expression: e,
|
||||
result: await evaluate(e, session.adapter === "gdb" ? "watch" : "repl", session),
|
||||
error: null,
|
||||
});
|
||||
} catch (err) {
|
||||
setLastEval({ expression: e, result: null, error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
|
||||
@@ -706,7 +706,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
setHistory(readHistory("evaluate"));
|
||||
historyPos.current = -1;
|
||||
try {
|
||||
const v: Variable = await evaluate(e, "repl", session ?? null);
|
||||
const v: Variable = await evaluate(e, session?.adapter === "gdb" ? "watch" : "repl", session ?? null);
|
||||
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: v, error: null });
|
||||
} catch (err) {
|
||||
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: null, error: errorText(err) });
|
||||
|
||||
@@ -66,6 +66,7 @@ const ADAPTERS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: "delve", label: "Delve (Go)" },
|
||||
{ id: "codelldb", label: "CodeLLDB (Rust, C, C++)" },
|
||||
{ id: "lldb-dap", label: "lldb-dap (C, C++, Swift)" },
|
||||
{ id: "gdb", label: "GDB (C, C++)" },
|
||||
{ id: "php-debug", label: "php-debug (PHP)" },
|
||||
{ id: "rdbg", label: "rdbg (Ruby)" },
|
||||
];
|
||||
@@ -375,7 +376,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
|
||||
const adapterOptions: SelectOption[] = [
|
||||
{ value: "", label: "None" },
|
||||
...ADAPTERS.map((a) => ({ value: a.id, label: a.label })),
|
||||
...ADAPTERS.map((a) => ({ value: a.id, label: tx(a.label) })),
|
||||
];
|
||||
if (config.debugAdapter && !ADAPTERS.some((a) => a.id === config.debugAdapter))
|
||||
adapterOptions.push({
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
worktree: vi.fn(),
|
||||
openDiff: vi.fn(),
|
||||
openFile: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: { ...real.commands, vcsDiffWithWorktree: mocks.worktree },
|
||||
};
|
||||
});
|
||||
vi.mock("../diffInput", async (original) => {
|
||||
const real = await original<typeof import("../diffInput")>();
|
||||
return { ...real, openVcsDiff: mocks.openDiff };
|
||||
});
|
||||
vi.mock("../DiffEditor", () => ({
|
||||
DiffEditor: ({ input }: { input: unknown }) => <div data-testid="diff">{JSON.stringify(input)}</div>,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (original) => {
|
||||
const real = await original<typeof import("@/workbench/contributions")>();
|
||||
return { ...real, maybeEditorService: () => ({ openFile: mocks.openFile }) };
|
||||
});
|
||||
import { useProject } from "@/platform/project";
|
||||
import { comparisonDiffData, type ComparisonFile } from "../operations";
|
||||
import { CompareToolWindow, useCompareTool } from "../compareTool";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const modified: ComparisonFile = {
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
oldPath: null,
|
||||
root: "/workspace/client",
|
||||
revision: "aaa",
|
||||
added: 3,
|
||||
removed: 1,
|
||||
};
|
||||
const from = { rev: "main", label: "main" };
|
||||
|
||||
describe("comparisonDiffData", () => {
|
||||
it("puts the revision on the left and the working tree on the right", () => {
|
||||
const data = comparisonDiffData(modified, from, null, false);
|
||||
expect(data.path).toBe("/workspace/client/src/app.ts");
|
||||
expect(data.left).toEqual({ type: "rev", rev: "aaa", label: "main", path: undefined });
|
||||
expect(data.right).toEqual({ type: "worktree" });
|
||||
});
|
||||
|
||||
it("swaps both sides, for worktree and revision diffs alike", () => {
|
||||
const worktree = comparisonDiffData(modified, from, null, true);
|
||||
expect(worktree.left).toEqual({ type: "worktree" });
|
||||
expect(worktree.right).toEqual({ type: "rev", rev: "aaa", label: "main", path: undefined });
|
||||
const revisions = comparisonDiffData(modified, from, { rev: "feature", label: "feature" }, true);
|
||||
expect(revisions.left).toEqual({ type: "rev", rev: "feature", label: "feature" });
|
||||
expect(revisions.right).toEqual({ type: "rev", rev: "aaa", label: "main", path: undefined });
|
||||
});
|
||||
|
||||
it("keeps the one-sided markers on their file after a swap", () => {
|
||||
const added: ComparisonFile = { ...modified, kind: "added", path: "src/new.ts" };
|
||||
expect(comparisonDiffData(added, from, null, false).left).toEqual({
|
||||
type: "text",
|
||||
text: "",
|
||||
label: "(does not exist)",
|
||||
});
|
||||
expect(comparisonDiffData(added, from, null, true).right).toEqual({
|
||||
type: "text",
|
||||
text: "",
|
||||
label: "(does not exist)",
|
||||
});
|
||||
const deleted: ComparisonFile = { ...modified, kind: "deleted", path: "src/old.ts" };
|
||||
expect(comparisonDiffData(deleted, from, null, false).right).toEqual({
|
||||
type: "text",
|
||||
text: "",
|
||||
label: "(deleted)",
|
||||
});
|
||||
expect(comparisonDiffData(deleted, from, null, true).left).toEqual({
|
||||
type: "text",
|
||||
text: "",
|
||||
label: "(deleted)",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("CompareToolWindow", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useProject.setState({ project: { root: "/workspace", name: "workspace" } as never });
|
||||
useVcs.setState({ available: true, root: "/workspace", roots: ["/workspace/client"], repo: "/workspace/client" });
|
||||
mocks.worktree.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{ ...modified, added: 3, removed: 1 },
|
||||
{ path: "src/new.ts", kind: "added", oldPath: null, root: "/workspace/client", revision: "aaa" },
|
||||
{ path: "src/old.ts", kind: "deleted", oldPath: null, root: "/workspace/client", revision: "aaa" },
|
||||
],
|
||||
});
|
||||
useCompareTool.getState().show(from, null);
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
useCompareTool.getState().close();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
it("lists the worktree diff and jumps to the selected source file", async () => {
|
||||
render(<CompareToolWindow />);
|
||||
const jump = screen.getByRole("button", { name: "Jump to Source" });
|
||||
expect(jump).toBeDisabled();
|
||||
fireEvent.mouseDown(await screen.findByText("app.ts"), { button: 0 });
|
||||
expect(jump).toBeEnabled();
|
||||
fireEvent.click(jump);
|
||||
expect(mocks.openFile).toHaveBeenCalledWith("/workspace/client/src/app.ts", { focus: true });
|
||||
});
|
||||
|
||||
it("has no Jump to Source for a file deleted from the working tree", async () => {
|
||||
render(<CompareToolWindow />);
|
||||
fireEvent.mouseDown(await screen.findByText("old.ts"), { button: 0 });
|
||||
expect(screen.getByRole("button", { name: "Jump to Source" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("swaps the sides of the shown diff", async () => {
|
||||
mocks.openDiff.mockResolvedValue(undefined);
|
||||
render(<CompareToolWindow />);
|
||||
fireEvent.mouseDown(await screen.findByText("app.ts"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Show Diff" }));
|
||||
expect(mocks.openDiff).toHaveBeenLastCalledWith(expect.objectContaining({ right: { type: "worktree" } }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Swap Sides" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Diff" }));
|
||||
expect(mocks.openDiff).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
left: { type: "worktree" },
|
||||
right: expect.objectContaining({ type: "rev", label: "main" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* The Compare tool window: `Show Diff with Working Tree` shows the worktree diff
|
||||
* in the sidebar instead of a dialog, with Jump to Source and Swap Sides (#2442).
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { Button } from "@/ui";
|
||||
import { maybeEditorService, notifications, registerToolWindow } from "@/workbench/contributions";
|
||||
import { showToolWindow } from "@/workbench/toolwindows/store";
|
||||
import { openVcsDiff, type DiffData } from "./diffInput";
|
||||
import { ChangesBetweenDialog, type ComparisonFile, type Revision } from "./operations";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import styles from "./common.module.css";
|
||||
|
||||
interface CompareToolState {
|
||||
target: { from: Revision; to: Revision | null } | null;
|
||||
swapped: boolean;
|
||||
current: ComparisonFile | null;
|
||||
show: (from: Revision, to: Revision | null) => void;
|
||||
close: () => void;
|
||||
toggleSwapped: () => void;
|
||||
select: (file: ComparisonFile | null) => void;
|
||||
}
|
||||
|
||||
export const useCompareTool = create<CompareToolState>()((set) => ({
|
||||
target: null,
|
||||
swapped: false,
|
||||
current: null,
|
||||
show: (from, to) => set({ target: { from, to }, swapped: false, current: null }),
|
||||
close: () => set({ target: null, swapped: false, current: null }),
|
||||
toggleSwapped: () => set((s) => ({ swapped: !s.swapped })),
|
||||
select: (current) => set({ current }),
|
||||
}));
|
||||
|
||||
let disposeCompareWindow: (() => void) | null = null;
|
||||
|
||||
function ensureCompareWindow() {
|
||||
disposeCompareWindow ??= registerToolWindow({
|
||||
id: "compare",
|
||||
title: "Compare",
|
||||
icon: "diff",
|
||||
anchor: "left",
|
||||
order: 2,
|
||||
component: CompareToolWindow,
|
||||
});
|
||||
}
|
||||
|
||||
function disposeCompareWindowNow() {
|
||||
disposeCompareWindow?.();
|
||||
disposeCompareWindow = null;
|
||||
}
|
||||
|
||||
/** Worktree diff of `rev` in the sidebar's Compare tool window (no dialog). */
|
||||
export function showWorktreeComparison(rev: string, label: string) {
|
||||
useCompareTool.getState().show({ rev, label }, null);
|
||||
ensureCompareWindow();
|
||||
showToolWindow("compare", true);
|
||||
}
|
||||
|
||||
export function CompareToolWindow() {
|
||||
const target = useCompareTool((s) => s.target);
|
||||
const swapped = useCompareTool((s) => s.swapped);
|
||||
const current = useCompareTool((s) => s.current);
|
||||
const toggleSwapped = useCompareTool((s) => s.toggleSwapped);
|
||||
const select = useCompareTool((s) => s.select);
|
||||
const close = useCompareTool((s) => s.close);
|
||||
if (!target) return null;
|
||||
const jumpToSource = () => {
|
||||
if (!current || current.kind === "deleted") return;
|
||||
void maybeEditorService()?.openFile(repositoryPath(current.root, current.path), { focus: true });
|
||||
};
|
||||
const showDiff = (data: DiffData) => {
|
||||
void openVcsDiff(data).catch((error) =>
|
||||
notifications().notify({ level: "error", title: "Could not show diff", body: String(error) }),
|
||||
);
|
||||
};
|
||||
const handleClose = () => {
|
||||
close();
|
||||
disposeCompareWindowNow();
|
||||
};
|
||||
return (
|
||||
<div className={styles.comparisonWindow}>
|
||||
<div className={styles.compareToolbar}>
|
||||
<Button size="small" onClick={jumpToSource} disabled={!current || current.kind === "deleted"}>
|
||||
Jump to Source
|
||||
</Button>
|
||||
<Button size="small" variant={swapped ? "primary" : "secondary"} onClick={toggleSwapped}>
|
||||
Swap Sides
|
||||
</Button>
|
||||
</div>
|
||||
<div className={styles.comparisonWindowBody}>
|
||||
<ChangesBetweenDialog
|
||||
key={target.from.rev}
|
||||
from={target.from}
|
||||
to={target.to}
|
||||
native
|
||||
swapped={swapped}
|
||||
onSelect={select}
|
||||
onShowDiff={showDiff}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import { reloadLog, useGitLog } from "./logStore";
|
||||
import { conflictedFiles, currentRepo, currentRepoRoot, refreshNow, repoName, repoOf, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { ComparisonTree } from "./ComparisonTree";
|
||||
import { showWorktreeComparison } from "./compareTool";
|
||||
import { buildFileTree, type FileTreeNode } from "./fileTree";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { displayPath } from "./compareData";
|
||||
@@ -508,9 +507,9 @@ export function showCompareWithLocal(commit: Commit) {
|
||||
showDiffWithWorkingTree(commit.id, short(commit.id));
|
||||
}
|
||||
|
||||
/** Files that differ between `rev` (a commit or branch) and the working tree, in the Compare tool window. */
|
||||
/** Files that differ between `rev` (a commit or branch) and the working tree. */
|
||||
export function showDiffWithWorkingTree(rev: string, label = rev) {
|
||||
showWorktreeComparison(rev, label);
|
||||
showComparison({ rev, label }, null);
|
||||
}
|
||||
|
||||
/** IDEA's Compare Versions of two Git Log commits: files that differ between them, older first. */
|
||||
@@ -538,7 +537,7 @@ function showComparison(from: Revision, to: Revision | null, scope?: ScopedCompa
|
||||
);
|
||||
}
|
||||
|
||||
export interface Revision {
|
||||
interface Revision {
|
||||
rev: string;
|
||||
label: string;
|
||||
}
|
||||
@@ -548,43 +547,13 @@ interface ScopedComparison {
|
||||
repositories: string[] | null;
|
||||
}
|
||||
|
||||
export interface ComparisonFile extends ChangedFile {
|
||||
interface ComparisonFile extends ChangedFile {
|
||||
root: string;
|
||||
revision: string;
|
||||
added?: number;
|
||||
removed?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Diff content of one comparison file. `swapped` exchanges the two sides
|
||||
* (the Compare tool window's Swap Sides), for worktree and revision diffs alike.
|
||||
*/
|
||||
export function comparisonDiffData(
|
||||
file: ComparisonFile,
|
||||
from: Revision,
|
||||
to: Revision | null,
|
||||
swapped: boolean,
|
||||
): DiffData {
|
||||
const missing = (label: string): DiffSide => ({ type: "text", text: "", label });
|
||||
const path = repositoryPath(file.root, file.path);
|
||||
const left: DiffSide =
|
||||
file.kind === "added" || file.kind === "untracked"
|
||||
? missing("(does not exist)")
|
||||
: {
|
||||
type: "rev",
|
||||
rev: file.revision,
|
||||
label: from.label,
|
||||
path: file.oldPath ? repositoryPath(file.root, file.oldPath) : undefined,
|
||||
};
|
||||
const right: DiffSide =
|
||||
file.kind === "deleted"
|
||||
? missing("(deleted)")
|
||||
: !to
|
||||
? { type: "worktree" }
|
||||
: { type: "rev", rev: to.rev, label: to.label };
|
||||
return swapped ? { path, left: right, right: left } : { path, left, right };
|
||||
}
|
||||
|
||||
export function comparisonEmpty(revision: string, repositories: number): string {
|
||||
return repositories === 1
|
||||
? tx`No changes against ${revision} in 1 repository`
|
||||
@@ -600,8 +569,6 @@ export function ChangesBetweenDialog({
|
||||
native = false,
|
||||
onCaption,
|
||||
onShowDiff,
|
||||
swapped = false,
|
||||
onSelect,
|
||||
}: {
|
||||
from: Revision;
|
||||
to: Revision | null;
|
||||
@@ -611,21 +578,13 @@ export function ChangesBetweenDialog({
|
||||
native?: boolean;
|
||||
onCaption?: (caption: string) => void;
|
||||
onShowDiff?: (data: DiffData) => void;
|
||||
/** Exchange the two sides (the Compare tool window's Swap Sides). */
|
||||
swapped?: boolean;
|
||||
/** Reports the selected file (the Compare tool window's Jump to Source / Swap Sides). */
|
||||
onSelect?: (file: ComparisonFile | null) => void;
|
||||
}) {
|
||||
const [root] = useState(currentRepoRoot);
|
||||
const [repo] = useState(currentRepo);
|
||||
const [files, setFiles] = useState<ComparisonFile[] | null>(null);
|
||||
const [result, setResult] = useState<CompareResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [current, setCurrentState] = useState<ComparisonFile | null>(null);
|
||||
const setCurrent = (file: ComparisonFile | null) => {
|
||||
setCurrentState(file);
|
||||
onSelect?.(file);
|
||||
};
|
||||
const [current, setCurrent] = useState<ComparisonFile | null>(null);
|
||||
const fromRev = from.rev;
|
||||
const toRev = to?.rev ?? null;
|
||||
useEffect(() => {
|
||||
@@ -674,7 +633,27 @@ export function ChangesBetweenDialog({
|
||||
};
|
||||
});
|
||||
}, [files, result, scope]);
|
||||
const diffFor = (f: ComparisonFile): DiffData => comparisonDiffData(f, from, to, swapped);
|
||||
const diffFor = (f: ComparisonFile): DiffData => {
|
||||
const missing = (label: string): DiffSide => ({ type: "text", text: "", label });
|
||||
return {
|
||||
path: repositoryPath(f.root, f.path),
|
||||
left:
|
||||
f.kind === "added" || f.kind === "untracked"
|
||||
? missing("(does not exist)")
|
||||
: {
|
||||
type: "rev",
|
||||
rev: f.revision,
|
||||
label: from.label,
|
||||
path: f.oldPath ? repositoryPath(f.root, f.oldPath) : undefined,
|
||||
},
|
||||
right:
|
||||
f.kind === "deleted"
|
||||
? missing("(deleted)")
|
||||
: !to
|
||||
? { type: "worktree" }
|
||||
: { type: "rev", rev: to.rev, label: to.label },
|
||||
};
|
||||
};
|
||||
const input = current ? diffInput(diffFor(current)) : null;
|
||||
const title = to
|
||||
? tx`Changes between ${from.label} and ${to.label}`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"GDB (C, C++)": "GDB (C, C++)",
|
||||
"Unknown error": "Unknown error",
|
||||
"Retry Loading Conversation": "Retry Loading Conversation",
|
||||
"No conversation history": "No conversation history",
|
||||
@@ -8,9 +9,7 @@
|
||||
"Astro Language Server needs Node.js. Install it or select its executable in Settings › Languages & Frameworks › Node.js.": "Astro Language Server needs Node.js. Install it or select its executable in Settings › Languages & Frameworks › Node.js.",
|
||||
"Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.": "Astro Language Server needs a TypeScript language-service library. Install typescript@6 in the project or select a TypeScript lib directory in Settings.",
|
||||
"Cannot show current revision": "Cannot show current revision",
|
||||
"Compare": "Compare",
|
||||
"Compare with Revision…": "Compare with Revision…",
|
||||
"Swap Sides": "Swap Sides",
|
||||
"Show Current Revision": "Show Current Revision",
|
||||
"Search file revisions": "Search file revisions",
|
||||
"File revisions": "File revisions",
|
||||
|
||||
@@ -1476,7 +1476,6 @@
|
||||
"Package manager": "Administrador de paquetes",
|
||||
"Package to install": "Paquete a instalar",
|
||||
"Packages": "Paquetes",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "Empaqueta el proyecto (mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
"Page size": "Tamaño de página",
|
||||
"Parameter Info": "Información de parámetros",
|
||||
"Parameter names": "Nombres de parámetros",
|
||||
|
||||
@@ -1404,7 +1404,6 @@
|
||||
"Package manager": "Gestionnaire de paquets",
|
||||
"Package to install": "Paquet à installer",
|
||||
"Packages": "Paquets",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "Empaquette le projet (mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
"Page size": "Taille de page",
|
||||
"Parameter Info": "Informations sur les paramètres",
|
||||
"Parameter names": "Noms des paramètres",
|
||||
|
||||
@@ -1518,7 +1518,6 @@
|
||||
"Package manager": "패키지 관리자",
|
||||
"Package to install": "설치할 패키지",
|
||||
"Packages": "패키지",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "프로젝트를 패키징합니다(mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
"Page size": "페이지 크기",
|
||||
"Parameter Info": "매개변수 정보",
|
||||
"Parameter names": "매개변수 이름",
|
||||
|
||||
@@ -1466,7 +1466,6 @@
|
||||
"Package manager": "Menedżer pakietów",
|
||||
"Package to install": "Pakiet do zainstalowania",
|
||||
"Packages": "Pakiety",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "Pakuje projekt (mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
"Page size": "Rozmiar strony",
|
||||
"Parameter Info": "Informacje o parametrach",
|
||||
"Parameter names": "Nazwy parametrów",
|
||||
|
||||
@@ -1466,7 +1466,6 @@
|
||||
"Package manager": "Gerenciador de pacotes",
|
||||
"Package to install": "Pacote a instalar",
|
||||
"Packages": "Pacotes",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "Empacota o projeto (mvn package, gradle assemble, cargo build --release, npm run build)",
|
||||
"Page size": "Tamanho da página",
|
||||
"Parameter Info": "Informações de parâmetros",
|
||||
"Parameter names": "Nomes dos parâmetros",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"GDB (C, C++)": "GDB(C、C++)",
|
||||
"Unknown error": "未知错误",
|
||||
"Retry Loading Conversation": "重新加载对话",
|
||||
"No conversation history": "没有对话历史记录",
|
||||
@@ -674,7 +675,6 @@
|
||||
"Commit…": "提交…",
|
||||
"Compact mode": "紧凑模式",
|
||||
"Companion object": "伴生对象",
|
||||
"Compare": "对比",
|
||||
"Compare Files": "比较文件",
|
||||
"Compare Texts": "比较文本",
|
||||
"Compare With": "比较对象",
|
||||
@@ -1671,7 +1671,7 @@
|
||||
"Package manager": "软件包管理器",
|
||||
"Package to install": "要安装的软件包",
|
||||
"Packages": "软件包",
|
||||
"Packages the project (mvn package, gradle assemble, cargo build --release, npm run build)": "打包项目(mvn package、gradle assemble、cargo build --release、npm run build)",
|
||||
"Packages the current module's artifacts, or the whole project when no file is active": "打包当前模块的产物,无活动文件时则打包整个项目",
|
||||
"Page size": "页面大小",
|
||||
"Parameter Info": "形参信息",
|
||||
"Parameter names": "形参名称",
|
||||
@@ -2515,7 +2515,6 @@
|
||||
"Surround With…": "包围方式…",
|
||||
"Surround selection on typing quote or brace": "输入引号或括号时包围所选内容",
|
||||
"Suspend on": "挂起时机",
|
||||
"Swap Sides": "交换两侧",
|
||||
"Switch to Auto-Commit": "切换到自动提交",
|
||||
"Switcher": "切换器",
|
||||
"Switcher (Backward)": "切换器(向后)",
|
||||
|
||||
Reference in new issue
Заблокувати користувача