дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 13:06:07 +02:00
Порівняти коміти
2
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f43b43aadd | ||
|
|
8ca7efc411 |
No files matched your search
Створено
+38
-36
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4061,7 +4061,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4075,11 +4075,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4090,7 +4091,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4099,11 +4100,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4116,7 +4116,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4130,7 +4130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4148,7 +4148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4170,9 +4170,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4183,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4195,10 +4196,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4208,7 +4210,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4255,7 +4257,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4273,7 +4275,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4295,7 +4297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4311,7 +4313,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4366,7 +4368,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4391,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4414,7 +4416,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4432,7 +4434,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4445,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4462,7 +4464,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4485,7 +4487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4504,7 +4506,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4524,7 +4526,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4537,7 +4539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4556,7 +4558,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4571,7 +4573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4584,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4596,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4617,7 +4619,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4636,7 +4638,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4658,7 +4660,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4674,7 +4676,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6146,7 +6148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"block2 0.6.2",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -169,7 +169,7 @@ impl Translator {
|
||||
Some("tool_use") => {
|
||||
// The input streams after this: shown by name until the message has it.
|
||||
let (id, name) = (str_of(&block, "id"), str_of(&block, "name"));
|
||||
if !(id.is_empty() || tools::is_plan(&name) || tools::is_agent(&name) && self.subagents) {
|
||||
if !id.is_empty() && !tools::is_plan(&name) && !(tools::is_agent(&name) && self.subagents) {
|
||||
out.extend(self.ensure_call(&id, &name, &json!({}), &session));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,5 +15,8 @@ specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -2,12 +2,11 @@
|
||||
//! line to a callback, and cancellation kills the whole process group (the
|
||||
//! `mvnw` / `gradlew` wrapper scripts start the JVM as a child).
|
||||
|
||||
use ide_core::process::kill_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -23,6 +22,18 @@ pub(crate) struct Output {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
fn kill_tree(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
if let Ok(pid) = i32::try_from(child.id()) {
|
||||
// SAFETY: plain syscall; the group was created by `process_group(0)` at spawn.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// `program` as spawnable: a bare name (`mvn`, `mvn.cmd`) resolves on the IDE's
|
||||
/// search path — the login shell's `PATH` plus version-manager shims — since the
|
||||
/// app's own `PATH` can be minimal and `Command` would not see `mvn` there.
|
||||
@@ -69,8 +80,12 @@ pub(crate) fn run_with_env(
|
||||
let mut command = Command::new(&program);
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
// Its own group: `mvnw` / `gradlew` start the JVM as a child, and cancelling kills both.
|
||||
ide_core::process::prepare(ide_core::process::own_group(&mut command));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(&mut command);
|
||||
if clear_env {
|
||||
command.env_clear().envs(env).envs(encoding.env);
|
||||
}
|
||||
|
||||
@@ -18,8 +18,5 @@ tokio-util.workspace = true
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation"] }
|
||||
@@ -36,21 +36,12 @@ pub enum IdeEvent {
|
||||
base_version: u32,
|
||||
version: u32,
|
||||
changes: Vec<TextChange>,
|
||||
/// Part of a grouped transaction; the editor must not record a file-local undo.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
workspace_edit: bool,
|
||||
},
|
||||
/// A document's dirty flag changed (saved / modified externally).
|
||||
DocDirty {
|
||||
doc: DocId,
|
||||
dirty: bool,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
paths: Vec<crate::IpcPath>,
|
||||
},
|
||||
/// An open document's language changed (Settings › File Types, Override File
|
||||
/// Type), or its UI mode (a framework's root marker appeared or went).
|
||||
DocLanguage {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
//! Child-process helpers shared by every crate that spawns tools.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
#[cfg(windows)]
|
||||
use std::process::Stdio;
|
||||
use std::process::{Child, Command};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
|
||||
/// with other flags (and then call [`host_env`] themselves). Prefer [`prepare`] otherwise.
|
||||
@@ -28,70 +25,6 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
host_env(cmd)
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
|
||||
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
|
||||
pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
/// - Windows: `taskkill /T /F`, which walks the tree from the child's process id.
|
||||
pub fn kill_tree(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
signal_group(child, libc::SIGKILL);
|
||||
#[cfg(windows)]
|
||||
taskkill_tree(child);
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// [`kill_tree`] that first asks the group to exit: `SIGTERM`, then `grace`, then `SIGKILL`.
|
||||
/// Git removes its `index.lock` on `SIGTERM`, where `SIGKILL` leaves it behind and the next
|
||||
/// git command fails. Windows has no such signal to send from outside the child's console,
|
||||
/// so there it is [`kill_tree`].
|
||||
pub fn terminate_tree(child: &mut Child, grace: Duration) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
signal_group(child, libc::SIGTERM);
|
||||
// Sleep rather than `try_wait`: the child stays unreaped, so its process id (and the
|
||||
// group id) cannot be reused before the `SIGKILL` below.
|
||||
std::thread::sleep(grace);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = grace;
|
||||
kill_tree(child);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
if let Ok(pid) = libc::pid_t::try_from(child.id()) {
|
||||
// SAFETY: plain syscall. The child is not reaped yet, so `-pid` is still its group (or
|
||||
// no group at all when it was not spawned with `own_group`, and the call fails).
|
||||
unsafe {
|
||||
libc::kill(-pid, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn taskkill_tree(child: &Child) {
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &child.id().to_string()])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
}
|
||||
|
||||
/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and
|
||||
/// its hooks point `LD_LIBRARY_PATH`, `PATH`, `XDG_DATA_DIRS`, `GIO_MODULE_DIR`, `GTK_PATH`,
|
||||
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
|
||||
@@ -664,71 +597,3 @@ mod tests {
|
||||
assert_eq!(find_executable("nope", &search), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod kill_tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Runs `script` in `sh` as its own group's leader and waits for it to write `ready`.
|
||||
fn start(script: &str, ready: &Path) -> Child {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.arg("-c").arg(script);
|
||||
let child = own_group(&mut cmd).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !ready.exists() {
|
||||
assert!(Instant::now() < deadline, "the script never got ready");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
child
|
||||
}
|
||||
|
||||
fn assert_gone(pid: libc::pid_t) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
// SAFETY: signal 0 only checks that the process exists.
|
||||
while unsafe { libc::kill(pid, 0) } == 0 {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_tree_kills_what_the_child_started() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let script = format!("sleep 30 & echo $! > '{0}.tmp' && mv '{0}.tmp' '{0}'; wait", pid_file.display());
|
||||
let mut child = start(&script, &pid_file);
|
||||
let grandchild: libc::pid_t = std::fs::read_to_string(&pid_file).unwrap().trim().parse().unwrap();
|
||||
kill_tree(&mut child);
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
assert_gone(grandchild);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_tree_lets_the_child_clean_up() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (ready, cleaned) = (dir.path().join("ready"), dir.path().join("cleaned"));
|
||||
let script = format!(
|
||||
"trap 'touch \"{}\"; exit 0' TERM; touch \"{}\"; sleep 30 & wait",
|
||||
cleaned.display(),
|
||||
ready.display()
|
||||
);
|
||||
let mut child = start(&script, &ready);
|
||||
terminate_tree(&mut child, Duration::from_millis(500));
|
||||
assert!(cleaned.exists(), "the SIGTERM handler ran before the SIGKILL");
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_tree_still_kills_a_child_that_ignores_sigterm() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ready = dir.path().join("ready");
|
||||
let script = format!("trap '' TERM; touch \"{}\"; while :; do sleep 1; done", ready.display());
|
||||
let mut child = start(&script, &ready);
|
||||
let started = Instant::now();
|
||||
terminate_tree(&mut child, Duration::from_millis(50));
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
@@ -97,16 +97,6 @@ pub struct TextEdit {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct WorkspaceEdit {
|
||||
pub files: Vec<FileEdit>,
|
||||
/// Content fingerprints captured before presenting an edit for confirmation.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub preconditions: Vec<WorkspaceEditPrecondition>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct WorkspaceEditPrecondition {
|
||||
pub path: crate::IpcPath,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
impl WorkspaceEdit {
|
||||
@@ -118,26 +108,17 @@ impl WorkspaceEdit {
|
||||
let mut resolve_aliases = true;
|
||||
for file in std::mem::take(&mut self.files) {
|
||||
match file {
|
||||
FileEdit::Edit { path, edits, version } => {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
let path = if resolve_aliases {
|
||||
dunce::canonicalize(&path).unwrap_or_else(|_| path.to_path_buf())
|
||||
} else {
|
||||
path.to_path_buf()
|
||||
};
|
||||
let index = *batch.entry(path.clone()).or_insert_with(|| {
|
||||
files.push(FileEdit::Edit { path: path.clone().into(), edits: Vec::new(), version });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits: Vec::new() });
|
||||
files.len() - 1
|
||||
});
|
||||
let FileEdit::Edit { edits: own, version: expected, .. } = &mut files[index] else {
|
||||
unreachable!()
|
||||
};
|
||||
if expected.is_some() && version.is_some() && *expected != version {
|
||||
// Keep incompatible constraints so application rejects them
|
||||
// before changing any file instead of silently losing one.
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version });
|
||||
continue;
|
||||
}
|
||||
*expected = expected.or(version);
|
||||
let FileEdit::Edit { edits: own, .. } = &mut files[index] else { unreachable!() };
|
||||
for edit in edits {
|
||||
if !own.contains(&edit) {
|
||||
own.push(edit);
|
||||
@@ -159,26 +140,10 @@ impl WorkspaceEdit {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum FileEdit {
|
||||
Edit {
|
||||
path: crate::IpcPath,
|
||||
edits: Vec<TextEdit>,
|
||||
/// LSP TextDocumentEdit version; null/unversioned edits use content preconditions.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
version: Option<i32>,
|
||||
},
|
||||
Create {
|
||||
path: crate::IpcPath,
|
||||
overwrite: bool,
|
||||
},
|
||||
Rename {
|
||||
from: crate::IpcPath,
|
||||
to: crate::IpcPath,
|
||||
},
|
||||
Delete {
|
||||
path: crate::IpcPath,
|
||||
recursive: bool,
|
||||
},
|
||||
Edit { path: crate::IpcPath, edits: Vec<TextEdit> },
|
||||
Create { path: crate::IpcPath, overwrite: bool },
|
||||
Rename { from: crate::IpcPath, to: crate::IpcPath },
|
||||
Delete { path: crate::IpcPath, recursive: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
@@ -289,7 +254,7 @@ mod workspace_edit_tests {
|
||||
std::fs::write(&real, "add()").unwrap();
|
||||
std::os::unix::fs::symlink(&real, &alias).unwrap();
|
||||
let change = TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() };
|
||||
let edit = |path: PathBuf| FileEdit::Edit { path: path.into(), edits: vec![change.clone()], version: None };
|
||||
let edit = |path: PathBuf| FileEdit::Edit { path: path.into(), edits: vec![change.clone()] };
|
||||
let mut workspace = WorkspaceEdit {
|
||||
files: vec![
|
||||
edit(real.clone()),
|
||||
@@ -297,7 +262,6 @@ mod workspace_edit_tests {
|
||||
FileEdit::Create { path: dir.path().join("other").into(), overwrite: false },
|
||||
edit(real),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 3);
|
||||
|
||||
@@ -13,5 +13,8 @@ specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1,16 +1,11 @@
|
||||
//! Child processes of the docker CLI: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (CLI plugins such as compose)
|
||||
/// gets to exit on `SIGTERM`, and clean up, before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
@@ -25,13 +20,36 @@ pub(crate) enum Stream {
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}")))
|
||||
}
|
||||
|
||||
/// Kills the child and, on Unix, its whole process group (CLI plugins such as compose).
|
||||
pub(crate) fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child leads its own process group (`prepare`).
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
@@ -70,11 +88,11 @@ pub(crate) fn run_with_input(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::unavailable("docker did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -148,7 +166,7 @@ pub(crate) fn stream(
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
@@ -171,7 +189,7 @@ pub(crate) fn stream(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -13,3 +13,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
@@ -1,16 +1,11 @@
|
||||
//! Child processes of the gh CLI: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (gh spawns git and helpers)
|
||||
/// gets to exit on `SIGTERM` before `SIGKILL`: git removes its lock files on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
@@ -25,13 +20,36 @@ pub(crate) enum Stream {
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}")))
|
||||
}
|
||||
|
||||
/// Kills the child and, on Unix, its whole process group (gh spawns git and helpers).
|
||||
pub(crate) fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child leads its own process group (`prepare`).
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
@@ -74,11 +92,11 @@ pub(crate) fn run_with_input(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::unavailable("gh did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -152,7 +170,7 @@ pub(crate) fn stream(
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
@@ -175,7 +193,7 @@ pub(crate) fn stream(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -57,7 +57,6 @@ fn migrate_entries(data: &Path, local: &Path) {
|
||||
"notebook-runtime",
|
||||
"server",
|
||||
"java-usages-1.1.1.jar",
|
||||
"java-usages-1.2.0.jar",
|
||||
"agents/registry.json",
|
||||
]
|
||||
.into_iter()
|
||||
@@ -299,7 +298,6 @@ mod tests {
|
||||
"agents/tools",
|
||||
"agents/registry.json",
|
||||
"java-usages-1.1.1.jar",
|
||||
"java-usages-1.2.0.jar",
|
||||
] {
|
||||
assert!(is_local(Path::new(entry)), "{entry}");
|
||||
assert_eq!(
|
||||
|
||||
@@ -174,7 +174,6 @@ impl Host {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.shutdown();
|
||||
project.notebooks.stop_admission();
|
||||
// What the closing window started goes with it — the builds and searches it
|
||||
@@ -252,13 +251,6 @@ impl Host {
|
||||
);
|
||||
}
|
||||
|
||||
/// Called before desktop exit, which may bypass document destructors.
|
||||
pub fn clear_workspace_edit_history_on_exit(&self) {
|
||||
for project in self.projects() {
|
||||
project.documents.clear_workspace_edit_history();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops what this host started: notebook kernels, language servers, agents, runs and terminals.
|
||||
/// For a process that exits without dropping the host (the remote server).
|
||||
pub async fn shutdown(&self) {
|
||||
@@ -270,7 +262,6 @@ impl Host {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
}
|
||||
|
||||
@@ -210,10 +210,8 @@ pub async fn maven_exclude_dependency(
|
||||
let (path, text, range) = declaring_pom(&project, &pom, &dependency)?;
|
||||
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
|
||||
Some(Exclusion::Edit(edit)) => {
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit { path: path.clone().into(), edits: vec![edit], version: None }],
|
||||
..Default::default()
|
||||
};
|
||||
let edit =
|
||||
WorkspaceEdit { files: vec![FileEdit::Edit { path: path.clone().into(), edits: vec![edit] }] };
|
||||
apply_workspace_edit(&project.documents, &edit)?;
|
||||
}
|
||||
Some(Exclusion::Present) => {}
|
||||
|
||||
@@ -127,7 +127,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?).await
|
||||
});
|
||||
d.add("doc_set_line_ending", |c| async move {
|
||||
blocking(move || doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)).await
|
||||
doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)
|
||||
});
|
||||
d.add("doc_outline", |c| async move { doc_outline(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_folding", |c| async move { doc_folding(&c.host, &c.window, c.arg("doc")?).await });
|
||||
|
||||
@@ -1,33 +1,9 @@
|
||||
use super::doc::blocking;
|
||||
use crate::Host;
|
||||
use crate::apply_workspace_edit as apply_edit;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::{DocId, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
|
||||
use ide_lsp::types::*;
|
||||
|
||||
async fn prepare_actions(
|
||||
project: std::sync::Arc<crate::Project>,
|
||||
doc: DocId,
|
||||
version: u32,
|
||||
mut actions: Vec<CodeAction>,
|
||||
) -> IdeResult<Vec<CodeAction>> {
|
||||
blocking(move || {
|
||||
if project.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
ide_core::error::ErrorKind::OutOfSync,
|
||||
"document changed while computing code actions; request them again",
|
||||
));
|
||||
}
|
||||
for action in &mut actions {
|
||||
if let Some(edit) = &mut action.edit {
|
||||
project.documents.prepare_workspace_edit(edit)?;
|
||||
}
|
||||
}
|
||||
Ok(actions)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn lsp_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -162,11 +138,7 @@ pub async fn lsp_code_actions(
|
||||
range: Range,
|
||||
only: Vec<String>,
|
||||
) -> IdeResult<Vec<CodeAction>> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let actions = project.lsp.code_actions(doc, range, only).await?;
|
||||
prepare_actions(project, doc, version, actions).await
|
||||
host.project(window)?.lsp.code_actions(doc, range, only).await
|
||||
}
|
||||
|
||||
/// Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability).
|
||||
@@ -178,15 +150,11 @@ pub async fn lsp_code_action_query(
|
||||
range: Range,
|
||||
only: Vec<String>,
|
||||
) -> IdeResult<CodeActionQuery> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.code_action_query(doc, range, only, cancel).await;
|
||||
let result = lsp.code_action_query(doc, range, only, cancel).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
result.actions = prepare_actions(project, doc, version, result.actions).await?;
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
/// Resolves a code action's edit without applying it (intention preview).
|
||||
@@ -199,28 +167,19 @@ pub async fn lsp_resolve_code_action(
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
Ok(prepare_actions(project, doc, version, vec![action]).await?.remove(0))
|
||||
host.project(window)?.lsp.resolve_code_action(doc, action).await
|
||||
}
|
||||
|
||||
/// Resolves (if needed), applies the edit, then runs the command of a code action.
|
||||
pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action: CodeAction) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
let action = if action.edit.is_none() && action.command.is_none() {
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
prepare_actions(project.clone(), doc, version, vec![action]).await?.remove(0)
|
||||
project.lsp.resolve_code_action(doc, action).await?
|
||||
} else {
|
||||
action
|
||||
};
|
||||
if let Some(edit) = &action.edit {
|
||||
let documents = project.documents.clone();
|
||||
let edit = edit.clone();
|
||||
blocking(move || apply_edit(&documents, &edit)).await?;
|
||||
apply_edit(&project.documents, edit)?;
|
||||
}
|
||||
if let Some(command) = action.command {
|
||||
project.lsp.execute_command(doc, command).await?;
|
||||
@@ -241,24 +200,11 @@ pub async fn lsp_rename(
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
) -> IdeResult<Renamed> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.rename(doc, pos, new_name, cancel).await;
|
||||
let result = lsp.rename(doc, pos, new_name, cancel).await;
|
||||
host.end_request(request);
|
||||
let mut renamed = result?;
|
||||
blocking(move || {
|
||||
if project.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
ide_core::error::ErrorKind::OutOfSync,
|
||||
"document changed while computing rename; request it again",
|
||||
));
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
|
||||
Ok(renamed)
|
||||
})
|
||||
.await
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn lsp_format(
|
||||
@@ -333,43 +279,21 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu
|
||||
}
|
||||
|
||||
/// Applies a (previewed) workspace edit, e.g. after rename confirmation.
|
||||
pub async fn apply_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
pub fn apply_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
// Multi-file refactorings leave a Local History point to go back to.
|
||||
let paths: Vec<&std::path::Path> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if edit.files.len() > 1 {
|
||||
project.record_before_refactoring(&paths, "Apply changes");
|
||||
}
|
||||
apply_edit(&project.documents, &edit)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn prepare_workspace_edit(host: &Host, window: &str, mut edit: WorkspaceEdit) -> IdeResult<WorkspaceEdit> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn undo_workspace_edit(host: &Host, window: &str, id: u32) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.documents.undo_workspace_edit(id)).await
|
||||
}
|
||||
|
||||
pub async fn redo_workspace_edit(host: &Host, window: &str, id: u32) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.documents.redo_workspace_edit(id)).await
|
||||
// Multi-file refactorings leave a Local History point to go back to.
|
||||
let paths: Vec<&std::path::Path> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if edit.files.len() > 1 {
|
||||
project.record_before_refactoring(&paths, "Apply changes");
|
||||
}
|
||||
apply_edit(&project.documents, &edit)
|
||||
}
|
||||
|
||||
/// Runs a server command (`workspace/executeCommand`), e.g. a completion item's
|
||||
@@ -517,7 +441,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
|
||||
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
|
||||
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?) });
|
||||
d.add("lsp_resolve_command", |c| async move {
|
||||
lsp_resolve_command(
|
||||
&c.host,
|
||||
@@ -541,12 +465,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"prepare_workspace_edit",
|
||||
|c| async move { prepare_workspace_edit(&c.host, &c.window, c.arg("edit")?).await },
|
||||
);
|
||||
d.add("redo_workspace_edit", |c| async move { redo_workspace_edit(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("undo_workspace_edit", |c| async move { undo_workspace_edit(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("lsp_execute_command", |c| async move {
|
||||
lsp_execute_command(&c.host, &c.window, c.arg("doc")?, c.arg("command")?).await
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ pub mod notebook;
|
||||
pub mod project;
|
||||
mod python;
|
||||
pub mod refactor;
|
||||
pub mod routes;
|
||||
pub mod run;
|
||||
pub mod sdk;
|
||||
pub mod search;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! File move / rename refactoring: reference updates from the language
|
||||
//! servers, the move itself (one undoable step) and its undo.
|
||||
use crate::Host;
|
||||
use crate::apply_workspace_edit;
|
||||
use crate::rpc::Dispatcher;
|
||||
|
||||
use ide_core::{IdeResult, RequestId, WorkspaceEdit};
|
||||
@@ -25,12 +26,7 @@ pub async fn refactor_file_move_edits(
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
blocking(move || {
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
result
|
||||
}
|
||||
|
||||
/// Applies `edit` (from [`refactor_file_move_edits`], possibly empty), moves the
|
||||
@@ -46,7 +42,7 @@ pub async fn refactor_move_files(
|
||||
let p = project.clone();
|
||||
let moved = moves.clone();
|
||||
let id = blocking(move || {
|
||||
let apply = |e: &WorkspaceEdit| p.documents.apply_file_move_edits(e);
|
||||
let apply = |e: &WorkspaceEdit| apply_workspace_edit(&p.documents, e);
|
||||
p.moves.perform(&p.documents, Some(&p.history), &moved, &edit, &label, &apply)
|
||||
})
|
||||
.await?;
|
||||
@@ -81,17 +77,13 @@ pub async fn refactor_file_move_text_edits(
|
||||
let cancel = token.clone();
|
||||
let result = blocking(move || {
|
||||
let replacements = ide_workspace::text_refs::move_replacements(&project.root, &project.roots(), &moves);
|
||||
let mut edit = ide_workspace::text_refs::find_text_occurrences(
|
||||
let edit = ide_workspace::text_refs::find_text_occurrences(
|
||||
&project.root,
|
||||
&project.exclude_globs(),
|
||||
&replacements,
|
||||
&|| cancel.is_cancelled(),
|
||||
);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
if cancel.is_cancelled() { Err(ide_core::IdeError::cancelled()) } else { Ok(edit) }
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
//! Spring Web mappings, source side: the project's Java and Kotlin files that could
|
||||
//! declare a route, with their text. The UI owns the annotation parser and the index
|
||||
//! it feeds, so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Files handed out at most, and bytes in total: a project's controllers fit well
|
||||
/// inside these, and the UI indexes them once.
|
||||
const MAX_FILES: usize = 1024;
|
||||
const MAX_BYTES: usize = 48 << 20;
|
||||
/// A single source bigger than this is not a controller.
|
||||
const MAX_FILE_BYTES: u64 = 4 << 20;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RouteSource {
|
||||
pub path: String,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The files Spring mappings can live in: Java and Kotlin sources.
|
||||
fn declares_mappings(path: &Path) -> bool {
|
||||
matches!(path.extension().and_then(|e| e.to_str()), Some("java" | "kt" | "kts"))
|
||||
}
|
||||
|
||||
/// Files under `root` whose text names a mapping: `ignore` rules and `excludes`
|
||||
/// decide what counts, and the UI ranks the matches itself.
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<RouteSource> {
|
||||
let found: Mutex<Vec<RouteSource>> = Mutex::new(Vec::new());
|
||||
let bytes = AtomicUsize::new(0);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !declares_mappings(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
// Only a file that names a mapping annotation is worth parsing.
|
||||
if !text.contains("Mapping") {
|
||||
return;
|
||||
}
|
||||
let Ok(mut found) = found.lock() else { return };
|
||||
if found.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
bytes.fetch_add(text.len(), Ordering::Relaxed);
|
||||
found.push(RouteSource { path: path.to_string_lossy().into_owned(), text });
|
||||
});
|
||||
let mut files = found.into_inner().unwrap_or_default();
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
files
|
||||
}
|
||||
|
||||
/// The folders to scan: the project folder itself first, then content roots outside it
|
||||
/// (`content_roots` lists only the ones outside, so the project folder is never implied —
|
||||
/// forgetting it scans nothing).
|
||||
fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots);
|
||||
roots
|
||||
}
|
||||
|
||||
/// Every mapping source of the project, for the request-path index.
|
||||
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
let excludes = project.search_excludes();
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &excludes));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?} (excludes: {})", project.root, excludes.len()),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_project_folder_is_scanned_even_without_other_content_roots() {
|
||||
let root = Path::new("/p/demo");
|
||||
assert_eq!(scan_roots(root, Vec::new()), [PathBuf::from("/p/demo")]);
|
||||
assert_eq!(
|
||||
scan_roots(root, vec![PathBuf::from("/p/elsewhere")]),
|
||||
[PathBuf::from("/p/demo"), PathBuf::from("/p/elsewhere")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_java_and_kotlin_sources_are_read() {
|
||||
for (name, expected) in
|
||||
[("A.java", true), ("B.kt", true), ("C.kts", true), ("D.txt", false), ("pom.xml", false), ("noext", false)]
|
||||
{
|
||||
assert_eq!(declares_mappings(Path::new(name)), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_name_no_mapping_are_left_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
|
||||
std::fs::write(tmp.path().join("src/Ctl.java"), "class Ctl { @GetMapping(\"/a\") void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Plain.java"), "class Plain { void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Notes.txt"), "@GetMapping(\"/a\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &[]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(Path::new(&files[0].path).ends_with("src/Ctl.java"), "{}", files[0].path);
|
||||
assert!(files[0].text.contains("@GetMapping"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_folders_are_skipped() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("module/src")).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("build")).unwrap();
|
||||
std::fs::write(tmp.path().join("module/src/A.java"), "@RequestMapping(\"/a\")").unwrap();
|
||||
std::fs::write(tmp.path().join("build/B.java"), "@RequestMapping(\"/b\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(Path::new(&files[0].path).ends_with("module/src/A.java"), "{}", files[0].path);
|
||||
}
|
||||
}
|
||||
@@ -881,7 +881,37 @@ impl Project {
|
||||
|
||||
/// Applies a multi-file edit through the document layer so open editors update live.
|
||||
pub fn apply_workspace_edit(documents: &Documents, edit: &ide_core::WorkspaceEdit) -> IdeResult<()> {
|
||||
documents.apply_workspace_edit(edit)
|
||||
use ide_core::FileEdit;
|
||||
let mut edit = edit.clone();
|
||||
edit.deduplicate();
|
||||
for file in &edit.files {
|
||||
match file {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
// Files not open in an editor are opened transiently and closed again.
|
||||
let (doc, transient) = match documents.by_path(path) {
|
||||
Some(doc) => (doc, false),
|
||||
None => (documents.open(path)?.id, true),
|
||||
};
|
||||
let result = documents.apply_edits(doc, edits).and_then(|_| documents.save(doc));
|
||||
if transient {
|
||||
documents.close(doc);
|
||||
}
|
||||
result?;
|
||||
}
|
||||
FileEdit::Create { path, overwrite } => {
|
||||
if path.exists() {
|
||||
if *overwrite {
|
||||
ide_vfs::save_text(path, "", "utf-8", false)?;
|
||||
}
|
||||
} else {
|
||||
ide_vfs::create_file(path)?;
|
||||
}
|
||||
}
|
||||
FileEdit::Rename { from, to } => ide_vfs::rename(from, to)?,
|
||||
FileEdit::Delete { path, .. } => ide_vfs::delete(path)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Files the watcher reports per batch that Local History snapshots.
|
||||
@@ -1223,14 +1253,10 @@ mod workspace_edit_tests {
|
||||
let doc = documents.open(&alias).unwrap();
|
||||
let changes = |path: PathBuf| FileEdit::Edit {
|
||||
path: path.into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() }],
|
||||
};
|
||||
apply_workspace_edit(
|
||||
&documents,
|
||||
&WorkspaceEdit { files: vec![changes(real.clone()), changes(alias)], ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
apply_workspace_edit(&documents, &WorkspaceEdit { files: vec![changes(real.clone()), changes(alias)] })
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(real).unwrap(), "sum_values();\n");
|
||||
assert_eq!(documents.snapshot(doc.id).unwrap().text, "sum_values();\n");
|
||||
}
|
||||
|
||||
@@ -215,14 +215,9 @@ impl Dispatcher {
|
||||
})
|
||||
.add("fs_read_text", |c| async move { ops::fs::read_text(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_open", |c| async move { ops::doc::open(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_close", |c| async move {
|
||||
ops::doc::blocking(move || ops::doc::close(&c.host, &c.window, c.arg("doc")?)).await
|
||||
})
|
||||
.add("doc_close", |c| async move { ops::doc::close(&c.host, &c.window, c.arg("doc")?) })
|
||||
.add("doc_edit", |c| async move {
|
||||
ops::doc::blocking(move || {
|
||||
ops::doc::edit(&c.host, &c.window, c.arg("doc")?, c.arg("baseVersion")?, c.arg("changes")?)
|
||||
})
|
||||
.await
|
||||
ops::doc::edit(&c.host, &c.window, c.arg("doc")?, c.arg("baseVersion")?, c.arg("changes")?)
|
||||
})
|
||||
.add("doc_save", |c| async move { ops::doc::save(&c.host, &c.window, c.arg("doc")?).await })
|
||||
.add("doc_save_all", |c| async move { ops::doc::save_all(&c.host, &c.window).await })
|
||||
|
||||
@@ -209,10 +209,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "menu_model"
|
||||
| "menu_configure"
|
||||
| "menu_set_disabled"
|
||||
| "prepare_workspace_edit"
|
||||
| "apply_workspace_edit"
|
||||
| "undo_workspace_edit"
|
||||
| "redo_workspace_edit"
|
||||
| "lsp_servers"
|
||||
| "lsp_resend_diagnostics"
|
||||
| "recent_projects"
|
||||
|
||||
@@ -88,40 +88,6 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
assert!(peer.request::<_, Value>("invoke", call, None).await.is_err());
|
||||
// Manual workspace edits remain available in Restricted Mode, like doc/fs
|
||||
// editing. They do not ask a language server to execute project commands.
|
||||
let manual = project.join("src/manual.txt");
|
||||
std::fs::write(&manual, "old").unwrap();
|
||||
let edit = json!({ "files": [{ "kind": "edit", "path": manual, "edits": [{
|
||||
"range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } },
|
||||
"new_text": "new"
|
||||
}] }] });
|
||||
let edit = invoke(&peer, "prepare_workspace_edit", json!({ "edit": edit })).await.unwrap();
|
||||
assert_eq!(edit["preconditions"].as_array().unwrap().len(), 1);
|
||||
invoke(&peer, "apply_workspace_edit", json!({ "edit": edit })).await.unwrap();
|
||||
until("workspace edit history", || {
|
||||
client.events.lock().iter().any(|event| matches!(event.event, ide_core::IdeEvent::WorkspaceEditApplied { .. }))
|
||||
})
|
||||
.await;
|
||||
let undo_id = client
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match &event.event {
|
||||
ide_core::IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "new");
|
||||
invoke(&peer, "undo_workspace_edit", json!({ "id": undo_id })).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "old");
|
||||
invoke(&peer, "redo_workspace_edit", json!({ "id": undo_id })).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "new");
|
||||
assert_eq!(invoke(&peer, "project_current", json!({})).await.unwrap()["trusted"], false);
|
||||
for command in ["lsp_execute_command", "lsp_apply_code_action"] {
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
invoke(&peer, "project_trust_set", json!({"path": project, "trusted": true, "folder": false})).await.unwrap();
|
||||
let current = invoke(&peer, "project_current", json!({})).await.unwrap();
|
||||
assert_eq!(current["name"], "demo");
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
use ide_core::{IdeEvent, SharedSink, WorkspaceEdit, error::ErrorKind};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn preview_apply_and_grouped_undo_use_the_shared_host_commands() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let second = tmp.path().join("second.txt");
|
||||
for path in [&first, &second] {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
}
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
};
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("local-data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |_| sink.clone()),
|
||||
owner: |window| window,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.open_light("main", &first).unwrap();
|
||||
let info = ops::doc::open(&host, "main", first.clone()).await.unwrap();
|
||||
let edit: WorkspaceEdit = serde_json::from_value(json!({ "files": [
|
||||
{ "kind": "edit", "path": first, "version": info.version, "edits": [{ "range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } }, "new_text": "new" }] },
|
||||
{ "kind": "edit", "path": second, "edits": [{ "range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } }, "new_text": "new" }] }
|
||||
] })).unwrap();
|
||||
let preview = ops::lsp::prepare_workspace_edit(&host, "main", edit.clone()).await.unwrap();
|
||||
assert_eq!(preview.preconditions.len(), 2);
|
||||
std::fs::write(&second, "own\n").unwrap();
|
||||
let error = ops::lsp::apply_workspace_edit(&host, "main", preview).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
|
||||
let preview = ops::lsp::prepare_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
ops::lsp::apply_workspace_edit(&host, "main", preview).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "new\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "new\n");
|
||||
let id = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "own\n");
|
||||
assert_eq!(ops::doc::snapshot(&host, "main", info.id).await.unwrap().text, "old\n");
|
||||
ops::lsp::redo_workspace_edit(&host, "main", id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "new\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "new\n");
|
||||
host.clear_workspace_edit_history_on_exit();
|
||||
assert_eq!(ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn contended_version_reads_do_not_block_the_async_worker() {
|
||||
use ide_core::{LanguageId, Pos, Range, RequestId};
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct PausedWrite {
|
||||
entered: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
|
||||
release: Mutex<mpsc::Receiver<()>>,
|
||||
}
|
||||
impl DocumentObserver for PausedWrite {
|
||||
fn changed(
|
||||
&self,
|
||||
_: ide_core::DocId,
|
||||
_: &std::path::Path,
|
||||
_: u32,
|
||||
_: &[ide_text::AppliedChange],
|
||||
_: &dyn Fn() -> String,
|
||||
) {
|
||||
if let Some(entered) = self.entered.lock().take() {
|
||||
let _ = entered.send(());
|
||||
self.release.lock().recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for request_kind in 0..5 {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("main.txt");
|
||||
std::fs::write(&file, "old").unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("local-data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |window| window,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
let project = host.open_light("main", &file).unwrap();
|
||||
let doc = project.documents.open(&file).unwrap().id;
|
||||
assert_eq!(project.documents.snapshot(doc).unwrap().language, LanguageId::plain_text());
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
project.documents.add_observer(Arc::new(PausedWrite {
|
||||
entered: Mutex::new(Some(entered_tx)),
|
||||
release: Mutex::new(release_rx),
|
||||
}));
|
||||
let documents = project.documents.clone();
|
||||
let writer = std::thread::spawn(move || {
|
||||
documents
|
||||
.apply_workspace_edit(
|
||||
&serde_json::from_value(json!({ "files": [{
|
||||
"kind": "edit", "path": file, "edits": [{ "range": {
|
||||
"start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 }
|
||||
}, "new_text": "new" }]
|
||||
}] }))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
entered_rx.await.unwrap();
|
||||
let (heartbeat_tx, heartbeat_rx) = mpsc::channel();
|
||||
// Always release the writer, even on the old blocking implementation.
|
||||
let watchdog = std::thread::spawn(move || {
|
||||
let responsive = heartbeat_rx.recv_timeout(Duration::from_secs(2)).is_ok();
|
||||
release_tx.send(()).unwrap();
|
||||
responsive
|
||||
});
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
let _ = started_tx.send(());
|
||||
let action =
|
||||
|| serde_json::from_value(json!({ "title": "test", "isPreferred": false, "server": 1 })).unwrap();
|
||||
match request_kind {
|
||||
0 => {
|
||||
let _ = ops::lsp::lsp_code_actions(&host, "main", doc, Range::point(Pos::new(0, 0)), vec![]).await;
|
||||
}
|
||||
1 => {
|
||||
let _ = ops::lsp::lsp_code_action_query(
|
||||
&host,
|
||||
"main",
|
||||
RequestId(1),
|
||||
doc,
|
||||
Range::point(Pos::new(0, 0)),
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
2 => {
|
||||
let _ = ops::lsp::lsp_resolve_code_action(&host, "main", doc, action()).await;
|
||||
}
|
||||
3 => {
|
||||
let _ = ops::lsp::lsp_apply_code_action(&host, "main", doc, action()).await;
|
||||
}
|
||||
_ => {
|
||||
let _ =
|
||||
ops::lsp::lsp_rename(&host, "main", RequestId(1), doc, Pos::new(0, 0), "other".into()).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
let _ = heartbeat_tx.send(());
|
||||
task.await.unwrap();
|
||||
writer.join().unwrap();
|
||||
assert!(watchdog.join().unwrap(), "request {request_kind} blocked the only async worker");
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ mod syntax;
|
||||
pub use markers::marked_root;
|
||||
pub use registry::{FileTypes, LanguageRegistry};
|
||||
pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, FileReference, Literal, LiteralKind, MAX_CACHED_TREES,
|
||||
MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats,
|
||||
SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
|
||||
ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
|
||||
SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
@@ -96,9 +96,7 @@ pub struct LanguageServerConfig {
|
||||
pub args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`;
|
||||
/// `file#table` requires the TOML file to contain that dotted table, e.g.
|
||||
/// `pyproject.toml#tool.ruff`.
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`.
|
||||
#[serde(default)]
|
||||
pub root_markers: Vec<String>,
|
||||
/// Serve only files below a root marker, not the whole project: a framework's
|
||||
|
||||
@@ -19,13 +19,9 @@ pub fn marked_root(project_root: Option<&Path>, file: &Path, markers: &[String])
|
||||
best
|
||||
}
|
||||
|
||||
/// `dir` contains `marker`: a relative path, a file name pattern with one
|
||||
/// `*` (`*.csproj`), or a TOML file name (no pattern) and a dotted table it
|
||||
/// must contain (`pyproject.toml#tool.ruff`).
|
||||
/// `dir` contains `marker`: a relative path, or a file name pattern with one
|
||||
/// `*` (`*.csproj`).
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
if let Some((file, table)) = marker.split_once('#') {
|
||||
return has_toml_table(&dir.join(file), table);
|
||||
}
|
||||
let Some((prefix, suffix)) = marker.split_once('*') else {
|
||||
return dir.join(marker).exists();
|
||||
};
|
||||
@@ -34,23 +30,9 @@ fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// `file` parses as TOML and has the dotted `table` (`tool.ruff`).
|
||||
fn has_toml_table(file: &Path, table: &str) -> bool {
|
||||
let Ok(text) = std::fs::read_to_string(file) else { return false };
|
||||
let value = match toml::from_str::<toml::Value>(&text) {
|
||||
Ok(value) => value,
|
||||
Err(e) => {
|
||||
tracing::debug!("root marker {}: {e}", file.display());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
/// directory above it.
|
||||
pub(crate) fn is_marker_path(path: &Path, marker: &str) -> bool {
|
||||
let marker = marker.split_once('#').map_or(marker, |(file, _)| file);
|
||||
match marker.split_once('*') {
|
||||
None => path.ends_with(marker),
|
||||
Some((prefix, suffix)) => {
|
||||
@@ -92,29 +74,6 @@ mod tests {
|
||||
assert_eq!(marked_root(None, &file, &markers), Some(home.to_path_buf()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toml_markers_need_their_table() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("svc/app/main.py");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["ruff.toml".to_string(), "pyproject.toml#tool.ruff".to_string()];
|
||||
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"x\"\n[tool.black]\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), None);
|
||||
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff.lint]\nselect = [\"E\"]\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
// Outermost wins: an inline table counts; a value that is no table, or a
|
||||
// file that does not parse, does not.
|
||||
std::fs::write(root.join("pyproject.toml"), "tool = { ruff = { line-length = 100 } }\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.to_path_buf()));
|
||||
std::fs::write(root.join("pyproject.toml"), "tool = { ruff = 1 }\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.ruff]\n[broken").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
assert!(is_marker_path(&root.join("svc/pyproject.toml"), "pyproject.toml#tool.ruff"));
|
||||
assert!(!is_marker_path(&root.join("svc/setup.cfg"), "pyproject.toml#tool.ruff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_match_file_names() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -604,32 +604,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_serves_python_files_only_below_its_config() {
|
||||
let reg = reg();
|
||||
let cfg = reg.get(&LanguageId::new("python")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallbacks: hover, rename and symbols stay with the type checker.
|
||||
assert_eq!(names, ["basedpyright", "pyright", "ty", "ruff"]);
|
||||
let ruff = cfg.language_servers.iter().find(|s| s.name == "ruff").unwrap();
|
||||
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", ["server".to_string()].as_slice()));
|
||||
assert!(ruff.require_root_marker && !ruff.fallback);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["lint", "dot", "pyproject", "plain"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("lint/ruff.toml"), "").unwrap();
|
||||
std::fs::write(root.join("dot/.ruff.toml"), "").unwrap();
|
||||
std::fs::write(root.join("pyproject/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
|
||||
std::fs::write(root.join("plain/pyproject.toml"), "[project]\nname = \"plain\"\n").unwrap();
|
||||
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &ruff.root_markers);
|
||||
for dir in ["lint", "dot", "pyproject"] {
|
||||
assert_eq!(served(&format!("{dir}/pkg/main.py")), Some(root.join(dir)), "{dir}");
|
||||
}
|
||||
assert_eq!(served("plain/main.py"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_of_angular_projects_is_an_angular_template() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
//! Source ranges for Spring-style configuration keys. This is a syntax index,
|
||||
//! not a YAML evaluator: aliases, merge keys and runtime profile precedence are
|
||||
//! intentionally left to the YAML server / application.
|
||||
use super::lines::LineIndex;
|
||||
use super::{ParsedTree, Syntax, TreeError};
|
||||
use ide_core::{LanguageId, Range};
|
||||
use tree_sitter::Node;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConfigurationKey {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
pub fn configuration_keys(
|
||||
&self,
|
||||
language: &LanguageId,
|
||||
text: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Vec<ConfigurationKey>, TreeError> {
|
||||
if language.as_str() == "properties" {
|
||||
return Ok(properties(text));
|
||||
}
|
||||
self.with_parsed(language, text, cancelled, |tree| tree.configuration_keys(cancelled))
|
||||
}
|
||||
}
|
||||
|
||||
impl ParsedTree<'_> {
|
||||
pub fn configuration_keys(&self, cancelled: &dyn Fn() -> bool) -> Vec<ConfigurationKey> {
|
||||
let mut out = Vec::new();
|
||||
if self.grammar == "yaml" {
|
||||
yaml(self.tree.root_node(), "", self.text, &LineIndex::new(self.text), &mut out, cancelled, 0);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn yaml(
|
||||
node: Node<'_>,
|
||||
prefix: &str,
|
||||
text: &str,
|
||||
lines: &LineIndex<'_>,
|
||||
out: &mut Vec<ConfigurationKey>,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
depth: usize,
|
||||
) {
|
||||
if depth > 64 || cancelled() || out.len() >= 20_000 {
|
||||
return;
|
||||
}
|
||||
match node.kind() {
|
||||
"block_mapping_pair" | "flow_pair" => {
|
||||
let Some(key) = node.child_by_field_name("key") else { return };
|
||||
let raw = &text[key.byte_range()];
|
||||
if raw.contains('\n') {
|
||||
return;
|
||||
}
|
||||
let name = if raw.starts_with('\'') && raw.ends_with('\'') {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else if raw.starts_with('"') {
|
||||
// JSON escapes cover ordinary quoted configuration keys. Unsupported
|
||||
// YAML-only escapes are skipped rather than indexed under a wrong key.
|
||||
let Ok(name) = serde_json::from_str::<String>(raw) else { return };
|
||||
name
|
||||
} else {
|
||||
if raw.contains(['\n', '{', '[', '*', '&', '!']) || raw == "<<" {
|
||||
return;
|
||||
}
|
||||
raw.to_owned()
|
||||
};
|
||||
if name.is_empty() {
|
||||
return;
|
||||
}
|
||||
let name = if prefix.is_empty() {
|
||||
name
|
||||
} else if name.starts_with('[') {
|
||||
format!("{prefix}{name}")
|
||||
} else {
|
||||
format!("{prefix}.{name}")
|
||||
};
|
||||
if name.len() > 1024 {
|
||||
return;
|
||||
}
|
||||
out.push(ConfigurationKey { name: name.clone(), range: lines.range(key.start_byte(), key.end_byte()) });
|
||||
if let Some(value) = node.child_by_field_name("value") {
|
||||
yaml(value, &name, text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
"block_sequence" | "flow_sequence" => {
|
||||
let mut cursor = node.walk();
|
||||
for (i, child) in node.named_children(&mut cursor).filter(|n| n.kind() != "comment").enumerate() {
|
||||
yaml(child, &format!("{prefix}[{i}]"), text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
// Do not descend into scalars, anchors or aliases.
|
||||
"stream"
|
||||
| "document"
|
||||
| "block_node"
|
||||
| "flow_node"
|
||||
| "block_mapping"
|
||||
| "flow_mapping"
|
||||
| "block_sequence_item" => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
yaml(child, prefix, text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn properties(text: &str) -> Vec<ConfigurationKey> {
|
||||
let lines = LineIndex::new(text);
|
||||
let mut out = Vec::new();
|
||||
let mut logical = String::new();
|
||||
let mut offsets = Vec::new();
|
||||
let mut base = 0;
|
||||
for line in text.split_inclusive('\n') {
|
||||
let physical = line.trim_end_matches(['\r', '\n']);
|
||||
let start = physical.len() - physical.trim_start_matches([' ', '\t', '\u{c}']).len();
|
||||
let slice = &physical[start..];
|
||||
if logical.is_empty() && (slice.is_empty() || slice.starts_with(['#', '!'])) {
|
||||
base += line.len();
|
||||
continue;
|
||||
}
|
||||
let continued = slice.bytes().rev().take_while(|b| *b == b'\\').count() % 2 == 1;
|
||||
let end = physical.len() - usize::from(continued);
|
||||
for (i, ch) in physical[start..end].char_indices() {
|
||||
offsets.extend((0..ch.len_utf8()).map(|byte| base + start + i + byte));
|
||||
logical.push(ch);
|
||||
}
|
||||
if !continued || base + line.len() == text.len() {
|
||||
let mut escaped = false;
|
||||
let key_end = logical
|
||||
.char_indices()
|
||||
.find_map(|(i, ch)| {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
return None;
|
||||
}
|
||||
if ch == '\\' {
|
||||
escaped = true;
|
||||
return None;
|
||||
}
|
||||
matches!(ch, '=' | ':' | ' ' | '\t' | '\u{c}').then_some(i)
|
||||
})
|
||||
.unwrap_or(logical.len());
|
||||
if key_end > 0
|
||||
&& key_end <= 1024
|
||||
&& let Some(name) = unescape_property(&logical[..key_end])
|
||||
{
|
||||
out.push(ConfigurationKey { name, range: lines.range(offsets[0], offsets[key_end - 1] + 1) });
|
||||
}
|
||||
logical.clear();
|
||||
offsets.clear();
|
||||
}
|
||||
base += line.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn unescape_property(raw: &str) -> Option<String> {
|
||||
let mut chars = raw.chars();
|
||||
let mut out = String::new();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch != '\\' {
|
||||
out.push(ch);
|
||||
continue;
|
||||
}
|
||||
match chars.next()? {
|
||||
'u' => {
|
||||
let hex: String = chars.by_ref().take(4).collect();
|
||||
if hex.len() != 4 {
|
||||
return None;
|
||||
}
|
||||
out.push(char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?);
|
||||
}
|
||||
't' => out.push('\t'),
|
||||
'n' => out.push('\n'),
|
||||
'r' => out.push('\r'),
|
||||
'f' => out.push('\u{c}'),
|
||||
ch => out.push(ch),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn yaml_structures_and_utf16() {
|
||||
let text = "app:\n 'time-out': 1\n hosts:\n - url: a\n - {url: b}\n map: {east: {size: 2}}\n---\n\"app.name\": ok\n'😀': {port: 3}\n";
|
||||
let keys = Syntax::new().configuration_keys(&LanguageId::new("yaml"), text, &|| false).unwrap();
|
||||
let names: Vec<_> = keys.iter().map(|k| k.name.as_str()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"app",
|
||||
"app.time-out",
|
||||
"app.hosts",
|
||||
"app.hosts[0].url",
|
||||
"app.hosts[1].url",
|
||||
"app.map",
|
||||
"app.map.east",
|
||||
"app.map.east.size",
|
||||
"app.name",
|
||||
"😀",
|
||||
"😀.port"
|
||||
]
|
||||
);
|
||||
assert_eq!(keys.last().unwrap().range.start.col, 7);
|
||||
}
|
||||
#[test]
|
||||
fn aliases_and_values_are_not_configuration_keys() {
|
||||
let keys = Syntax::new()
|
||||
.configuration_keys(
|
||||
&LanguageId::new("yaml"),
|
||||
"base: &base {size: 1}\napp:\n <<: *base\n text: |\n fake: key\n",
|
||||
&|| false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(keys.iter().map(|k| k.name.as_str()).collect::<Vec<_>>(), ["base", "base.size", "app", "app.text"]);
|
||||
}
|
||||
#[test]
|
||||
fn properties_unicode_ranges_and_eof_continuation() {
|
||||
let keys = properties("app.中文=1\nlast\\\n");
|
||||
assert_eq!(keys[0].range.end.col, 6);
|
||||
assert_eq!(keys[1].name, "last");
|
||||
}
|
||||
#[test]
|
||||
fn properties_escapes_continuations_and_comments() {
|
||||
let keys = properties(
|
||||
"# comment\r\napp.time\\\n -out : 1\napp\\.name=ok\napp.\\u0061=2\nspace\\ key value\n!ignored=x\n",
|
||||
);
|
||||
assert_eq!(
|
||||
keys.iter().map(|k| k.name.as_str()).collect::<Vec<_>>(),
|
||||
["app.time-out", "app.name", "app.a", "space key"]
|
||||
);
|
||||
assert_eq!(keys[0].range.end.line, 2);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
|
||||
mod cache;
|
||||
mod configuration;
|
||||
mod folding;
|
||||
mod grammars;
|
||||
mod highlight;
|
||||
@@ -13,7 +12,6 @@ mod web;
|
||||
|
||||
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
|
||||
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
|
||||
pub use configuration::ConfigurationKey;
|
||||
use grammars::{SPECS, Spec};
|
||||
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
|
||||
use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
|
||||
@@ -621,7 +621,7 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
})
|
||||
.map(|e| conv.text_edit(&path, e))
|
||||
.collect();
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version: e.text_document.version });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits });
|
||||
};
|
||||
if let Some(changes) = e.document_changes {
|
||||
match changes {
|
||||
@@ -657,11 +657,11 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
for (uri, edits) in changes {
|
||||
if let Some(path) = uri_path(&uri) {
|
||||
let edits = conv.text_edits(&path, edits);
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version: None });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edit = WorkspaceEdit { files, ..Default::default() };
|
||||
let mut edit = WorkspaceEdit { files };
|
||||
edit.deduplicate();
|
||||
edit
|
||||
}
|
||||
@@ -670,36 +670,28 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
/// `edit` where they leave its own alone: what only the other server sees
|
||||
/// (Angular templates next to vtsls's TypeScript).
|
||||
pub fn merge_workspace_edit(edit: &mut WorkspaceEdit, extra: WorkspaceEdit) {
|
||||
edit.preconditions.extend(extra.preconditions);
|
||||
let overlap =
|
||||
|a: &TextEdit, b: &TextEdit| a.range == b.range || (a.range.start < b.range.end && b.range.start < a.range.end);
|
||||
for file in extra.files {
|
||||
let FileEdit::Edit { path, edits, version } = file else {
|
||||
let FileEdit::Edit { path, edits } = file else {
|
||||
if !edit.files.contains(&file) {
|
||||
edit.files.push(file);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let own = edit.files.iter_mut().find_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits, version } if *p == path => Some((edits, version)),
|
||||
FileEdit::Edit { path: p, edits } if *p == path => Some(edits),
|
||||
_ => None,
|
||||
});
|
||||
match own {
|
||||
Some((own, own_version)) => {
|
||||
// Conflicting versions cannot describe one consistent edit. Keep both
|
||||
// operations so transaction preflight rejects them instead of dropping a guard.
|
||||
if own_version.is_some() && version.is_some() && *own_version != version {
|
||||
edit.files.push(FileEdit::Edit { path, edits, version });
|
||||
continue;
|
||||
}
|
||||
*own_version = own_version.or(version);
|
||||
Some(own) => {
|
||||
let added: Vec<TextEdit> = edits.into_iter().filter(|e| !own.iter().any(|o| overlap(o, e))).collect();
|
||||
if !added.is_empty() {
|
||||
own.extend(added);
|
||||
own.sort_by_key(|e| e.range.start);
|
||||
}
|
||||
}
|
||||
None => edit.files.push(FileEdit::Edit { path, edits, version }),
|
||||
None => edit.files.push(FileEdit::Edit { path, edits }),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1044,20 +1036,16 @@ mod tests {
|
||||
range: Range::new(Pos::new(l, c), Pos::new(l, c + 5)),
|
||||
new_text: text.into(),
|
||||
};
|
||||
let file =
|
||||
|p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits, version: None };
|
||||
let file = |p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits };
|
||||
// vtsls renames a shorthand property with an alias; the Angular server
|
||||
// renames it plainly and adds the template.
|
||||
let mut merged = WorkspaceEdit {
|
||||
files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])],
|
||||
..Default::default()
|
||||
};
|
||||
let mut merged =
|
||||
WorkspaceEdit { files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])] };
|
||||
let angular = WorkspaceEdit {
|
||||
files: vec![
|
||||
file("/a.ts", vec![edit(9, 4, "entries"), edit(3, 2, "entries"), edit(1, 14, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
merge_workspace_edit(&mut merged, angular);
|
||||
assert_eq!(
|
||||
@@ -1318,7 +1306,7 @@ mod tests {
|
||||
assert_eq!(w.files.len(), 4);
|
||||
assert_eq!(w.files[0], FileEdit::Create { path: "/n.rs".into(), overwrite: true });
|
||||
match &w.files[1] {
|
||||
FileEdit::Edit { path, edits, .. } => {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
assert_eq!(path, Path::new("/n.rs"));
|
||||
assert_eq!(edits.len(), 2);
|
||||
assert_eq!(edits[1].new_text, "y");
|
||||
@@ -1334,26 +1322,6 @@ mod tests {
|
||||
assert!(matches!(&workspace_edit(&conv, e).files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "q"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_edits_preserve_document_versions_and_merge_guards() {
|
||||
let conv = Conv::utf16();
|
||||
let incoming = |version| {
|
||||
serde_json::from_value(json!({
|
||||
"documentChanges": [{
|
||||
"textDocument": { "uri": "file:///a.rs", "version": version },
|
||||
"edits": [{ "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } }, "newText": "x" }]
|
||||
}]
|
||||
})).unwrap()
|
||||
};
|
||||
let mut edit = workspace_edit(&conv, incoming(Some(7)));
|
||||
assert!(matches!(edit.files[0], FileEdit::Edit { version: Some(7), .. }));
|
||||
merge_workspace_edit(&mut edit, workspace_edit(&conv, incoming(None::<i32>)));
|
||||
assert!(matches!(edit.files[0], FileEdit::Edit { version: Some(7), .. }));
|
||||
merge_workspace_edit(&mut edit, workspace_edit(&conv, incoming(Some(8))));
|
||||
assert_eq!(edit.files.len(), 2, "inconsistent version guards must not be discarded");
|
||||
assert!(matches!(edit.files[1], FileEdit::Edit { version: Some(8), .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_token_decoding() {
|
||||
let data = [1, 2, 3, 0, 1, 0, 5, 2, 1, 0, 2, 0, 4, 2, 3];
|
||||
|
||||
@@ -18,7 +18,6 @@ use std::time::{Duration, Instant};
|
||||
|
||||
const SERVER: &str = "jdtls";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
mod formatter;
|
||||
pub use formatter::configure_formatter;
|
||||
/// First start imports the Maven / Gradle model, which can take minutes.
|
||||
|
||||
@@ -1,416 +0,0 @@
|
||||
//! Bridges configuration syntax to the app-owned JDT extension. No additional
|
||||
//! language server, build, or network request is needed. Disk parsing runs on a
|
||||
//! blocking worker; open buffers always win over cached disk contents.
|
||||
use super::*;
|
||||
use crate::text::Encoding;
|
||||
use crate::types::{References, ReferencesIncomplete};
|
||||
use crate::{DocSnap, Target};
|
||||
use ide_core::{Location, Pos};
|
||||
use ide_language::{ConfigurationKey, Syntax};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::SystemTime;
|
||||
|
||||
const COMMAND: &str = "openidea.java.configuration";
|
||||
const MAX_BYTES: u64 = 2 * 1024 * 1024;
|
||||
const MAX_FILES: usize = 2000;
|
||||
const MAX_CACHED_KEYS: usize = 100_000;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ConfigurationCache {
|
||||
files: HashMap<PathBuf, CachedFile>,
|
||||
}
|
||||
struct CachedFile {
|
||||
stamp: (SystemTime, u64),
|
||||
keys: Vec<ConfigurationKey>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Pattern {
|
||||
name: String,
|
||||
relaxed: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
locations: Vec<lsp_types::Location>,
|
||||
#[serde(default)]
|
||||
keys: Vec<Pattern>,
|
||||
#[serde(default)]
|
||||
roots: Vec<String>,
|
||||
#[serde(default)]
|
||||
incomplete: bool,
|
||||
}
|
||||
fn syntax() -> &'static Syntax {
|
||||
static SYNTAX: OnceLock<Syntax> = OnceLock::new();
|
||||
SYNTAX.get_or_init(Syntax::new)
|
||||
}
|
||||
fn language(path: &Path) -> Option<LanguageId> {
|
||||
match path.extension()?.to_str()? {
|
||||
"yaml" | "yml" => Some(LanguageId::new("yaml")),
|
||||
"properties" => Some(LanguageId::new("properties")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn parts(key: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut part = String::new();
|
||||
let mut chars = key.chars().peekable();
|
||||
let mut bracket = false;
|
||||
while let Some(ch) = chars.next() {
|
||||
match ch {
|
||||
'[' => {
|
||||
if !part.is_empty() {
|
||||
out.push(std::mem::take(&mut part));
|
||||
}
|
||||
for ch in chars.by_ref() {
|
||||
if ch == ']' {
|
||||
break;
|
||||
}
|
||||
if !matches!(ch, '-' | '_') {
|
||||
part.extend(ch.to_lowercase());
|
||||
}
|
||||
}
|
||||
out.push(std::mem::take(&mut part));
|
||||
bracket = true;
|
||||
}
|
||||
'.' => {
|
||||
if !bracket {
|
||||
out.push(std::mem::take(&mut part));
|
||||
}
|
||||
bracket = false;
|
||||
}
|
||||
'-' | '_' => {}
|
||||
ch => {
|
||||
part.extend(ch.to_lowercase());
|
||||
bracket = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !part.is_empty() {
|
||||
out.push(part);
|
||||
}
|
||||
out
|
||||
}
|
||||
fn matches(pattern: &Pattern, key: &str) -> bool {
|
||||
if !pattern.relaxed {
|
||||
return pattern.name == key;
|
||||
}
|
||||
let (a, b) = (parts(&pattern.name), parts(key));
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a == "*" || *a == b)
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
pub(crate) async fn configuration_navigation(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
pos: Pos,
|
||||
usages: bool,
|
||||
include_declaration: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<References>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let config = language(&snap.path).is_some();
|
||||
if !config && snap.language.as_str() != "java" {
|
||||
return Ok(None);
|
||||
}
|
||||
// Definition in ordinary Java code remains JDT's definition. Reverse
|
||||
// configuration navigation is offered on string expressions; field/config
|
||||
// accessor usages are merged into the ordinary Find Usages response.
|
||||
if !config && !usages {
|
||||
let text = snap.text.as_str();
|
||||
if !text.contains("Value") && !text.contains("getProperty") && !text.contains("getRequiredProperty") {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let key = if config {
|
||||
let text = snap.text.as_str().to_owned();
|
||||
if text.len() as u64 > MAX_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
let lang = language(&snap.path).expect("configuration language");
|
||||
let cancelled = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
syntax()
|
||||
.configuration_keys(&lang, &text, &|| cancelled.is_cancelled())
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.find(|key| key.range.start <= pos && pos < key.range.end)
|
||||
.map(|key| key.name)
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if config && key.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
if config {
|
||||
// Avoid starting a JVM for unrelated YAML (CI, Kubernetes, etc.).
|
||||
let path = snap.path.clone();
|
||||
let root = self.project_root.clone();
|
||||
let java_project = tokio::task::spawn_blocking(move || {
|
||||
path.ancestors().take_while(|p| p.starts_with(&root)).any(|p| {
|
||||
["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"]
|
||||
.iter()
|
||||
.any(|name| p.join(name).is_file())
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !java_project {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let result = self.configuration_query(snap, pos, key, usages, include_declaration, cancel).await;
|
||||
match result {
|
||||
Err(e) if cancel.is_cancelled() || e.kind == ErrorKind::Cancelled => Err(IdeError::cancelled()),
|
||||
Err(e) => {
|
||||
tracing::debug!("Configuration navigation unavailable; retaining native language navigation: {e}");
|
||||
Ok(None)
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn configuration_query(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
pos: Pos,
|
||||
key: Option<String>,
|
||||
usages: bool,
|
||||
include_declaration: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<References>> {
|
||||
let (server, run) = self.jdtls(&snap.path, cancel).await?;
|
||||
if !run.caps.read().commands().iter().any(|command| command == COMMAND) {
|
||||
return Ok(None);
|
||||
}
|
||||
let target = Target { server: server.clone(), run };
|
||||
let position = snap.text.ide_to_lsp(Encoding::Utf16, pos);
|
||||
let response: Response = self
|
||||
.call(
|
||||
&target,
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"command": COMMAND, "arguments": [snap.uri, key, position.line, position.character, usages, include_declaration]
|
||||
}),
|
||||
Some(cancel),
|
||||
crate::LONG_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if response.keys.is_empty() {
|
||||
return Ok(response
|
||||
.incomplete
|
||||
.then(|| References { incomplete: Some(ReferencesIncomplete::FilesSkipped), ..Default::default() }));
|
||||
}
|
||||
let mut result = References {
|
||||
locations: response.locations.iter().filter_map(|l| self.conv(Encoding::Utf16).location(l)).collect(),
|
||||
incomplete: response.incomplete.then_some(ReferencesIncomplete::FilesSkipped),
|
||||
..Default::default()
|
||||
};
|
||||
self.note_virtual(&server, result.locations.iter().map(|l| l.uri.as_deref()));
|
||||
if key.is_none() || usages {
|
||||
let roots: Vec<PathBuf> = response.roots.iter().filter_map(|uri| super::project_path(uri)).collect();
|
||||
let overlays: HashMap<PathBuf, String> = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.filter(|d| language(&d.path).is_some() && d.text.as_str().len() as u64 <= MAX_BYTES)
|
||||
.map(|d| (d.canonical.clone(), d.text.as_str().to_owned()))
|
||||
.collect();
|
||||
let cache = self.configuration_cache.clone();
|
||||
let cancelled = cancel.clone();
|
||||
let keys = response.keys;
|
||||
let files =
|
||||
tokio::task::spawn_blocking(move || configuration_files(&roots, &keys, &overlays, &cache, &cancelled))
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("configuration search worker stopped"))?;
|
||||
result.locations.extend(files.locations);
|
||||
result.incomplete = result.incomplete.or(files.incomplete);
|
||||
}
|
||||
if cancel.is_cancelled() || !self.docs.lock().values().any(|d| d.uri == snap.uri && d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if usages && key.is_some() && !include_declaration {
|
||||
let source_path = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.find(|d| d.uri == snap.uri)
|
||||
.map(|d| d.canonical.clone())
|
||||
.unwrap_or_else(|| snap.path.clone());
|
||||
result.locations.retain(|location| {
|
||||
location.path.to_path_buf() != source_path || !(location.range.start <= pos && pos < location.range.end)
|
||||
});
|
||||
}
|
||||
crate::convert::dedup_locations(&mut result.locations);
|
||||
Ok(Some(result))
|
||||
}
|
||||
}
|
||||
|
||||
fn in_module(root: &Path, path: &Path) -> bool {
|
||||
if !path.starts_with(root) {
|
||||
return false;
|
||||
}
|
||||
for parent in path.parent().into_iter().flat_map(Path::ancestors).take_while(|p| *p != root) {
|
||||
if matches!(
|
||||
parent.file_name().and_then(|n| n.to_str()),
|
||||
Some("target" | "build" | "node_modules" | ".git" | ".gradle")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"].iter().any(|name| parent.join(name).is_file())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn configuration_files(
|
||||
roots: &[PathBuf],
|
||||
patterns: &[Pattern],
|
||||
overlays: &HashMap<PathBuf, String>,
|
||||
cache: &Mutex<ConfigurationCache>,
|
||||
cancel: &CancellationToken,
|
||||
) -> References {
|
||||
let mut result = References::default();
|
||||
let mut paths = std::collections::BTreeSet::new();
|
||||
// Do not scan a source root twice when its enclosing module is also present.
|
||||
let roots: Vec<_> =
|
||||
roots.iter().filter(|root| !roots.iter().any(|other| other != *root && root.starts_with(other))).collect();
|
||||
for root in &roots {
|
||||
let module = (*root).clone();
|
||||
let walker = ignore::WalkBuilder::new(root)
|
||||
.follow_links(false)
|
||||
.filter_entry(move |entry| {
|
||||
if !entry.file_type().is_some_and(|t| t.is_dir()) {
|
||||
return true;
|
||||
}
|
||||
if entry.path() == module {
|
||||
return true;
|
||||
}
|
||||
if matches!(entry.file_name().to_str(), Some("target" | "build" | "node_modules" | ".git" | ".gradle"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// A sibling application's identical key must not leak into this module.
|
||||
!["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"]
|
||||
.iter()
|
||||
.any(|name| entry.path().join(name).is_file())
|
||||
})
|
||||
.build();
|
||||
for (visited, entry) in walker.enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return result;
|
||||
}
|
||||
if visited >= 50_000 || paths.len() >= MAX_FILES {
|
||||
result.incomplete = Some(ReferencesIncomplete::TooManyFiles);
|
||||
break;
|
||||
}
|
||||
match entry {
|
||||
Ok(entry) if entry.file_type().is_some_and(|t| t.is_file()) && language(entry.path()).is_some() => {
|
||||
paths.insert(entry.into_path());
|
||||
}
|
||||
Err(_) => result.incomplete = Some(ReferencesIncomplete::FilesSkipped),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
paths.extend(overlays.keys().filter(|p| roots.iter().any(|r| in_module(r, p))).cloned());
|
||||
let mut cache = cache.lock();
|
||||
if cache.files.len() > MAX_FILES {
|
||||
cache.files.clear();
|
||||
}
|
||||
for path in paths {
|
||||
if cancel.is_cancelled() {
|
||||
return result;
|
||||
}
|
||||
let lang = language(&path).expect("configuration file");
|
||||
let keys = if let Some(text) = overlays.get(&path) {
|
||||
syntax().configuration_keys(&lang, text, &|| cancel.is_cancelled()).ok()
|
||||
} else {
|
||||
(|| {
|
||||
let metadata = std::fs::metadata(&path).ok()?;
|
||||
if metadata.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let stamp = (metadata.modified().ok()?, metadata.len());
|
||||
if let Some(file) = cache.files.get(&path).filter(|f| f.stamp == stamp) {
|
||||
return Some(file.keys.clone());
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).ok()?;
|
||||
let keys = syntax().configuration_keys(&lang, &text, &|| cancel.is_cancelled()).ok()?;
|
||||
cache.files.remove(&path);
|
||||
if cache.files.len() >= MAX_FILES
|
||||
|| cache.files.values().map(|file| file.keys.len()).sum::<usize>() + keys.len() > MAX_CACHED_KEYS
|
||||
{
|
||||
cache.files.clear();
|
||||
}
|
||||
cache.files.insert(path.clone(), CachedFile { stamp, keys: keys.clone() });
|
||||
Some(keys)
|
||||
})()
|
||||
};
|
||||
match keys {
|
||||
Some(keys) => result.locations.extend(
|
||||
keys.into_iter()
|
||||
.filter(|key| patterns.iter().any(|p| matches(p, &key.name)))
|
||||
.map(|key| Location::file(path.clone(), key.range)),
|
||||
),
|
||||
None => result.incomplete = Some(ReferencesIncomplete::FilesSkipped),
|
||||
}
|
||||
if result.locations.len() >= MAX_FILES {
|
||||
result.locations.truncate(MAX_FILES);
|
||||
result.incomplete = Some(ReferencesIncomplete::TooManyFiles);
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn file_cache_tracks_edits_overlays_removals_and_limits() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().to_path_buf();
|
||||
let file = root.join("application.properties");
|
||||
std::fs::write(&file, "app.port=1\n").unwrap();
|
||||
let patterns = [Pattern { name: "app.port".into(), relaxed: true }];
|
||||
let cache = Mutex::new(ConfigurationCache::default());
|
||||
let cancel = CancellationToken::new();
|
||||
let query = |overlays: &HashMap<PathBuf, String>| {
|
||||
configuration_files(std::slice::from_ref(&root), &patterns, overlays, &cache, &cancel)
|
||||
};
|
||||
assert_eq!(query(&HashMap::new()).locations.len(), 1);
|
||||
std::fs::write(&file, "app.other=12\n").unwrap();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
assert_eq!(query(&HashMap::from([(file.clone(), "app.port=unsaved\n".into())])).locations.len(), 1);
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
std::fs::write(&file, "x".repeat(MAX_BYTES as usize + 1)).unwrap();
|
||||
assert_eq!(query(&HashMap::new()).incomplete, Some(ReferencesIncomplete::FilesSkipped));
|
||||
cancel.cancel();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relaxed_binding_keeps_boundaries() {
|
||||
let pattern = Pattern { name: "app.clients[*].timeOut".into(), relaxed: true };
|
||||
assert!(matches(&pattern, "app.clients[2].time-out"));
|
||||
assert!(!matches(&pattern, "app.clientsTimeOut"));
|
||||
let map = Pattern { name: "app.routes.*.url".into(), relaxed: true };
|
||||
assert!(matches(&map, "app.routes[us.east].url"));
|
||||
assert!(!matches(&map, "app.routes.us.east.url"));
|
||||
assert!(!matches(&Pattern { name: "app.time-out".into(), relaxed: false }, "app.timeOut"));
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,6 @@ pub struct LspManager {
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
java_usages_warned: AtomicBool,
|
||||
configuration_cache: Arc<Mutex<jdtls::configuration::ConfigurationCache>>,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
shown_messages: Mutex<HashSet<(String, String)>>,
|
||||
/// Virtual (non-`file:`) URIs a server returned, by the server that owns them.
|
||||
@@ -314,7 +313,6 @@ impl LspManager {
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
java_usages_warned: AtomicBool::new(false),
|
||||
configuration_cache: Arc::new(Mutex::new(Default::default())),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
virtual_origins: Mutex::new(HashMap::new()),
|
||||
virtual_docs: Mutex::new(HashMap::new()),
|
||||
@@ -1124,15 +1122,6 @@ impl LspManager {
|
||||
}
|
||||
|
||||
pub async fn goto(&self, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
|
||||
if matches!(kind, GotoKind::Definition) {
|
||||
let snap = self.snapshot(doc)?;
|
||||
if let Some(result) =
|
||||
self.configuration_navigation(&snap, pos, false, false, &CancellationToken::new()).await?
|
||||
&& !result.locations.is_empty()
|
||||
{
|
||||
return Ok(result.locations);
|
||||
}
|
||||
}
|
||||
let (method, cap, feature) = goto_method(kind);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
self.goto_in(&snap, &targets, method, pos, None).await
|
||||
@@ -1211,36 +1200,6 @@ impl LspManager {
|
||||
include_declaration: bool,
|
||||
project_wide: bool,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<References> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
// Scoped probes back code lenses and bulk analysis. Keep their native cost;
|
||||
// configuration indexing is reserved for explicit, project-wide usages.
|
||||
let configuration = if project_wide || snap.language.as_str() != "java" {
|
||||
self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if snap.language.as_str() != "java"
|
||||
&& let Some(result) = configuration
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
let mut result = self.native_references(doc, pos, include_declaration, project_wide, cancel).await?;
|
||||
if let Some(configuration) = configuration {
|
||||
result.locations.extend(configuration.locations);
|
||||
result.incomplete = result.incomplete.or(configuration.incomplete);
|
||||
convert::dedup_locations(&mut result.locations);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn native_references(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
include_declaration: bool,
|
||||
project_wide: bool,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<References> {
|
||||
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
|
||||
// The extension preserves method identity before JDT collapses references to locations.
|
||||
@@ -1253,7 +1212,7 @@ impl LspManager {
|
||||
let t = &targets[0];
|
||||
let extension_error = Mutex::new(None);
|
||||
let query = || async {
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let params = snap.pos_params(t, pos);
|
||||
@@ -1281,7 +1240,7 @@ impl LspManager {
|
||||
*extension_error.lock() = Some(e.clone());
|
||||
}
|
||||
let rows = result?;
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let conv = self.conv(t.enc());
|
||||
@@ -1307,7 +1266,7 @@ impl LspManager {
|
||||
scope::Widened::only(first, empty, &t.server)
|
||||
};
|
||||
// A changed source also invalidates an earlier answer retained by scope widening.
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Scope widening can retain the first answer after a failed second query.
|
||||
@@ -1333,7 +1292,7 @@ impl LspManager {
|
||||
Err(e) => {
|
||||
if e.kind == ErrorKind::Cancelled
|
||||
|| cancel.is_cancelled()
|
||||
|| self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version)
|
||||
|| !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version)
|
||||
{
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -650,7 +650,7 @@ async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
assert_eq!(s.requested("codeAction/resolve")[0]["data"], json!({ "id": 7 }));
|
||||
let edit = resolved.edit.unwrap();
|
||||
assert!(
|
||||
matches!(&edit.files[0], FileEdit::Edit { path: p, edits, .. } if p == &path && edits[0].range == rng(0, 0, 1, 0))
|
||||
matches!(&edit.files[0], FileEdit::Edit { path: p, edits } if p == &path && edits[0].range == rng(0, 0, 1, 0))
|
||||
);
|
||||
|
||||
h.mgr.execute_command(doc, actions[1].command.clone().unwrap()).await.unwrap();
|
||||
@@ -695,9 +695,7 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
let edits = applied.lock().clone();
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].files[0], FileEdit::Create { path: new_file.into(), overwrite: false });
|
||||
assert!(
|
||||
matches!(&edits[0].files[1], FileEdit::Edit { path: p, edits, .. } if p == &path && edits[0].new_text == "X")
|
||||
);
|
||||
assert!(matches!(&edits[0].files[1], FileEdit::Edit { path: p, edits } if p == &path && edits[0].new_text == "X"));
|
||||
|
||||
let peer = s.peer();
|
||||
let cfg: Value = peer
|
||||
@@ -1393,7 +1391,7 @@ fn edits_in(edit: &WorkspaceEdit, path: &Path) -> Vec<(Range, String)> {
|
||||
edit.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits, .. } if p.to_path_buf() == path => {
|
||||
FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| (e.range, e.new_text.clone())))
|
||||
}
|
||||
_ => None,
|
||||
@@ -1790,7 +1788,7 @@ async fn will_and_did_rename_files_honour_filters() {
|
||||
assert_eq!(result.servers, vec!["mock".to_owned()]);
|
||||
assert!(result.errors.is_empty());
|
||||
match &result.edit.files[..] {
|
||||
[FileEdit::Edit { path, edits, .. }] => {
|
||||
[FileEdit::Edit { path, edits }] => {
|
||||
assert_eq!(path, &main);
|
||||
assert_eq!(edits[0].range, rng(0, 4, 0, 7));
|
||||
assert_eq!(edits[0].new_text, "lib");
|
||||
@@ -2916,92 +2914,3 @@ async fn clang_tidy_config_for_a_later_opened_file_warns_on_a_running_server() {
|
||||
assert_eq!(h.mgr.servers().len(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_definition_uses_java_without_yaml_definition_capability() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
|
||||
let s = h.launcher.state("jdtls");
|
||||
let target = uri_of(&h.root.join("Settings.java"));
|
||||
s.respond("workspace/executeCommand", json!({
|
||||
"locations": [{"uri": target, "range": {"start": {"line": 2, "character": 4}, "end": {"line": 2, "character": 11}}}],
|
||||
"keys": [{"name": "app.timeOut", "relaxed": true}], "roots": []
|
||||
}));
|
||||
let path = h.root.join("application.yml");
|
||||
let doc = DocId::next();
|
||||
h.mgr.did_open(doc, &path, &LanguageId::new("yaml"), 1, "app:\n time-out: 5\n");
|
||||
let locations = h.mgr.goto(doc, Pos::new(1, 4), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start, Pos::new(2, 4));
|
||||
assert_eq!(s.requested("workspace/executeCommand")[0]["arguments"][1], "app.time-out");
|
||||
assert!(s.requested("textDocument/definition").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_usages_merge_native_and_unsaved_profiles_without_sibling_modules() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let (doc, path) = h.open("Settings.java", "int timeOut;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let root = uri_of(&h.root);
|
||||
s.respond(
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"locations": [], "keys": [{"name": "app.timeOut", "relaxed": true}], "roots": [root]
|
||||
}),
|
||||
);
|
||||
s.respond(
|
||||
"textDocument/references",
|
||||
json!([{"uri": uri_of(&path), "range": {
|
||||
"start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 7}
|
||||
}}]),
|
||||
);
|
||||
std::fs::write(h.root.join("application.yml"), "app:\n time-out: 1\n").unwrap();
|
||||
std::fs::write(h.root.join("application-prod.properties"), "app.time-out=2\n").unwrap();
|
||||
let overlay = h.root.join("application-dev.yml");
|
||||
std::fs::write(&overlay, "app:\n old: 3\n").unwrap();
|
||||
h.mgr.did_open(DocId::next(), &overlay, &LanguageId::new("yaml"), 1, "app:\n time-out: 3\n");
|
||||
let sibling = h.root.join("other");
|
||||
std::fs::create_dir(&sibling).unwrap();
|
||||
std::fs::write(sibling.join("pom.xml"), "<project/>").unwrap();
|
||||
std::fs::write(sibling.join("application.yml"), "app:\n time-out: wrong\n").unwrap();
|
||||
h.mgr.did_open(
|
||||
DocId::next(),
|
||||
&sibling.join("application.yml"),
|
||||
&LanguageId::new("yaml"),
|
||||
1,
|
||||
"app:\n time-out: still-wrong\n",
|
||||
);
|
||||
let scoped = h.mgr.references(doc, Pos::new(0, 6), false, false, Default::default()).await.unwrap();
|
||||
assert_eq!(scoped.locations.len(), 1);
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 6), false, true, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.locations.len(), 4, "{refs:?}");
|
||||
assert!(refs.locations.iter().all(|l| !l.path.to_path_buf().starts_with(&sibling)));
|
||||
assert!(refs.locations.iter().any(|l| l.path.to_path_buf() == overlay));
|
||||
assert_eq!(refs.incomplete, None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_extension_failure_preserves_native_java_navigation() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let (doc, path) = h.open("Settings.java", "@Value(\"${app.port}\") int port;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
s.errors.lock().insert("workspace/executeCommand".into(), (-32603, "old server".into()));
|
||||
s.respond(
|
||||
"textDocument/definition",
|
||||
json!({"uri": uri_of(&path), "range": {
|
||||
"start": {"line": 0, "character": 1}, "end": {"line": 0, "character": 6}
|
||||
}}),
|
||||
);
|
||||
let result = h.mgr.goto(doc, Pos::new(0, 2), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(s.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
@@ -194,62 +194,6 @@ async fn ty_python_end_to_end() {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Ruff next to basedpyright in a project configured for Ruff: its lint
|
||||
/// diagnostics, the only formatter and the only Organize Imports and Fix All.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires ruff and basedpyright on PATH"]
|
||||
async fn ruff_next_to_basedpyright_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.ruff.lint]\nselect = [\"F\", \"I\"]\n").unwrap();
|
||||
let path = root.join("example.py");
|
||||
let source = "import sys\nimport os\n\nx = os.getcwd( )\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
|
||||
python.language_servers.retain(|server| matches!(server.name.as_str(), "basedpyright" | "ruff"));
|
||||
assert_eq!(python.language_servers.len(), 2);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
|
||||
for name in ["basedpyright", "ruff"] {
|
||||
retry(name, Duration::from_secs(60), || {
|
||||
let status = last_status(&events, name);
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("{name} failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
}
|
||||
// F401 (`sys` unused) and I001 (unsorted imports).
|
||||
let codes = retry("ruff diagnostics", Duration::from_secs(30), || {
|
||||
let codes: Option<Vec<String>> = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { source, items, .. } if source == "ruff" && !items.is_empty() => {
|
||||
Some(items.iter().filter_map(|d| d.code.clone()).collect())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
async move { codes }
|
||||
})
|
||||
.await;
|
||||
assert!(codes.iter().any(|c| c == "F401") && codes.iter().any(|c| c == "I001"), "{codes:?}");
|
||||
|
||||
let options = ide_lsp::types::FormatOptions { tab_size: 4, insert_spaces: true, on_save: false };
|
||||
let edits = mgr.format(doc, None, options).await.unwrap();
|
||||
assert!(!edits.is_empty() && edits.iter().all(|e| e.range.start.line == 3), "{edits:?}");
|
||||
|
||||
let whole = Range::new(Pos::new(0, 0), Pos::new(4, 0));
|
||||
for kind in ["source.organizeImports", "source.fixAll"] {
|
||||
let actions = mgr.code_actions(doc, whole, vec![kind.into()]).await.unwrap();
|
||||
let kinds: Vec<&str> = actions.iter().filter_map(|a| a.kind.as_deref()).collect();
|
||||
assert_eq!(kinds, [format!("{kind}.ruff")], "{actions:?}");
|
||||
let action = mgr.resolve_code_action(doc, actions[0].clone()).await.unwrap();
|
||||
let edit = action.edit.expect("an edit");
|
||||
assert!(!edited_lines(&edit, &path).is_empty(), "{edit:?}");
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires rust-analyzer"]
|
||||
async fn rust_analyzer_end_to_end() {
|
||||
@@ -468,7 +412,7 @@ fn edited_lines(edit: &ide_core::WorkspaceEdit, path: &Path) -> Vec<u32> {
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path: p, edits, .. } if p.to_path_buf() == path => {
|
||||
ide_core::FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| e.range.start.line))
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -890,19 +890,6 @@ fn detect_python(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
if uses_pytest(root) || env.has_tool(root, "pytest") {
|
||||
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
|
||||
}
|
||||
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
|
||||
if root.join("manage.py").is_file() {
|
||||
out.push(
|
||||
py_config(
|
||||
"django:test".into(),
|
||||
"manage.py test".into(),
|
||||
"django-test",
|
||||
env.python(),
|
||||
&["manage.py", "test"],
|
||||
)
|
||||
.test(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- make / just
|
||||
|
||||
@@ -317,7 +317,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
|
||||
if matches!(config.kind.as_str(), "python" | "pytest") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
@@ -745,7 +745,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
|
||||
@@ -372,19 +372,13 @@ fn python_projects() {
|
||||
("manage.py", ""),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
// pytest stays ahead of `manage.py test`: the first test configuration is the default for context runs.
|
||||
assert_eq!(ids(&c), ["django:runserver", "python:module:mypkg", "pytest", "django:test"]);
|
||||
assert_eq!(ids(&c), ["django:runserver", "python:module:mypkg", "pytest"]);
|
||||
let pytest = find(&c, "pytest");
|
||||
assert_eq!(cmdline(pytest), "uv run pytest");
|
||||
assert!(pytest.is_test);
|
||||
assert_eq!(pytest.debug_adapter.as_deref(), Some("debugpy"));
|
||||
assert_eq!(cmdline(find(&c, "python:module:mypkg")), "uv run python -m mypkg");
|
||||
assert_eq!(cmdline(find(&c, "django:runserver")), "uv run python manage.py runserver");
|
||||
let django = find(&c, "django:test");
|
||||
assert_eq!(cmdline(django), "uv run python manage.py test");
|
||||
assert_eq!(django.kind, "django-test");
|
||||
assert!(django.is_test);
|
||||
assert_eq!(django.debug_adapter.as_deref(), Some("debugpy"));
|
||||
|
||||
let dir = project(&[("pytest.ini", "[pytest]\n"), ("poetry.lock", "")]);
|
||||
assert_eq!(cmdline(find(&detect(dir.path()), "pytest")), "poetry run pytest");
|
||||
@@ -404,7 +398,6 @@ fn python_virtualenv() {
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(cmdline(find(&c, "pytest")), ".venv/bin/pytest");
|
||||
assert_eq!(cmdline(find(&c, "django:runserver")), ".venv/bin/python manage.py runserver");
|
||||
assert_eq!(cmdline(find(&c, "django:test")), ".venv/bin/python manage.py test");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -447,7 +447,7 @@ fn build_tools_get_the_console_encoding_for_every_jvm() {
|
||||
|
||||
#[test]
|
||||
fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
for (kind, source_dir) in [("python", ""), ("pytest", "src"), ("django-test", "")] {
|
||||
for (kind, source_dir) in [("python", ""), ("pytest", "src")] {
|
||||
let h = harness();
|
||||
let root = h.root.path();
|
||||
let source = root.join(source_dir);
|
||||
@@ -465,11 +465,6 @@ fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
let mut config = cfg("python-imports", "python3", &["app/main.py"]);
|
||||
config.kind = kind.into();
|
||||
config.extras.env_files = vec![".env".into()];
|
||||
// Unbuffered, so output printed by a test stays next to its result line.
|
||||
assert_eq!(
|
||||
ide_run::resolved_env(root, &config).unwrap().get("PYTHONUNBUFFERED").map(String::as_str),
|
||||
Some("1")
|
||||
);
|
||||
let options = StartOptions { python_paths: vec![root.to_owned(), source], ..Default::default() };
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
|
||||
@@ -629,10 +629,10 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
resolve_run_command(c, root, s);
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
match c.kind.as_str() {
|
||||
"python" | "pytest" | "django-test" => {
|
||||
"python" | "pytest" => {
|
||||
if let Some(py) = &explicit_python {
|
||||
let runner = PY_RUNNERS.contains(&c.command.as_str());
|
||||
if (c.kind == "python" || c.kind == "django-test") && (runner || is_python_command(&c.command)) {
|
||||
if c.kind == "python" && (runner || is_python_command(&c.command)) {
|
||||
if runner && c.args.first().map(String::as_str) == Some("run") {
|
||||
// `uv run python …` → `<interpreter> …`
|
||||
let skip = if c.args.get(1).is_some_and(|a| is_python_command(a)) { 2 } else { 1 };
|
||||
|
||||
@@ -1173,7 +1173,7 @@ mod kotlin_bridge_bundle_tests {
|
||||
|
||||
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
|
||||
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
let extension = data_dir.join("java-usages-1.2.0.jar");
|
||||
let extension = data_dir.join("java-usages-1.1.1.jar");
|
||||
let bytes = include_bytes!("../../../plugins/java-usages/openidea-java-usages.jar");
|
||||
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
|
||||
@@ -152,8 +152,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
run("pytest", "uv", &["run", "pytest", "-x"]),
|
||||
run("npm", "npm", &["run", "dev"]),
|
||||
run("shell", "python3", &["x.py"]),
|
||||
run("django-test", "uv", &["run", "python", "manage.py", "test"]),
|
||||
run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]),
|
||||
];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].command, "/opt/py/bin/python3");
|
||||
@@ -163,11 +161,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
assert_eq!(configs[2].args, ["-m", "pytest", "-x"]);
|
||||
assert_eq!(configs[3].command, "pnpm");
|
||||
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
|
||||
// Django tests run on the selected interpreter, like `manage.py runserver`.
|
||||
assert_eq!(configs[5].command, "/opt/py/bin/python3");
|
||||
assert_eq!(configs[5].args, ["manage.py", "test"]);
|
||||
assert_eq!(configs[6].command, "/opt/py/bin/python3");
|
||||
assert_eq!(configs[6].args, ["manage.py", "test", "polls"]);
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path) {
|
||||
@@ -261,10 +254,10 @@ fn language_server_settings_disable_add_and_override() {
|
||||
let mut s = Settings::default();
|
||||
s.language_servers.insert("pylsp".into(), LanguageServerSettings { enabled: false, ..Default::default() });
|
||||
s.language_servers.insert(
|
||||
"pylyzer".into(),
|
||||
"ruff".into(),
|
||||
LanguageServerSettings {
|
||||
command: "pylyzer".into(),
|
||||
args: Some(vec!["--server".into()]),
|
||||
command: "ruff".into(),
|
||||
args: Some(vec!["server".into()]),
|
||||
languages: vec!["python".into()],
|
||||
root_markers: vec!["pyproject.toml".into()],
|
||||
..Default::default()
|
||||
@@ -272,42 +265,17 @@ fn language_server_settings_disable_add_and_override() {
|
||||
);
|
||||
let defined = [server("basedpyright"), server("pylsp")];
|
||||
let names = |v: Vec<LanguageServerConfig>| v.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "pylyzer"]);
|
||||
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "ruff"]);
|
||||
assert_eq!(names(language_servers("rust", &[server("rust-analyzer")], &s)), ["rust-analyzer"]);
|
||||
|
||||
// Listed with the tools even while disabled.
|
||||
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
with_custom_servers(&mut langs, &s);
|
||||
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
|
||||
let mut pylyzer = python.language_servers.iter().find(|c| c.name == "pylyzer").unwrap().clone();
|
||||
assert_eq!(pylyzer.root_markers, ["pyproject.toml"]);
|
||||
server_launch_overrides(&mut pylyzer, &s);
|
||||
assert_eq!((pylyzer.command.as_str(), pylyzer.args.as_slice()), ("pylyzer", &["--server".to_string()][..]));
|
||||
|
||||
// A hand-defined server named like a built-in one only overrides how it
|
||||
// launches: languages and root markers stay the built-in definition's.
|
||||
s.language_servers.insert(
|
||||
"ruff".into(),
|
||||
LanguageServerSettings {
|
||||
command: "/opt/ruff".into(),
|
||||
args: Some(vec!["server".into(), "--preview".into()]),
|
||||
languages: vec!["python".into()],
|
||||
root_markers: vec!["pyproject.toml".into()],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
with_custom_servers(&mut langs, &s);
|
||||
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
|
||||
assert_eq!(python.language_servers.iter().filter(|c| c.name == "ruff").count(), 1);
|
||||
let mut ruff = python.language_servers.iter().find(|c| c.name == "ruff").unwrap().clone();
|
||||
assert_eq!(ruff.root_markers, ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"]);
|
||||
assert!(ruff.require_root_marker);
|
||||
assert_eq!(ruff.root_markers, ["pyproject.toml"]);
|
||||
server_launch_overrides(&mut ruff, &s);
|
||||
assert_eq!(
|
||||
(ruff.command.as_str(), ruff.args.as_slice()),
|
||||
("/opt/ruff", &["server".to_string(), "--preview".to_string()][..])
|
||||
);
|
||||
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", &["server".to_string()][..]));
|
||||
|
||||
s.language_servers.insert(
|
||||
"rust-analyzer".into(),
|
||||
|
||||
@@ -159,7 +159,7 @@ impl StructureService {
|
||||
let runnable = body.is_some_and(|b| {
|
||||
members(*b).into_iter().any(|n| {
|
||||
if !matches!(n.kind(), "method_declaration" | "function_declaration")
|
||||
|| n.child_by_field_name("name").is_none_or(|id| text(id, snap.text) != "main")
|
||||
|| !n.child_by_field_name("name").is_some_and(|id| text(id, snap.text) == "main")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ zip.workspace = true
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
@@ -4,16 +4,48 @@
|
||||
use crate::InstallEvent;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::process::{kill_tree, own_group};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub type Emit<'a> = &'a dyn Fn(InstallEvent);
|
||||
|
||||
/// Starts the child as the leader of its own process group, so [`kill`] reaches what it
|
||||
/// starts in turn (`npm` → `node`, `go install` → the compiler, `pip` → build backends).
|
||||
fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started.
|
||||
fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
if let Ok(pid) = i32::try_from(child.id()) {
|
||||
// SAFETY: plain syscall; the child leads its own process group (`own_group`) and is not reaped yet.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
ide_core::process::prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &child.id().to_string()])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn describe(cmd: &Command) -> String {
|
||||
let mut s = Path::new(cmd.get_program()).file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
for a in cmd.get_args() {
|
||||
@@ -68,7 +100,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
|
||||
let mut output = String::new();
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
@@ -112,7 +144,7 @@ pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)>
|
||||
Ok(Some(s)) => break s,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(15)),
|
||||
_ => {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -224,7 +256,7 @@ impl Http {
|
||||
});
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match child.try_wait()? {
|
||||
@@ -276,7 +308,7 @@ impl Http {
|
||||
let mut last_bytes = 0;
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
let _ = std::fs::remove_file(dest);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -381,7 +413,7 @@ pub(crate) fn run_input(
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
}
|
||||
result?;
|
||||
let output = output.unwrap()?;
|
||||
|
||||
@@ -233,17 +233,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://docs.astral.sh/ty/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "ruff",
|
||||
display: "Ruff",
|
||||
kind: LanguageServer,
|
||||
commands: &["ruff"],
|
||||
method: Method::PipVenv { package: "ruff" },
|
||||
fallback: None,
|
||||
version: ver("ruff"),
|
||||
homepage: "https://docs.astral.sh/ruff/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-language-server",
|
||||
display: "Bash Language Server",
|
||||
|
||||
@@ -157,7 +157,6 @@ fn interchangeable_servers_list_their_alternatives() {
|
||||
assert_eq!(find(&list, "vtsls").alternatives, ["vtsls", "typescript-language-server"]);
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
assert!(find(&list, "rust-analyzer").alternatives.is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
//! Thin wrapper around the `git` executable used for every mutating operation.
|
||||
|
||||
use ide_core::process::{own_group, terminate_tree};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled git's process group (remote helpers, `ssh`, credential helpers) gets
|
||||
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
/// Explicit git executable from Settings › Version Control › Git (`None` = auto-detect).
|
||||
static CONFIGURED: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
|
||||
|
||||
@@ -366,7 +361,11 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
|
||||
}
|
||||
let mut cmd = command(root)?;
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
own_group(&mut cmd);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
let capture = |mut pipe: Box<dyn Read + Send>| {
|
||||
@@ -379,7 +378,8 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
|
||||
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
let _ = stdout.join();
|
||||
let _ = stderr.join();
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -504,7 +504,11 @@ pub(crate) fn run_streaming_env(
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
own_group(&mut cmd);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
tracing::debug!(?args, "git (streaming)");
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
@@ -525,7 +529,8 @@ pub(crate) fn run_streaming_env(
|
||||
let mut open = readers.len();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
for r in readers {
|
||||
let _ = r.join();
|
||||
}
|
||||
@@ -554,7 +559,8 @@ pub(crate) fn run_streaming_env(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -638,6 +644,22 @@ fn spawn_reader(
|
||||
})
|
||||
}
|
||||
|
||||
fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child was spawned as leader of its own process group.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod command_session_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -19,7 +19,6 @@ semver = "1.0.28"
|
||||
parking_lot.workspace = true
|
||||
blake3.workspace = true
|
||||
tracing.workspace = true
|
||||
tempfile.workspace = true
|
||||
globset.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -4,7 +4,7 @@ use ide_core::error::ErrorKind;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
use parking_lot::{Mutex, ReentrantMutex, RwLock};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
@@ -62,11 +62,6 @@ pub type DetectUiMode = dyn Fn(&Path, &LanguageId) -> Option<String> + Send + Sy
|
||||
/// Every document has its own lock; operations on one document are serialized
|
||||
/// and observers see them in version order.
|
||||
pub struct Documents {
|
||||
/// Workspace transactions hold this across preflight/commit/rollback; ordinary
|
||||
/// operations re-enter it while accessing the individual document locks.
|
||||
operations: ReentrantMutex<()>,
|
||||
workspace_edits: Arc<Mutex<workspace_edit::History>>,
|
||||
workspace_edit_active: std::sync::atomic::AtomicBool,
|
||||
registry: Mutex<Registry>,
|
||||
observers: RwLock<Vec<Arc<dyn DocumentObserver>>>,
|
||||
sink: SharedSink,
|
||||
@@ -101,8 +96,6 @@ pub trait DocumentObserver: Send + Sync {
|
||||
fn closed(&self, _doc: DocId, _path: &Path) {}
|
||||
}
|
||||
|
||||
mod workspace_edit;
|
||||
|
||||
type Slot = Arc<Mutex<DocState>>;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -118,7 +111,6 @@ struct RegEntry {
|
||||
keys: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DocState {
|
||||
path: PathBuf,
|
||||
doc: Document,
|
||||
@@ -171,9 +163,6 @@ fn read_only_error(path: &Path) -> IdeError {
|
||||
impl Documents {
|
||||
pub fn new(sink: SharedSink, detect_language: Box<DetectLanguage>) -> Self {
|
||||
Self {
|
||||
operations: ReentrantMutex::new(()),
|
||||
workspace_edits: Arc::default(),
|
||||
workspace_edit_active: std::sync::atomic::AtomicBool::new(false),
|
||||
registry: Mutex::default(),
|
||||
observers: RwLock::default(),
|
||||
sink,
|
||||
@@ -290,7 +279,6 @@ impl Documents {
|
||||
|
||||
/// Locks a document, failing if it was closed concurrently.
|
||||
fn with_doc<T>(&self, doc: DocId, f: impl FnOnce(&mut DocState) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let _operation = self.operations.lock();
|
||||
let slot = self.slot(doc)?;
|
||||
let mut st = slot.lock();
|
||||
if st.closed {
|
||||
@@ -338,7 +326,6 @@ impl Documents {
|
||||
|
||||
/// Opens (or re-references) the document at `path`.
|
||||
pub fn open(&self, path: &Path) -> IdeResult<DocumentInfo> {
|
||||
let _operation = self.operations.lock();
|
||||
if let Some(info) = self.reopen(path) {
|
||||
return Ok(info);
|
||||
}
|
||||
@@ -431,7 +418,6 @@ impl Documents {
|
||||
/// language server provides for a non-`file:` URI. It is keyed by the URI,
|
||||
/// never touches the disk and cannot be edited or saved.
|
||||
pub fn open_virtual(&self, uri: &str, language: LanguageId, text: &str) -> IdeResult<DocumentInfo> {
|
||||
let _operation = self.operations.lock();
|
||||
let key = PathBuf::from(uri);
|
||||
if let Some(info) = self.reopen(&key) {
|
||||
return Ok(info);
|
||||
@@ -490,7 +476,6 @@ impl Documents {
|
||||
}
|
||||
|
||||
pub fn close(&self, doc: DocId) {
|
||||
let _operation = self.operations.lock();
|
||||
let slot = {
|
||||
let mut reg = self.registry.lock();
|
||||
let Some(entry) = reg.docs.get_mut(&doc) else { return };
|
||||
@@ -573,13 +558,7 @@ impl Documents {
|
||||
edits: &[ByteEdit],
|
||||
) {
|
||||
self.notify_changed(doc, st, applied, edits);
|
||||
self.sink.emit(IdeEvent::DocPatched {
|
||||
doc,
|
||||
base_version,
|
||||
version: st.doc.version(),
|
||||
changes: set.changes,
|
||||
workspace_edit: self.workspace_edit_active.load(std::sync::atomic::Ordering::Relaxed),
|
||||
});
|
||||
self.sink.emit(IdeEvent::DocPatched { doc, base_version, version: st.doc.version(), changes: set.changes });
|
||||
}
|
||||
|
||||
/// Minimal-diff replacement; no event when the text is unchanged.
|
||||
@@ -714,11 +693,6 @@ impl Documents {
|
||||
self.with_doc(doc, |st| Ok(st.dirty))
|
||||
}
|
||||
|
||||
/// Current generation without copying the document text.
|
||||
pub fn version(&self, doc: DocId) -> IdeResult<u32> {
|
||||
self.with_doc(doc, |st| Ok(st.doc.version()))
|
||||
}
|
||||
|
||||
/// Ids of all open documents.
|
||||
pub fn open_documents(&self) -> Vec<DocId> {
|
||||
self.registry.lock().docs.keys().copied().collect()
|
||||
@@ -731,7 +705,6 @@ impl Documents {
|
||||
/// for the observers, so it moves to the matching language servers and
|
||||
/// syntax tree. Returns the changed documents.
|
||||
pub fn redetect_languages(&self) -> Vec<DocId> {
|
||||
let _operation = self.operations.lock();
|
||||
let slots: Vec<(DocId, Slot)> = self.registry.lock().docs.iter().map(|(id, e)| (*id, e.slot.clone())).collect();
|
||||
let mut changed = Vec::new();
|
||||
for (id, slot) in slots {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -89,7 +89,7 @@ fn write_text(documents: &Documents, path: &Path, text: &str) -> IdeResult<()> {
|
||||
fn edited_paths(edit: &WorkspaceEdit) -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for f in &edit.files {
|
||||
if let FileEdit::Edit { path, edits, .. } = f
|
||||
if let FileEdit::Edit { path, edits } = f
|
||||
&& !edits.is_empty()
|
||||
&& !out.iter().any(|p| p == path)
|
||||
{
|
||||
@@ -245,7 +245,17 @@ mod tests {
|
||||
}
|
||||
|
||||
fn apply(documents: &Documents) -> impl Fn(&WorkspaceEdit) -> IdeResult<()> + '_ {
|
||||
move |edit| documents.apply_file_move_edits(edit)
|
||||
move |edit| {
|
||||
for f in &edit.files {
|
||||
if let FileEdit::Edit { path, edits } = f {
|
||||
let doc = documents.open(path)?.id;
|
||||
documents.apply_edits(doc, edits)?;
|
||||
documents.save(doc)?;
|
||||
documents.close(doc);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,10 +272,8 @@ mod tests {
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit {
|
||||
path: root.join("main.ts").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 21), Pos::new(0, 22)), new_text: "b".into() }],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let id = moves.perform(&docs, Some(&history), &mv, &edit, "Move", &apply(&docs)).unwrap();
|
||||
assert!(root.join("b/util.ts").exists() && !root.join("a").exists());
|
||||
@@ -295,16 +303,13 @@ mod tests {
|
||||
files: vec![
|
||||
FileEdit::Edit {
|
||||
path: root.join("Foo.java").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 6), Pos::new(0, 9)), new_text: "Bar".into() }],
|
||||
},
|
||||
FileEdit::Edit {
|
||||
path: root.join("Use.java").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "Bar".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let mv = vec![FileMove { from: root.join("Foo.java").into(), to: root.join("Bar.java").into() }];
|
||||
let id = moves.perform(&docs, None, &mv, &edit, "Rename", &apply(&docs)).unwrap();
|
||||
|
||||
@@ -201,11 +201,7 @@ pub fn find_text_occurrences(
|
||||
let mut files = found.into_inner();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
WorkspaceEdit {
|
||||
files: files
|
||||
.into_iter()
|
||||
.map(|(path, edits)| FileEdit::Edit { path: path.into(), edits, version: None })
|
||||
.collect(),
|
||||
..Default::default()
|
||||
files: files.into_iter().map(|(path, edits)| FileEdit::Edit { path: path.into(), edits }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{IdeEvent, error::ErrorKind};
|
||||
use ide_workspace::Documents;
|
||||
use parking_lot::Mutex;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn documents() -> Documents {
|
||||
Documents::new(Arc::new(NullSink), Box::new(|_, _| LanguageId::plain_text()))
|
||||
}
|
||||
|
||||
fn edit(path: &Path, text: &str) -> FileEdit {
|
||||
FileEdit::Edit {
|
||||
path: path.to_owned().into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: text.into() }],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_failure_preserves_disk_and_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let missing = tmp.path().join("missing.txt");
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
let result = docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![edit(&first, "new"), edit(&missing, "bad")],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
let after = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(after.text, "own\n");
|
||||
assert!(after.dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_conflict_does_not_modify_earlier_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let existing = tmp.path().join("exists.txt");
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
std::fs::write(&existing, "keep").unwrap();
|
||||
let docs = documents();
|
||||
let result = docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![edit(&first, "new"), FileEdit::Create { path: existing.clone().into(), overwrite: false }],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(existing).unwrap(), "keep");
|
||||
}
|
||||
|
||||
fn recorded_documents() -> (Documents, Arc<Mutex<Vec<IdeEvent>>>) {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
(Documents::new(Arc::new(move |event| sink.lock().push(event)), Box::new(|_, _| LanguageId::plain_text())), events)
|
||||
}
|
||||
|
||||
fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.expect("successful transaction has one undo record")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_document_version_rejects_the_whole_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let b = tmp.path().join("b.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
std::fs::write(&b, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&b).unwrap();
|
||||
docs.edit(info.id, 0, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "own ".into() }] }).unwrap();
|
||||
let mut second = edit(&b, "new");
|
||||
if let FileEdit::Edit { version, .. } = &mut second {
|
||||
*version = Some(0);
|
||||
}
|
||||
let result =
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&a, "new"), second], ..Default::default() });
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "old\n");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own old\n");
|
||||
assert!(docs.is_dirty(info.id).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_document_version_is_applied() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&a).unwrap();
|
||||
let mut operation = edit(&a, "new");
|
||||
if let FileEdit::Edit { version, .. } = &mut operation {
|
||||
*version = Some(info.version as i32);
|
||||
}
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![operation], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unversioned_preview_rejects_changed_disk_and_dirty_buffers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for open in [false, true] {
|
||||
let path = tmp.path().join(if open { "open.txt" } else { "closed.txt" });
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = open.then(|| docs.open(&path).unwrap());
|
||||
let mut change = WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() };
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
if let Some(info) = &info {
|
||||
docs.edit(
|
||||
info.id,
|
||||
info.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
std::fs::write(&path, "own\n").unwrap();
|
||||
}
|
||||
let original = change.preconditions.clone();
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
assert_eq!(change.preconditions, original, "resolution must not refresh an old preview's guard");
|
||||
assert_eq!(docs.apply_workspace_edit(&change).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
if let Some(info) = info {
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
} else {
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "own\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_undo_restores_open_closed_and_unsaved_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let b = tmp.path().join("b.txt");
|
||||
let c = tmp.path().join("c.txt");
|
||||
for path in [&a, &b, &c] {
|
||||
std::fs::write(path, "old\r\n").unwrap();
|
||||
}
|
||||
let (docs, events) = recorded_documents();
|
||||
let dirty = docs.open(&a).unwrap();
|
||||
let clean = docs.open(&b).unwrap();
|
||||
docs.edit(dirty.id, 0, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] }).unwrap();
|
||||
let change =
|
||||
WorkspaceEdit { files: [&a, &b, &c].into_iter().map(|p| edit(p, "new")).collect(), ..Default::default() };
|
||||
docs.apply_workspace_edit(&change).unwrap();
|
||||
assert_eq!(docs.snapshot(dirty.id).unwrap().text, "new\n");
|
||||
assert!(docs.is_dirty(dirty.id).unwrap());
|
||||
assert_eq!(std::fs::read(&a).unwrap(), b"old\r\n", "unrelated unsaved work is not saved");
|
||||
assert_eq!(std::fs::read(&c).unwrap(), b"new\r\n");
|
||||
let opened_later = docs.open(&c).unwrap();
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(docs.snapshot(dirty.id).unwrap().text, "own\n");
|
||||
assert!(docs.is_dirty(dirty.id).unwrap());
|
||||
for info in [clean, opened_later] {
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old\n");
|
||||
assert!(!docs.is_dirty(info.id).unwrap());
|
||||
}
|
||||
for path in [&a, &b, &c] {
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"old\r\n");
|
||||
}
|
||||
assert!(docs.undo_workspace_edit(id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&a, "new")], ..Default::default() }).unwrap();
|
||||
let id = undo_id(&events);
|
||||
std::fs::write(&a, "own\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(id).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "own\n");
|
||||
std::fs::write(&a, "new\n").unwrap();
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let created = tmp.path().join("new/deep/file.txt");
|
||||
let renamed = tmp.path().join("renamed.txt");
|
||||
let deleted = tmp.path().join("binary.dat");
|
||||
let overwritten = tmp.path().join("overwrite.txt");
|
||||
std::fs::write(&deleted, [0, 255, 1, 128]).unwrap();
|
||||
std::fs::write(&overwritten, [255, 254, 65, 0]).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let change = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Create { path: created.clone().into(), overwrite: false },
|
||||
edit(&created, "hello"),
|
||||
FileEdit::Rename { from: created.clone().into(), to: renamed.clone().into() },
|
||||
FileEdit::Delete { path: deleted.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: overwritten.clone().into(), overwrite: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.apply_workspace_edit(&change).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&renamed).unwrap(), "hello");
|
||||
assert!(!deleted.exists());
|
||||
assert!(std::fs::read(&overwritten).unwrap().is_empty());
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert!(!tmp.path().join("new").exists());
|
||||
assert!(!renamed.exists());
|
||||
assert_eq!(std::fs::read(deleted).unwrap(), [0, 255, 1, 128]);
|
||||
assert_eq!(std::fs::read(overwritten).unwrap(), [255, 254, 65, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonrecursive_directory_delete_is_rejected_before_any_write() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let dir = tmp.path().join("directory");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("keep.txt"), "keep").unwrap();
|
||||
let change = WorkspaceEdit {
|
||||
files: vec![edit(&a, "new"), FileEdit::Delete { path: dir.clone().into(), recursive: false }],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(documents().apply_workspace_edit(&change).is_err());
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
assert!(dir.join("keep.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_write_not_yet_seen_by_watcher_is_not_overwritten() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
std::fs::write(&path, "own\n").unwrap();
|
||||
let mut change = WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() };
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
assert_eq!(docs.apply_workspace_edit(&change).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "own\n");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn undo_restores_deleted_directory_with_symlinks_and_permissions() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("tree");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("script"), "old\n").unwrap();
|
||||
std::fs::set_permissions(dir.join("script"), std::fs::Permissions::from_mode(0o751)).unwrap();
|
||||
symlink("missing-target", dir.join("link")).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![FileEdit::Delete { path: dir.clone().into(), recursive: true }],
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!dir.exists());
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join("script")).unwrap(), b"old\n");
|
||||
assert_eq!(std::fs::metadata(dir.join("script")).unwrap().permissions().mode() & 0o777, 0o751);
|
||||
assert_eq!(std::fs::read_link(dir.join("link")).unwrap(), Path::new("missing-target"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn preflight_never_writes_through_copied_or_moved_symlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("target.txt");
|
||||
let link = tmp.path().join("link.txt");
|
||||
let moved = tmp.path().join("moved.txt");
|
||||
std::fs::write(&target, "old\n").unwrap();
|
||||
symlink(&target, &link).unwrap();
|
||||
let docs = documents();
|
||||
for files in [
|
||||
vec![FileEdit::Create { path: link.clone().into(), overwrite: true }],
|
||||
vec![FileEdit::Rename { from: link.clone().into(), to: moved.clone().into() }, edit(&moved, "new")],
|
||||
] {
|
||||
assert!(docs.apply_workspace_edit(&WorkspaceEdit { files, ..Default::default() }).is_err());
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old\n");
|
||||
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
||||
assert!(!moved.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_after_restoring_inplace_typing_saves_but_real_unsaved_work_stays_dirty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.ts");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
for (version, text) in [(0, "own"), (1, "old")] {
|
||||
docs.edit(info.id, version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
assert!(docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty, "restoring saved bytes must clear a stale dirty flag");
|
||||
docs.redo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.edit(
|
||||
info.id,
|
||||
docs.version(info.id).unwrap(),
|
||||
ChangeSet { changes: vec![TextChange { from: 3, to: 3, insert: " own".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(id).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_edits_keep_versions_and_apply_one_replacement() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.cpp");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
let mut versioned = edit(&path, "new_long");
|
||||
if let FileEdit::Edit { version, .. } = &mut versioned {
|
||||
*version = Some(info.version as i32);
|
||||
}
|
||||
let mut workspace = WorkspaceEdit { files: vec![edit(&path, "new_long"), versioned], ..Default::default() };
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 1);
|
||||
assert!(matches!(workspace.files[0], FileEdit::Edit { version: Some(0), .. }));
|
||||
docs.apply_workspace_edit(&workspace).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new_long");
|
||||
|
||||
let mut conflicting = workspace.files[0].clone();
|
||||
if let FileEdit::Edit { version, .. } = &mut conflicting {
|
||||
*version = Some(99);
|
||||
}
|
||||
workspace.files.push(conflicting);
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 2, "deduplication must not discard incompatible versions");
|
||||
assert_eq!(docs.apply_workspace_edit(&workspace).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "new_long");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_accepts_typing_that_was_reverted_to_the_saved_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.ts");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
let id = undo_id(&events);
|
||||
for text in ["own", "new"] {
|
||||
docs.edit(
|
||||
info.id,
|
||||
docs.version(info.id).unwrap(),
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: text.into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "old");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn replacing_a_symlink_then_editing_the_new_file_never_writes_its_old_target() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("precious.txt");
|
||||
let link = tmp.path().join("new.txt");
|
||||
std::fs::write(&target, "old target\n").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let target_doc = docs.open(&target).unwrap();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Delete { path: link.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: link.clone().into(), overwrite: false },
|
||||
FileEdit::Edit {
|
||||
path: link.clone().into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::point(Pos::new(0, 0)), new_text: "new file\n".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
docs.apply_workspace_edit(&edit).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old target\n");
|
||||
assert_eq!(docs.snapshot(target_doc.id).unwrap().text, "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(&link).unwrap(), "new file\n");
|
||||
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_link(&link).unwrap(), target);
|
||||
docs.redo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(&link).unwrap(), "new file\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn replacing_a_directory_symlink_does_not_resolve_later_child_paths_through_its_old_target() {
|
||||
for alias in 0..3 {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("precious");
|
||||
let link = tmp.path().join("new");
|
||||
std::fs::create_dir(&target).unwrap();
|
||||
std::fs::write(target.join("file.txt"), "old target\n").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let alternate = tmp.path().join("alternate");
|
||||
std::os::unix::fs::symlink(tmp.path(), &alternate).unwrap();
|
||||
let shortcut = tmp.path().join("shortcut");
|
||||
std::os::unix::fs::symlink(&link, &shortcut).unwrap();
|
||||
let edited = match alias {
|
||||
0 => link.join("file.txt"),
|
||||
1 => alternate.join("new/file.txt"),
|
||||
_ => shortcut.join("file.txt"),
|
||||
};
|
||||
let docs = documents();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Delete { path: link.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: link.join("file.txt").into(), overwrite: false },
|
||||
FileEdit::Edit {
|
||||
path: edited.into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::point(Pos::new(0, 0)), new_text: "new file\n".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
docs.apply_workspace_edit(&edit).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target.join("file.txt")).unwrap(), "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(link.join("file.txt")).unwrap(), "new file\n");
|
||||
}
|
||||
}
|
||||
@@ -40,16 +40,6 @@ args = ["server"]
|
||||
root-markers = ["ty.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
|
||||
install-hint = "uv tool install ty (or: pip install ty)"
|
||||
|
||||
# Lint, format, organize imports and fix all next to the type checker, in
|
||||
# projects configured for Ruff (formatting is Ruff's alone: basedpyright has none).
|
||||
[[language-servers]]
|
||||
name = "ruff"
|
||||
command = "ruff"
|
||||
args = ["server"]
|
||||
root-markers = ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"]
|
||||
require-root-marker = true
|
||||
install-hint = "pip install ruff (or: uv tool install ruff)"
|
||||
|
||||
[debugger]
|
||||
adapter = "debugpy"
|
||||
command = "python3"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.34",
|
||||
"version": "0.1.33",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
# Spring configuration navigation
|
||||
|
||||
`openidea.java.configuration` bridges YAML / properties to the existing JDT LS
|
||||
Java model. It is bundled with the Java usages extension; it does not install a
|
||||
second language server, run a build, change the application's dependencies, or
|
||||
connect to external configuration services.
|
||||
|
||||
## Editor behavior
|
||||
|
||||
- **Go to Definition** on a YAML / properties key opens binding members and
|
||||
literal consumers in Java. Multiple matches use the existing location chooser.
|
||||
- **Go to Definition** inside a Java `@Value` placeholder or a constant
|
||||
`Environment.getProperty` / `getRequiredProperty` argument opens matching
|
||||
configuration keys. Ordinary Java definition navigation remains native.
|
||||
- **Find Usages** joins configuration declarations, property consumers, and Java
|
||||
references to associated binding members. Java's existing reference results and
|
||||
read/write classifications are retained.
|
||||
- Open editor contents take precedence over disk. All matching profiles/documents
|
||||
are shown; navigation does not claim to know the runtime effective value.
|
||||
- Missing or older extension bundles preserve native language-server behavior.
|
||||
YAML aliases still use the YAML server's anchor navigation.
|
||||
|
||||
## Association sources
|
||||
|
||||
The Java command resolves annotation and method identities with JDT bindings:
|
||||
|
||||
- `@ConfigurationProperties` on classes and factory methods, including inherited
|
||||
members, nested objects, records, constructor-only parameters / `@Name`, arrays,
|
||||
collections and maps. Binder keys use relaxed spelling while retaining path
|
||||
boundaries. Indexed collection positions and arbitrary map keys use wildcards.
|
||||
- `@Value("${key:default}")`, including constant annotation values and nested
|
||||
default placeholders.
|
||||
- Literal or compile-time constant keys passed to Spring's `PropertyResolver`
|
||||
methods, including through `Environment`. Unrelated methods with the same name
|
||||
and non-Spring annotations are excluded.
|
||||
- Dependency JAR `META-INF/spring-configuration-metadata.json` and
|
||||
`additional-spring-configuration-metadata.json`. The closest group, source
|
||||
type, and source method locate a member or its owning class. Source attachments
|
||||
and JDT class-file/decompiler navigation use the existing virtual-document path.
|
||||
- The same metadata files in source roots and `src/main/resources`.
|
||||
|
||||
YAML key ranges come from the bundled tree-sitter grammar, including nested/flow
|
||||
mappings, sequences, quoted keys and multiple documents. Properties support
|
||||
escaped keys, Unicode escapes and logical-line continuations. Ranges crossing
|
||||
IPC are UTF-16. No new IPC type or frontend provider is required.
|
||||
|
||||
## Scope and costs
|
||||
|
||||
The command uses the selected JDT project's resolved package roots, including
|
||||
source dependencies and its dependency JARs. Configuration search includes those
|
||||
modules, skips nested independent modules and build output, and honors ignore
|
||||
files for disk discovery. It does not guess a global association from matching
|
||||
text in unrelated projects.
|
||||
|
||||
Indexing is lazy. The first explicit navigation/search builds a compact snapshot;
|
||||
ordinary typing, code-lens probes and bulk scoped reference analysis do not start indexing. At most eight project snapshots are
|
||||
retained, with a shared 100,000-association retention cap. Records contain property names, element handles and source locations;
|
||||
ASTs and bindings are discarded after indexing. A lexical prefilter avoids AST
|
||||
construction for ordinary Java units, but every accepted association is resolved
|
||||
semantically. Warm requests reuse the snapshot. Java model/reconcile changes
|
||||
invalidate it conservatively, including dependent-type changes; open working-copy
|
||||
content fingerprints also prevent stale answers before reconciliation. This is
|
||||
**snapshot invalidation**, not a fully incremental Java semantic index.
|
||||
|
||||
Metadata/JAR timestamps are checked before reuse. The client caches parsed disk
|
||||
configuration files by modification time and size (at most 100,000 cached keys), overlays open buffers, and
|
||||
performs bounded discovery/parsing on a blocking worker. It does not continuously
|
||||
watch or parse an additional copy of the entire workspace.
|
||||
|
||||
Bounds: 20,000 Java units, 100,000 associations per snapshot, 2 MiB per candidate
|
||||
metadata/configuration file (Java source: 2M UTF-16 units), 1,024-character property names, 2,000 configuration files/results, 50,000 filesystem
|
||||
entries per root, and depth limits on recursive bindings/YAML. Java requests and
|
||||
references are cancellable. File/association scan limits and unreadable files carry the
|
||||
existing incomplete-result indicator; unsupported syntax keys are omitted. First navigation can take seconds on a
|
||||
cold project; classpath import and source download remain owned by JDT LS.
|
||||
|
||||
## Deliberate limits
|
||||
|
||||
This is Java/Spring property navigation, not full IntelliJ Spring support. It
|
||||
cannot infer dynamically constructed names, custom configuration APIs/annotations,
|
||||
remote-only configuration, arbitrary SpEL evaluation, YAML merge/alias expansion,
|
||||
or custom Spring converters that change the binding shape. Kotlin is not indexed
|
||||
by this Java bundle. YAML-only quoted-string escape forms that cannot be decoded
|
||||
safely are skipped. Properties surrogate-pair escapes are not decoded as keys.
|
||||
A missing source attachment may navigate to the decompiled owning class when JDT
|
||||
cannot provide an exact member range. Binding members are navigation candidates;
|
||||
the feature does not validate whether Spring will successfully bind a bean at
|
||||
runtime or resolve profile/precedence rules.
|
||||
|
||||
## Verification
|
||||
|
||||
Use the JDT LS distribution / Java version documented in [README](README.md).
|
||||
|
||||
```sh
|
||||
python3 plugins/java-usages/build.py /path/to/jdtls
|
||||
python3 plugins/java-usages/tests/configuration.py /path/to/jdtls
|
||||
OPENIDEA_CONFIGURATION_STRESS=1 python3 plugins/java-usages/tests/configuration.py /path/to/jdtls
|
||||
OPENIDEA_SPRING_BOOT_JAR=/path/to/spring-boot-autoconfigure.jar python3 plugins/java-usages/tests/configuration.py /path/to/jdtls
|
||||
cargo test -p ide-language -p ide-lsp
|
||||
```
|
||||
|
||||
The isolated real-server harness covers custom bindings, inheritance, nesting,
|
||||
collections/maps, records, constructor aliases, factory methods, consumers,
|
||||
constant keys, negative identity matches, dependency metadata/source locations,
|
||||
reverse queries, and unsaved-change/close invalidation. Optional stress fixtures
|
||||
add 3,000 ordinary units and 100 binding classes; output includes cold/warm/edit
|
||||
latencies for the JDT command only, excluding server import, UI and configuration-file discovery. The optional actual Spring Boot JAR checks `server.port`,
|
||||
`spring.datasource.url` and `spring.jackson.date-format` through dependency
|
||||
metadata. No user's project is compiled or modified by the harness.
|
||||
|
||||
Rust tests cover configuration syntax/ranges and the actual manager bridge:
|
||||
YAML navigation without YAML definition capabilities, Java native fallback,
|
||||
reference merging, profiles, open-buffer overlays and sibling-module exclusion.
|
||||
Existing Java usages / read-write integration harnesses remain regression checks.
|
||||
@@ -2,9 +2,9 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.2.0
|
||||
Bundle-Version: 1.1.1
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
org.eclipse.lsp4j,org.eclipse.core.resources,com.google.gson
|
||||
org.eclipse.lsp4j
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
# Semantic Java usages and configuration navigation
|
||||
|
||||
Spring YAML / properties navigation is described in [CONFIGURATION.md](CONFIGURATION.md).
|
||||
# Semantic Java usages
|
||||
|
||||
The app-owned OSGi command `openidea.java.usages` returns `{location, kind, access}`.
|
||||
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
|
||||
@@ -57,7 +55,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.2.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.1.1.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -66,10 +64,8 @@ Use its shipped ECJ and plugin jars, with Java 25; emitted bytecode targets Java
|
||||
The build uses sorted inputs and fixed zip timestamps and does not resolve Maven
|
||||
artifacts. Check the extracted distribution against `build-dependencies.sha256`
|
||||
from its root (`sha256sum -c /path/to/build-dependencies.sha256`). Build twice
|
||||
and compare SHA-256. The prior 1.1.1 output was
|
||||
and compare SHA-256. The 1.1.1 output is
|
||||
`1e569939cba22c7db6e2c9b53de2a4c10ccaabe762a51427119a04af3d974ae4`.
|
||||
Version 1.2.0 adds the configuration command; its reproducible SHA-256 is
|
||||
`9140f1d2ecf27eadfe66b40a17daa18a08a65927ebef79456ba55d486ce5eeba`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
|
||||
Бінарний файл не відображається.
@@ -4,8 +4,5 @@
|
||||
<delegateCommandHandler class="ai.openidea.usages.UsagesCommand">
|
||||
<command id="openidea.java.usages"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.configuration.ConfigurationCommand">
|
||||
<command id="openidea.java.configuration"/>
|
||||
</delegateCommandHandler>
|
||||
</extension>
|
||||
</plugin>
|
||||
@@ -1,525 +0,0 @@
|
||||
package ai.openidea.configuration;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.zip.ZipFile;
|
||||
import com.google.gson.*;
|
||||
import org.eclipse.core.resources.ResourcesPlugin;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.core.runtime.OperationCanceledException;
|
||||
import org.eclipse.jdt.core.*;
|
||||
import org.eclipse.jdt.core.dom.*;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
|
||||
import org.eclipse.jdt.ls.core.internal.handlers.ReferencesHandler;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/** On-demand configuration index, scoped by JDT's resolved source/class path.
|
||||
* Cached records contain strings and locations, never ASTs or bindings. Java model
|
||||
* changes invalidate snapshots, including unsaved working copies and classpath edits.
|
||||
*/
|
||||
public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
private static final String PROPERTIES = "org.springframework.boot.context.properties.ConfigurationProperties";
|
||||
private static final String VALUE = "org.springframework.beans.factory.annotation.Value";
|
||||
private static final String RESOLVER = "org.springframework.core.env.PropertyResolver";
|
||||
private static final int MAX_UNITS = 20_000, MAX_ENTRIES = 100_000, MAX_BYTES = 2 * 1024 * 1024;
|
||||
private static final AtomicLong REVISION = new AtomicLong();
|
||||
private static final Map<String, Index> CACHE = new LinkedHashMap<>();
|
||||
static { JavaCore.addElementChangedListener(event -> REVISION.incrementAndGet(), ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE); }
|
||||
|
||||
private record Entry(String name, String handle, Location location, boolean relaxed) {}
|
||||
private record FileStamp(java.nio.file.attribute.FileTime modified, long size) {}
|
||||
private static FileStamp stamp(Path path) {
|
||||
try { return new FileStamp(Files.getLastModifiedTime(path), Files.size(path)); }
|
||||
catch (java.io.IOException e) { return new FileStamp(null, -1); }
|
||||
}
|
||||
private record Index(long revision, String workingCopies, List<Entry> entries, List<String> roots,
|
||||
Map<Path, FileStamp> files, boolean incomplete, int parsed) {}
|
||||
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> args, IProgressMonitor monitor) throws Exception {
|
||||
String uri = (String) args.get(0);
|
||||
String key = args.get(1) instanceof String s ? s : null;
|
||||
int line = ((Number) args.get(2)).intValue(), column = ((Number) args.get(3)).intValue();
|
||||
boolean references = args.size() > 4 && Boolean.TRUE.equals(args.get(4));
|
||||
boolean declarations = args.size() > 5 && Boolean.TRUE.equals(args.get(5));
|
||||
ITypeRoot selectedRoot = JDTUtils.resolveTypeRoot(uri);
|
||||
IJavaProject project = selectedRoot == null ? project(uri) : selectedRoot.getJavaProject();
|
||||
if (project == null) return Map.of("locations", List.of(), "keys", List.of(), "roots", List.of(), "incomplete", true);
|
||||
Index index = index(project, monitor);
|
||||
Set<Map<String, Object>> keys = new LinkedHashSet<>();
|
||||
Set<Location> locations = new LinkedHashSet<>();
|
||||
String selected = null;
|
||||
if (key == null && selectedRoot != null && references) {
|
||||
var element = JDTUtils.findElementAtSelection(selectedRoot, line, column,
|
||||
JavaLanguageServerPlugin.getPreferencesManager(), monitor);
|
||||
if (element != null) selected = element.getHandleIdentifier();
|
||||
}
|
||||
for (Entry entry : index.entries) {
|
||||
check(monitor);
|
||||
Location location = entry.location;
|
||||
if (key != null) {
|
||||
if (matches(entry.name, key, entry.relaxed)) {
|
||||
if (!entry.handle.isEmpty() && references) {
|
||||
var element = JavaCore.create(entry.handle);
|
||||
if (element != null && element.exists()) {
|
||||
List<Location> usages = new ArrayList<>();
|
||||
new ReferencesHandler(JavaLanguageServerPlugin.getPreferencesManager())
|
||||
.search(element, usages, monitor, declarations);
|
||||
locations.addAll(usages);
|
||||
}
|
||||
} else {
|
||||
if (location == null && !entry.handle.isEmpty()) location = location(entry.handle);
|
||||
if (location != null) locations.add(location);
|
||||
}
|
||||
keys.add(Map.of("name", entry.name, "relaxed", entry.relaxed));
|
||||
}
|
||||
} else if ((!entry.handle.isEmpty() && entry.handle.equals(selected)) ||
|
||||
(location != null && sameUri(location.getUri(), uri) && contains(location, line, column))) {
|
||||
keys.add(Map.of("name", entry.name, "relaxed", entry.relaxed));
|
||||
}
|
||||
if (locations.size() >= 2000) break;
|
||||
}
|
||||
// Reverse Find Usages joins property consumers with the binding member's
|
||||
// ordinary Java usages. Definition on a string only returns config keys.
|
||||
if (key == null && references && !keys.isEmpty()) {
|
||||
Set<String> searched = new HashSet<>();
|
||||
for (Entry entry : index.entries) {
|
||||
check(monitor);
|
||||
boolean related = keys.stream().anyMatch(pattern ->
|
||||
matches(entry.name, (String) pattern.get("name"), entry.relaxed) ||
|
||||
matches((String) pattern.get("name"), entry.name, Boolean.TRUE.equals(pattern.get("relaxed"))));
|
||||
if (!related) continue;
|
||||
if (entry.location != null) locations.add(entry.location);
|
||||
else if (!entry.handle.isEmpty() && searched.add(entry.handle)) {
|
||||
IJavaElement element = JavaCore.create(entry.handle);
|
||||
if (element != null && element.exists()) {
|
||||
List<Location> usages = new ArrayList<>();
|
||||
new ReferencesHandler(JavaLanguageServerPlugin.getPreferencesManager()).search(element, usages, monitor, declarations);
|
||||
locations.addAll(usages);
|
||||
}
|
||||
}
|
||||
if (locations.size() >= 2000) break;
|
||||
}
|
||||
}
|
||||
return Map.of("locations", locations, "keys", keys, "roots", index.roots,
|
||||
"incomplete", index.incomplete || locations.size() >= 2000,
|
||||
"parsedUnits", index.parsed, "revision", index.revision);
|
||||
}
|
||||
|
||||
private static boolean sameUri(String a, String b) {
|
||||
URI left = URI.create(a), right = URI.create(b);
|
||||
if (left.equals(right)) return true;
|
||||
if (!"file".equals(left.getScheme()) || !"file".equals(right.getScheme())) return false;
|
||||
try { return Path.of(left).toFile().getCanonicalFile().equals(Path.of(right).toFile().getCanonicalFile()); }
|
||||
catch (java.io.IOException e) { return false; }
|
||||
}
|
||||
private static boolean contains(Location l, int line, int col) {
|
||||
var r = l.getRange();
|
||||
return (line > r.getStart().getLine() || line == r.getStart().getLine() && col >= r.getStart().getCharacter()) &&
|
||||
(line < r.getEnd().getLine() || line == r.getEnd().getLine() && col < r.getEnd().getCharacter());
|
||||
}
|
||||
private static void check(IProgressMonitor monitor) { if (monitor.isCanceled()) throw new OperationCanceledException(); }
|
||||
private static IJavaProject project(String uri) {
|
||||
Path path;
|
||||
try { path = Path.of(URI.create(uri)).toFile().getCanonicalFile().toPath(); } catch (Exception e) { return null; }
|
||||
IJavaProject best = null;
|
||||
int length = -1;
|
||||
for (var p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
|
||||
if (!p.isOpen() || p.getLocation() == null) continue;
|
||||
var candidate = JavaCore.create(p);
|
||||
Path root;
|
||||
try { root = p.getLocation().toFile().getCanonicalFile().toPath(); } catch (java.io.IOException e) { continue; }
|
||||
if (candidate.exists() && path.startsWith(root) && root.getNameCount() > length) {
|
||||
best = candidate; length = root.getNameCount();
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
private static Location location(String handle) throws JavaModelException {
|
||||
IJavaElement element = JavaCore.create(handle);
|
||||
if (element == null || !element.exists()) return null;
|
||||
Location result = JDTUtils.toLocation(element);
|
||||
if (result == null && element instanceof IMember member && member.getClassFile() != null)
|
||||
result = JDTUtils.toLocation(member.getClassFile());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static synchronized Index index(IJavaProject project, IProgressMonitor monitor) throws Exception {
|
||||
long revision = REVISION.get();
|
||||
String id = project.getHandleIdentifier();
|
||||
Map<String, ICompilationUnit> copies = new TreeMap<>();
|
||||
for (ICompilationUnit copy : JavaCore.getWorkingCopies(null)) copies.put(copy.getPrimary().getHandleIdentifier(), copy);
|
||||
for (ICompilationUnit copy : JavaCore.getWorkingCopies(JavaLanguageServerPlugin.getInstance().getWorkingCopyOwner()))
|
||||
copies.put(copy.getPrimary().getHandleIdentifier(), copy);
|
||||
var digest = java.security.MessageDigest.getInstance("SHA-256");
|
||||
for (var entry : copies.entrySet()) {
|
||||
check(monitor);
|
||||
digest.update(entry.getKey().getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
String source = entry.getValue().getSource();
|
||||
if (source != null) digest.update(source.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
String workingCopies = HexFormat.of().formatHex(digest.digest());
|
||||
Index cached = CACHE.get(id);
|
||||
if (cached != null && cached.revision == revision && cached.workingCopies.equals(workingCopies)) {
|
||||
boolean valid = true;
|
||||
for (var entry : cached.files.entrySet()) {
|
||||
check(monitor);
|
||||
if (!entry.getValue().equals(stamp(entry.getKey()))) { valid = false; break; }
|
||||
}
|
||||
if (valid) return cached;
|
||||
}
|
||||
Builder builder = new Builder(monitor);
|
||||
Set<String> units = new HashSet<>(), roots = new LinkedHashSet<>();
|
||||
int visited = 0;
|
||||
for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {
|
||||
check(monitor);
|
||||
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
|
||||
if (root.getResource() != null && root.getResource().getLocationURI() != null)
|
||||
roots.add(root.getResource().getLocationURI().toString());
|
||||
if (root.getJavaProject().getProject().getLocationURI() != null)
|
||||
roots.add(root.getJavaProject().getProject().getLocationURI().toString());
|
||||
if (root.getResource() != null && root.getResource().getLocation() != null)
|
||||
builder.metadataDirectory(root.getResource().getLocation().toFile().toPath(), project);
|
||||
for (IJavaElement child : root.getChildren()) {
|
||||
if (!(child instanceof IPackageFragment pkg)) continue;
|
||||
for (ICompilationUnit unit : pkg.getCompilationUnits()) {
|
||||
check(monitor);
|
||||
unit = copies.getOrDefault(unit.getPrimary().getHandleIdentifier(), unit);
|
||||
if (!units.add(unit.getHandleIdentifier())) continue;
|
||||
if (++visited > MAX_UNITS || builder.entries.size() >= MAX_ENTRIES) { builder.incomplete = true; break; }
|
||||
String source = unit.getSource();
|
||||
if (source == null) continue;
|
||||
if (source.length() > MAX_BYTES) { builder.incomplete = true; continue; }
|
||||
// Cheap lexical filter only chooses candidates; all accepted symbols
|
||||
// below are verified by JDT bindings, including constants and imports.
|
||||
if (source.contains("ConfigurationProperties") || source.contains("Value") || source.contains("getProperty") || source.contains("getRequiredProperty"))
|
||||
builder.parse(unit);
|
||||
}
|
||||
}
|
||||
} else if (root.isArchive()) {
|
||||
builder.metadata(root, project);
|
||||
}
|
||||
}
|
||||
// Resource roots are not necessarily Java package roots (e.g. Maven resources).
|
||||
// Return project locations as well; the client excludes nested independent modules.
|
||||
roots.add(project.getProject().getLocationURI().toString());
|
||||
builder.metadataDirectory(project.getProject().getLocation().toFile().toPath().resolve("src/main/resources"), project);
|
||||
Index result = new Index(revision, workingCopies, List.copyOf(builder.entries), List.copyOf(roots), Map.copyOf(builder.files), builder.incomplete, builder.parsed);
|
||||
CACHE.remove(id);
|
||||
while (!CACHE.isEmpty() && (CACHE.size() >= 8 ||
|
||||
CACHE.values().stream().mapToInt(value -> value.entries.size()).sum() + result.entries.size() > MAX_ENTRIES))
|
||||
CACHE.remove(CACHE.keySet().iterator().next());
|
||||
CACHE.put(id, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Relaxed matching is reserved for binder/metadata entries. @Value and
|
||||
* Environment lookups retain their literal names; dots remain boundaries. */
|
||||
static boolean matches(String pattern, String key, boolean relaxed) {
|
||||
if (!relaxed) return pattern.equals(key);
|
||||
List<String> a = parts(pattern), b = parts(key);
|
||||
if (a.size() != b.size()) return false;
|
||||
for (int i = 0; i < a.size(); i++) if (!a.get(i).equals("*") && !a.get(i).equals(b.get(i))) return false;
|
||||
return true;
|
||||
}
|
||||
private static List<String> parts(String key) {
|
||||
List<String> result = new ArrayList<>();
|
||||
StringBuilder part = new StringBuilder();
|
||||
for (int i = 0; i < key.length(); i++) {
|
||||
char ch = key.charAt(i);
|
||||
if (ch == '[') {
|
||||
if (!part.isEmpty()) { result.add(canonical(part.toString())); part.setLength(0); }
|
||||
int end = key.indexOf(']', i + 1);
|
||||
if (end < 0) { part.append(key.substring(i)); break; }
|
||||
result.add(canonical(key.substring(i + 1, end))); i = end;
|
||||
} else if (ch == '.') {
|
||||
if (!part.isEmpty() || i == 0 || key.charAt(i - 1) != ']') result.add(canonical(part.toString()));
|
||||
part.setLength(0);
|
||||
} else part.append(ch);
|
||||
}
|
||||
if (!part.isEmpty()) result.add(canonical(part.toString()));
|
||||
return result;
|
||||
}
|
||||
private static String canonical(String key) {
|
||||
return key.replace("-", "").replace("_", "").toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static final class Builder {
|
||||
final IProgressMonitor monitor;
|
||||
final List<Entry> entries = new ArrayList<>();
|
||||
final Map<Path, FileStamp> files = new LinkedHashMap<>();
|
||||
boolean incomplete;
|
||||
int parsed;
|
||||
Builder(IProgressMonitor monitor) { this.monitor = monitor; }
|
||||
void add(String key, IJavaElement element) {
|
||||
if (key.length() > 1024 || entries.size() >= MAX_ENTRIES) { incomplete = true; return; }
|
||||
if (element != null) entries.add(new Entry(key, element.getHandleIdentifier(), null, true));
|
||||
}
|
||||
void use(String key, ICompilationUnit unit, ASTNode node) {
|
||||
if (key.length() > 1024 || entries.size() >= MAX_ENTRIES) { incomplete = true; return; }
|
||||
if (key.isBlank() || key.contains("${") || key.contains("#{")) return;
|
||||
try { entries.add(new Entry(key, "", JDTUtils.toLocation(unit, node.getStartPosition(), node.getLength()), false)); }
|
||||
catch (JavaModelException e) { incomplete = true; }
|
||||
}
|
||||
void parse(ICompilationUnit unit) {
|
||||
check(monitor);
|
||||
ASTParser parser = ASTParser.newParser(AST.getJLSLatest());
|
||||
parser.setSource(unit);
|
||||
parser.setResolveBindings(true);
|
||||
parser.setWorkingCopyOwner(JavaLanguageServerPlugin.getInstance().getWorkingCopyOwner());
|
||||
parser.setBindingsRecovery(false);
|
||||
CompilationUnit tree = (CompilationUnit) parser.createAST(monitor);
|
||||
parsed++;
|
||||
tree.accept(new ASTVisitor() {
|
||||
@Override public void preVisit(ASTNode node) { check(monitor); }
|
||||
@Override public boolean visit(NormalAnnotation node) { annotation(node); return true; }
|
||||
@Override public boolean visit(SingleMemberAnnotation node) { annotation(node); return true; }
|
||||
@Override public boolean visit(MarkerAnnotation node) { annotation(node); return true; }
|
||||
private void annotation(Annotation node) {
|
||||
IAnnotationBinding binding = node.resolveAnnotationBinding();
|
||||
if (binding == null) return;
|
||||
String name = binding.getAnnotationType().getQualifiedName();
|
||||
if (name.equals(PROPERTIES)) {
|
||||
String prefix = annotationValue(binding, "prefix");
|
||||
if (prefix == null || prefix.isEmpty()) prefix = annotationValue(binding, "value");
|
||||
if (prefix == null) prefix = "";
|
||||
ASTNode owner = node.getParent();
|
||||
if (owner instanceof AbstractTypeDeclaration type) {
|
||||
bind(prefix, type.resolveBinding(), new HashSet<>(), 0);
|
||||
} else if (owner instanceof MethodDeclaration method && method.resolveBinding() != null) {
|
||||
add(prefix, method.resolveBinding().getJavaElement());
|
||||
bind(prefix, method.resolveBinding().getReturnType(), new HashSet<>(), 0);
|
||||
}
|
||||
} else if (name.equals(VALUE)) {
|
||||
String value = annotationValue(binding, "value");
|
||||
ASTNode expression = node;
|
||||
if (node instanceof SingleMemberAnnotation single) expression = single.getValue();
|
||||
else if (node instanceof NormalAnnotation normal) {
|
||||
for (Object pair : normal.values()) if (pair instanceof MemberValuePair p && p.getName().getIdentifier().equals("value")) expression = p.getValue();
|
||||
}
|
||||
if (value != null) placeholders(value, unit, expression);
|
||||
}
|
||||
}
|
||||
@Override public boolean visit(MethodInvocation node) {
|
||||
IMethodBinding method = node.resolveMethodBinding();
|
||||
if (method != null && (method.getName().equals("getProperty") || method.getName().equals("getRequiredProperty")) &&
|
||||
subtype(method.getDeclaringClass(), RESOLVER, new HashSet<>()) && !node.arguments().isEmpty()) {
|
||||
Expression arg = (Expression) node.arguments().get(0);
|
||||
Object constant = arg.resolveConstantExpressionValue();
|
||||
if (constant instanceof String key) use(key, unit, arg);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
void placeholders(String text, ICompilationUnit unit, ASTNode node) {
|
||||
// Include nested default placeholders, but never a dynamically composed name.
|
||||
for (int at = text.indexOf("${"); at >= 0; at = text.indexOf("${", at + 2)) {
|
||||
int end = at + 2;
|
||||
while (end < text.length() && text.charAt(end) != ':' && text.charAt(end) != '}') end++;
|
||||
if (end < text.length()) use(text.substring(at + 2, end), unit, node);
|
||||
}
|
||||
}
|
||||
void bind(String prefix, ITypeBinding type, Set<String> visiting, int depth) {
|
||||
check(monitor);
|
||||
if (type == null || type.isRecovered() || type.isPrimitive() || type.isEnum()) return;
|
||||
String qualified = type.getErasure().getQualifiedName();
|
||||
if (qualified.startsWith("java.") || qualified.startsWith("javax.")) return;
|
||||
if (depth > 12 || !visiting.add(type.getKey())) return;
|
||||
try {
|
||||
if (!prefix.isEmpty()) add(prefix, type.getJavaElement());
|
||||
List<IMethodBinding> constructors = Arrays.stream(type.getDeclaredMethods())
|
||||
.filter(m -> m.isConstructor() && !Modifier.isPrivate(m.getModifiers())).toList();
|
||||
for (IMethodBinding constructor : constructors) {
|
||||
boolean explicit = Arrays.stream(constructor.getAnnotations()).anyMatch(a ->
|
||||
a.getAnnotationType().getQualifiedName().equals("org.springframework.boot.context.properties.bind.ConstructorBinding") ||
|
||||
a.getAnnotationType().getQualifiedName().equals("org.springframework.boot.context.properties.ConstructorBinding"));
|
||||
if (!explicit && constructors.size() != 1) continue;
|
||||
String[] parameters = constructor.getParameterNames();
|
||||
for (int i = 0; i < parameters.length; i++) {
|
||||
String name = parameters[i];
|
||||
for (IAnnotationBinding annotation : constructor.getParameterAnnotations(i)) {
|
||||
if (annotation.getAnnotationType().getQualifiedName().equals("org.springframework.boot.context.properties.bind.Name")) {
|
||||
String alias = annotationValue(annotation, "value");
|
||||
if (alias != null) name = alias;
|
||||
}
|
||||
}
|
||||
// Prefer fields/accessors for ordinary parameters; aliases and
|
||||
// constructor-only properties still have a navigable declaration.
|
||||
final String parameterName = name;
|
||||
if (Arrays.stream(type.getDeclaredFields()).noneMatch(f -> f.getName().equals(parameterName))) {
|
||||
add(join(prefix, name), constructor.getJavaElement());
|
||||
nested(join(prefix, name), constructor.getParameterTypes()[i], constructor.getJavaElement(), visiting, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Set<String> names = new HashSet<>();
|
||||
for (ITypeBinding current = type; current != null && !current.getQualifiedName().equals("java.lang.Object"); current = current.getSuperclass()) {
|
||||
for (IVariableBinding field : current.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic() || !names.add(field.getName())) continue;
|
||||
String key = join(prefix, field.getName());
|
||||
add(key, field.getJavaElement());
|
||||
nested(key, field.getType(), field.getJavaElement(), visiting, depth + 1);
|
||||
}
|
||||
for (IMethodBinding method : current.getDeclaredMethods()) {
|
||||
if (Modifier.isStatic(method.getModifiers()) || method.isConstructor()) continue;
|
||||
String name = method.getName();
|
||||
String property = null;
|
||||
ITypeBinding propertyType = null;
|
||||
if (name.startsWith("set") && name.length() > 3 && method.getParameterTypes().length == 1) {
|
||||
property = name.substring(3); propertyType = method.getParameterTypes()[0];
|
||||
} else if (name.startsWith("get") && name.length() > 3 && method.getParameterTypes().length == 0) {
|
||||
property = name.substring(3); propertyType = method.getReturnType();
|
||||
}
|
||||
if (property != null) {
|
||||
property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
|
||||
String key = join(prefix, property);
|
||||
add(key, method.getJavaElement());
|
||||
if (names.add(property)) nested(key, propertyType, method.getJavaElement(), visiting, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally { visiting.remove(type.getKey()); }
|
||||
}
|
||||
void nested(String key, ITypeBinding type, IJavaElement owner, Set<String> visiting, int depth) {
|
||||
if (type == null) return;
|
||||
if (type.isArray()) { add(key + "[*]", owner); bind(key + "[*]", type.getElementType(), visiting, depth); return; }
|
||||
String raw = type.getErasure().getQualifiedName();
|
||||
if (subtype(type, "java.util.Map", new HashSet<>())) {
|
||||
add(key + ".*", owner);
|
||||
var args = type.getTypeArguments();
|
||||
if (args.length == 2) bind(key + ".*", args[1], visiting, depth);
|
||||
} else if (subtype(type, "java.util.Collection", new HashSet<>())) {
|
||||
add(key + "[*]", owner);
|
||||
var args = type.getTypeArguments();
|
||||
if (args.length == 1) bind(key + "[*]", args[0], visiting, depth);
|
||||
} else if (!type.isPrimitive() && !type.isEnum() && !raw.startsWith("java.") && !raw.startsWith("javax.")) {
|
||||
bind(key, type, visiting, depth);
|
||||
}
|
||||
}
|
||||
void metadata(IPackageFragmentRoot root, IJavaProject project) {
|
||||
check(monitor);
|
||||
Path path = root.getPath().toFile().toPath();
|
||||
if (!root.isExternal() && root.getResource() != null && root.getResource().getLocation() != null)
|
||||
path = root.getResource().getLocation().toFile().toPath();
|
||||
files.put(path, stamp(path));
|
||||
if (!Files.isRegularFile(path)) return;
|
||||
try (ZipFile zip = new ZipFile(path.toFile())) {
|
||||
for (String filename : List.of("spring-configuration-metadata.json", "additional-spring-configuration-metadata.json")) {
|
||||
var entry = zip.getEntry("META-INF/" + filename);
|
||||
if (entry == null) continue;
|
||||
if (entry.getSize() > MAX_BYTES) { incomplete = true; continue; }
|
||||
JsonObject metadata;
|
||||
try (var stream = zip.getInputStream(entry)) {
|
||||
byte[] bytes = stream.readNBytes(MAX_BYTES + 1);
|
||||
if (bytes.length > MAX_BYTES) { incomplete = true; continue; }
|
||||
metadata = JsonParser.parseString(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
}
|
||||
metadataObject(metadata, project);
|
||||
}
|
||||
} catch (Exception e) { if (e instanceof OperationCanceledException) throw (OperationCanceledException)e; incomplete = true; }
|
||||
}
|
||||
void metadataObject(JsonObject metadata, IJavaProject project) throws JavaModelException {
|
||||
JsonArray groups = metadata.has("groups") ? metadata.getAsJsonArray("groups") : new JsonArray();
|
||||
for (JsonElement value : groups) {
|
||||
check(monitor);
|
||||
JsonObject group = value.getAsJsonObject();
|
||||
String name = string(group, "name"), source = string(group, "sourceType");
|
||||
if (source == null) source = string(group, "type");
|
||||
if (name != null && source != null) add(name, project.findType(source.replace('$', '.'), monitor));
|
||||
}
|
||||
if (!metadata.has("properties")) return;
|
||||
for (JsonElement value : metadata.getAsJsonArray("properties")) {
|
||||
check(monitor);
|
||||
if (entries.size() >= MAX_ENTRIES) { incomplete = true; return; }
|
||||
JsonObject property = value.getAsJsonObject();
|
||||
String key = string(property, "name"), source = string(property, "sourceType"), prefix = "";
|
||||
if (key == null) continue;
|
||||
JsonObject owner = null;
|
||||
for (JsonElement groupValue : groups) {
|
||||
JsonObject group = groupValue.getAsJsonObject();
|
||||
String name = string(group, "name");
|
||||
if (name != null && key.startsWith(name + ".") && name.length() > prefix.length()) {
|
||||
prefix = name; owner = group;
|
||||
}
|
||||
}
|
||||
if (source == null && owner != null) source = string(owner, "type");
|
||||
if (source == null && owner != null) source = string(owner, "sourceType");
|
||||
if (source == null) continue;
|
||||
IType type = project.findType(source.replace('$', '.'), monitor);
|
||||
if (type == null) continue;
|
||||
String leaf = key.substring(prefix.isEmpty() ? 0 : prefix.length() + 1);
|
||||
IJavaElement target = member(type, leaf, new HashSet<>());
|
||||
if (target == null && owner != null && string(owner, "sourceMethod") != null) {
|
||||
String declaring = string(owner, "sourceType");
|
||||
IType factory = declaring == null ? null : project.findType(declaring.replace('$', '.'), monitor);
|
||||
if (factory != null) {
|
||||
String methodName = string(owner, "sourceMethod").split("\\(", 2)[0];
|
||||
for (IMethod method : factory.getMethods()) if (method.getElementName().equals(methodName)) { target = method; break; }
|
||||
}
|
||||
}
|
||||
add(key, target == null ? type : target);
|
||||
}
|
||||
}
|
||||
void metadataDirectory(Path directory, IJavaProject project) {
|
||||
for (String name : List.of("spring-configuration-metadata.json", "additional-spring-configuration-metadata.json")) {
|
||||
Path file = directory.resolve("META-INF").resolve(name);
|
||||
files.put(file, stamp(file));
|
||||
if (!Files.isRegularFile(file)) continue;
|
||||
try {
|
||||
if (Files.size(file) > MAX_BYTES) { incomplete = true; continue; }
|
||||
try (var stream = Files.newInputStream(file)) {
|
||||
byte[] bytes = stream.readNBytes(MAX_BYTES + 1);
|
||||
if (bytes.length > MAX_BYTES) { incomplete = true; continue; }
|
||||
metadataObject(JsonParser.parseString(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(), project);
|
||||
}
|
||||
} catch (Exception e) { if (e instanceof OperationCanceledException) throw (OperationCanceledException)e; incomplete = true; }
|
||||
}
|
||||
}
|
||||
}
|
||||
private static IJavaElement member(IType type, String key, Set<String> seen) throws JavaModelException {
|
||||
if (type == null || !seen.add(type.getHandleIdentifier())) return null;
|
||||
String part = key.split("\\.", 2)[0];
|
||||
for (IField field : type.getFields()) if (canonical(field.getElementName()).equals(canonical(part))) {
|
||||
if (!key.contains(".")) return field;
|
||||
String signature = Signature.toString(Signature.getTypeErasure(field.getTypeSignature()));
|
||||
String[][] resolved = type.resolveType(signature);
|
||||
IType nested = type.getJavaProject().findType(signature);
|
||||
if (nested == null && resolved != null && resolved.length == 1)
|
||||
nested = type.getJavaProject().findType(resolved[0][0] + "." + resolved[0][1]);
|
||||
IJavaElement found = member(nested, key.substring(key.indexOf('.') + 1), seen);
|
||||
return found == null ? field : found;
|
||||
}
|
||||
for (IMethod method : type.getMethods()) {
|
||||
String name = method.getElementName();
|
||||
if (name.length() > 3 && (name.startsWith("get") || name.startsWith("set")) && canonical(name.substring(3)).equals(canonical(part))) return method;
|
||||
}
|
||||
String parent = type.getSuperclassName();
|
||||
if (parent != null) {
|
||||
String[][] resolved = type.resolveType(parent);
|
||||
if (resolved != null && resolved.length == 1)
|
||||
return member(type.getJavaProject().findType(resolved[0][0] + "." + resolved[0][1]), key, seen);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private static String string(JsonObject object, String key) {
|
||||
return object.has(key) && object.get(key).isJsonPrimitive() ? object.get(key).getAsString() : null;
|
||||
}
|
||||
private static String annotationValue(IAnnotationBinding binding, String name) {
|
||||
for (IMemberValuePairBinding pair : binding.getAllMemberValuePairs())
|
||||
if (pair.getName().equals(name) && pair.getValue() instanceof String s) return s;
|
||||
return null;
|
||||
}
|
||||
private static String join(String prefix, String name) { return prefix.isEmpty() ? name : prefix + "." + name; }
|
||||
private static boolean subtype(ITypeBinding type, String name, Set<String> seen) {
|
||||
if (type == null || !seen.add(type.getKey())) return false;
|
||||
if (type.getErasure().getQualifiedName().equals(name)) return true;
|
||||
for (ITypeBinding face : type.getInterfaces()) if (subtype(face, name, seen)) return true;
|
||||
return subtype(type.getSuperclass(), name, seen);
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
"""Real JDT LS configuration-navigation regression and warm-query benchmark.
|
||||
Run with Java 25 on PATH: python3 configuration.py /path/to/jdtls
|
||||
Fixtures use small Spring API stubs; no Maven/network/build of a user's project.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
home = pathlib.Path(sys.argv[1]).resolve()
|
||||
bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-configuration-'))
|
||||
project = work / 'project'
|
||||
source_dir = project / 'src'
|
||||
source_dir.mkdir(parents=True)
|
||||
|
||||
def write(relative, text):
|
||||
file = source_dir / relative
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_text(text)
|
||||
return file
|
||||
|
||||
write('org/springframework/boot/context/properties/ConfigurationProperties.java', '''package org.springframework.boot.context.properties;
|
||||
public @interface ConfigurationProperties { String value() default ""; String prefix() default ""; }''')
|
||||
write('org/springframework/boot/context/properties/bind/Name.java', 'package org.springframework.boot.context.properties.bind; public @interface Name { String value(); }')
|
||||
write('org/springframework/beans/factory/annotation/Value.java', '''package org.springframework.beans.factory.annotation;
|
||||
public @interface Value { String value(); }''')
|
||||
write('org/springframework/core/env/PropertyResolver.java', '''package org.springframework.core.env;
|
||||
public interface PropertyResolver { String getProperty(String key); String getRequiredProperty(String key); }''')
|
||||
write('org/springframework/core/env/Environment.java', '''package org.springframework.core.env;
|
||||
public interface Environment extends PropertyResolver {}''')
|
||||
source = '''package demo;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
@ConfigurationProperties(prefix="app")
|
||||
class Settings extends Parent {
|
||||
int timeOut;
|
||||
Nested nested;
|
||||
java.util.List<Nested> clients;
|
||||
java.util.Map<String, Nested> routes;
|
||||
java.util.List<String> tags;
|
||||
java.util.Map<String, String> labels;
|
||||
public int getTimeOut() { return timeOut; }
|
||||
public void setTimeOut(int value) { timeOut = value; }
|
||||
}
|
||||
class Parent { boolean enabled; }
|
||||
class Nested { String url; }
|
||||
@ConfigurationProperties("record")
|
||||
record RecordSettings(String name, int count) {}
|
||||
@ConfigurationProperties("constructor")
|
||||
class ConstructorSettings {
|
||||
ConstructorSettings(@org.springframework.boot.context.properties.bind.Name("remote-name") String name) {}
|
||||
}
|
||||
class Consumers {
|
||||
static final String KEY = "app.time-out";
|
||||
@Value("${app.time-out:30}") String timeout;
|
||||
@Value("${app.missing:${app.backup:42}}") String fallback;
|
||||
String call(Environment env) { return env.getProperty(KEY); }
|
||||
String required(Environment env) { return env.getRequiredProperty("app.required"); }
|
||||
String dynamic(Environment env, String key) { return env.getProperty(key); }
|
||||
String unrelated(Fake env) { return env.getProperty("app.time-out"); }
|
||||
@ConfigurationProperties("bean") Nested bean() { return new Nested(); }
|
||||
}
|
||||
class Fake { String getProperty(String name) { return name; } }
|
||||
'''
|
||||
file = write('demo/Settings.java', source)
|
||||
if os.environ.get('OPENIDEA_CONFIGURATION_STRESS') == '1':
|
||||
for i in range(3000):
|
||||
write(f'noise/Plain{i}.java', f'package noise; class Plain{i} {{ int number; }}')
|
||||
for i in range(100):
|
||||
write(f'noise/Config{i}.java', f'package noise; @org.springframework.boot.context.properties.ConfigurationProperties(prefix="stress{i}") class Config{i} {{ int value; }}')
|
||||
write('demo/NotSpring.java', '''package demo;
|
||||
@interface ConfigurationProperties { String prefix(); }
|
||||
@ConfigurationProperties(prefix="fake") class NotSpring { int timeOut; }
|
||||
''')
|
||||
local_metadata = project / 'src/main/resources/META-INF'
|
||||
local_metadata.mkdir(parents=True)
|
||||
(local_metadata / 'additional-spring-configuration-metadata.json').write_text(json.dumps({
|
||||
'groups': [{'name': 'extra', 'sourceType': 'demo.Nested', 'type': 'demo.Nested'}],
|
||||
'properties': [{'name': 'extra.url', 'sourceType': 'demo.Nested'}]
|
||||
}))
|
||||
# A dependency with metadata and attached source exercises actual library locations.
|
||||
libsource = work / 'libsrc/vendor/LibrarySettings.java'
|
||||
libsource.parent.mkdir(parents=True)
|
||||
libsource.write_text('package vendor; public class LibrarySettings { public int port; public int getPort() { return port; } }')
|
||||
classes = work / 'libclasses'
|
||||
classes.mkdir()
|
||||
subprocess.run(['javac', '--release', '21', '-d', str(classes), str(libsource)], check=True)
|
||||
library = work / 'library.jar'
|
||||
metadata = {'groups': [{'name': 'vendor', 'type': 'vendor.LibrarySettings', 'sourceType': 'vendor.LibrarySettings'}],
|
||||
'properties': [{'name': 'vendor.port', 'type': 'java.lang.Integer', 'sourceType': 'vendor.LibrarySettings'}]}
|
||||
with zipfile.ZipFile(library, 'w') as z:
|
||||
z.write(classes / 'vendor/LibrarySettings.class', 'vendor/LibrarySettings.class')
|
||||
z.writestr('META-INF/spring-configuration-metadata.json', json.dumps(metadata))
|
||||
sourcejar = work / 'library-sources.jar'
|
||||
with zipfile.ZipFile(sourcejar, 'w') as z:
|
||||
z.write(libsource, 'vendor/LibrarySettings.java')
|
||||
(project / '.project').write_text('<projectDescription><name>configuration</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
spring_jar = os.environ.get('OPENIDEA_SPRING_BOOT_JAR')
|
||||
extra_classpath = f'<classpathentry kind="lib" path="{pathlib.Path(spring_jar).resolve()}"/>' if spring_jar else ''
|
||||
(project / '.classpath').write_text(f'<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="lib" path="{library}" sourcepath="{sourcejar}"/>{extra_classpath}<classpathentry kind="output" path="bin"/></classpath>')
|
||||
config = work / 'config'
|
||||
config.mkdir()
|
||||
name = {'Darwin': 'config_mac', 'Windows': 'config_win'}.get(platform.system(), 'config_linux')
|
||||
names = ([name + '_arm'] if platform.machine().lower() in ('arm64', 'aarch64') else []) + [name]
|
||||
(config / 'config.ini').write_bytes(next(home / n / 'config.ini' for n in names if (home / n / 'config.ini').exists()).read_bytes())
|
||||
log = (work / 'stderr.log').open('w')
|
||||
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
|
||||
messages = queue.Queue()
|
||||
lock = threading.Lock()
|
||||
def send(message):
|
||||
data = json.dumps(message).encode()
|
||||
with lock:
|
||||
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
|
||||
proc.stdin.flush()
|
||||
def read():
|
||||
while True:
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if not line: return
|
||||
if line == b'\r\n': break
|
||||
k, v = line.decode().split(':', 1)
|
||||
headers[k.lower()] = v.strip()
|
||||
message = json.loads(proc.stdout.read(int(headers['content-length'])))
|
||||
if 'method' in message and 'id' in message:
|
||||
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
|
||||
else: messages.put(message)
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
sequence = 0
|
||||
transcript = []
|
||||
def request(method, params):
|
||||
global sequence
|
||||
sequence += 1
|
||||
send({'jsonrpc': '2.0', 'id': sequence, 'method': method, 'params': params})
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
|
||||
transcript.append(msg)
|
||||
if msg.get('id') == sequence:
|
||||
if 'error' in msg: raise RuntimeError(msg['error'])
|
||||
return msg.get('result')
|
||||
raise TimeoutError(method)
|
||||
def query(key, uri=None, line=0, col=0):
|
||||
return request('workspace/executeCommand', {'command': 'openidea.java.configuration', 'arguments': [uri or (project / 'application.yml').as_uri(), key, line, col, key is None, False]})
|
||||
def names(result):
|
||||
return {p['name'] for p in result['keys']}
|
||||
try:
|
||||
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'configuration'}], 'capabilities': {'textDocument': {'definition': {'linkSupport': False}}}, 'initializationOptions': {'bundles': [str(bundle)], 'extendedClientCapabilities': {'classFileContentsSupport': True}, 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
|
||||
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': file.as_uri(), 'languageId': 'java', 'version': 1, 'text': source}}})
|
||||
request('java/buildWorkspace', True)
|
||||
assert 'openidea.java.configuration' in init['capabilities']['executeCommandProvider']['commands'], init
|
||||
results = {}
|
||||
for key in ['app', 'vendor', 'app.time-out', 'app.enabled', 'app.nested.url', 'app.clients[0].url', 'app.routes.east.url', 'app.tags[0]', 'app.labels.region', 'app.labels[region.name]', 'constructor.remote-name', 'record.name', 'bean.url', 'app.backup', 'app.required', 'vendor.port', 'extra.url']:
|
||||
start = time.perf_counter()
|
||||
result = query(key)
|
||||
results[key] = {'seconds': time.perf_counter() - start, 'response': result}
|
||||
assert result['locations'], (key, result)
|
||||
attached = request('java/classFileContents', {'uri': results['vendor.port']['response']['locations'][0]['uri']})
|
||||
assert attached and 'LibrarySettings' in attached and 'port' in attached, attached
|
||||
if spring_jar:
|
||||
for key in ['server.port', 'spring.datasource.url', 'spring.jackson.date-format']:
|
||||
result = query(key)
|
||||
assert result['locations'], (key, result)
|
||||
assert all(loc['uri'].startswith('jdt://') for loc in result['locations']), result
|
||||
results[key] = {'response': result}
|
||||
if key == 'server.port':
|
||||
decompiled = request('java/classFileContents', {'uri': result['locations'][0]['uri']})
|
||||
assert decompiled and 'ServerProperties' in decompiled and 'port' in decompiled, decompiled
|
||||
assert not query('app.tags[0].value')['locations']
|
||||
assert not query('app.labels.region.coder')['locations']
|
||||
assert not query('fake.time-out')['locations']
|
||||
assert not query('app.does-not-exist')['locations']
|
||||
metadata_file = local_metadata / 'additional-spring-configuration-metadata.json'
|
||||
metadata_file.write_text(metadata_file.read_text().replace('extra', 'newer'))
|
||||
assert query('newer.url')['locations']
|
||||
assert not query('extra.url')['locations']
|
||||
# Property references include member usages and consumers, without declarations.
|
||||
references = request('workspace/executeCommand', {'command': 'openidea.java.configuration',
|
||||
'arguments': [(project / 'application.yml').as_uri(), 'app.time-out', 0, 0, True, False]})
|
||||
assert references['locations'], references
|
||||
assert any(loc['range']['start']['line'] == next(i for i, line in enumerate(source.splitlines()) if 'getProperty(KEY)' in line) for loc in references['locations']), references
|
||||
# 3 binding targets + @Value + Environment constant; Fake.getProperty excluded.
|
||||
timeout = query('app.time-out')
|
||||
assert len(timeout['locations']) == 5, timeout
|
||||
for needle, expected in [('int timeOut;', 'app.timeOut'), ('"${app.time-out:30}"', 'app.time-out'), ('env.getProperty(KEY)', 'app.time-out')]:
|
||||
line, text = next((i, s) for i, s in enumerate(source.splitlines()) if needle in s)
|
||||
col = text.index(needle) + (4 if needle == 'int timeOut;' else (len('env.getProperty(') if needle.startswith('env.') else 4))
|
||||
reverse = query(None, file.as_uri(), line, col)
|
||||
assert expected in names(reverse), (needle, reverse)
|
||||
warm = []
|
||||
for _ in range(20):
|
||||
start = time.perf_counter(); query('app.time-out'); warm.append(time.perf_counter() - start)
|
||||
# Unsaved changes must replace old keys, and closing must restore disk keys.
|
||||
changed = source.replace('prefix="app"', 'prefix="edited"').replace('${app.time-out:30}', '${edited.timeout:30}')
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didChange', 'params': {'textDocument': {'uri': file.as_uri(), 'version': 2}, 'contentChanges': [{'text': changed}]}})
|
||||
edit_start = time.perf_counter()
|
||||
updated = query('edited.time-out')
|
||||
edit_ms = (time.perf_counter() - edit_start) * 1000
|
||||
assert updated['locations'], updated
|
||||
assert not query('app.nested.url')['locations']
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didClose', 'params': {'textDocument': {'uri': file.as_uri()}}})
|
||||
restored = query('app.nested.url')
|
||||
assert restored['locations'], restored
|
||||
evidence = {'stress': os.environ.get('OPENIDEA_CONFIGURATION_STRESS') == '1', 'editRebuildMs': edit_ms, 'cases': results, 'warmMedianMs': sorted(warm)[len(warm)//2] * 1000, 'warmMaxMs': max(warm) * 1000}
|
||||
(work / 'evidence.json').write_text(json.dumps(evidence, indent=2))
|
||||
print(json.dumps(evidence, indent=2))
|
||||
finally:
|
||||
(work / 'transcript.json').write_text(json.dumps(transcript, indent=2))
|
||||
proc.terminate(); proc.wait(timeout=20)
|
||||
print('Evidence:', work, file=sys.stderr)
|
||||
@@ -20,26 +20,22 @@ pub async fn doc_open(window: Window, state: State<'_, AppState>, path: PathBuf)
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_close(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<()> {
|
||||
let host = state.host.clone();
|
||||
let window = window.label().to_owned();
|
||||
blocking(move || ide_host::ops::doc::close(&host, &window, doc)).await
|
||||
pub fn doc_close(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<()> {
|
||||
ide_host::ops::doc::close(&state.host, window.label(), doc)
|
||||
}
|
||||
|
||||
/// Applies a CodeMirror change set; returns the new version. Rejects with
|
||||
/// `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_edit(
|
||||
pub fn doc_edit(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
base_version: u32,
|
||||
changes: ChangeSet,
|
||||
) -> IdeResult<u32> {
|
||||
let host = state.host.clone();
|
||||
let window = window.label().to_owned();
|
||||
blocking(move || ide_host::ops::doc::edit(&host, &window, doc, base_version, changes)).await
|
||||
ide_host::ops::doc::edit(&state.host, window.label(), doc, base_version, changes)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -96,15 +92,13 @@ pub async fn doc_set_encoding(
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_set_line_ending(
|
||||
pub fn doc_set_line_ending(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
line_ending: LineEnding,
|
||||
) -> IdeResult<()> {
|
||||
let host = state.host.clone();
|
||||
let window = window.label().to_owned();
|
||||
blocking(move || ide_host::ops::doc::doc_set_line_ending(&host, &window, doc, line_ending)).await
|
||||
ide_host::ops::doc::doc_set_line_ending(&state.host, window.label(), doc, line_ending)
|
||||
}
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
|
||||
@@ -337,30 +337,8 @@ pub async fn lsp_restart(window: Window, state: State<'_, AppState>, server: Ser
|
||||
/// Applies a (previewed) workspace edit, e.g. after rename confirmation.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn apply_workspace_edit(window: Window, state: State<'_, AppState>, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
ide_host::ops::lsp::apply_workspace_edit(&state.host, window.label(), edit).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn prepare_workspace_edit(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
edit: WorkspaceEdit,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
ide_host::ops::lsp::prepare_workspace_edit(&state.host, window.label(), edit).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn undo_workspace_edit(window: Window, state: State<'_, AppState>, id: u32) -> IdeResult<()> {
|
||||
ide_host::ops::lsp::undo_workspace_edit(&state.host, window.label(), id).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn redo_workspace_edit(window: Window, state: State<'_, AppState>, id: u32) -> IdeResult<()> {
|
||||
ide_host::ops::lsp::redo_workspace_edit(&state.host, window.label(), id).await
|
||||
pub fn apply_workspace_edit(window: Window, state: State<'_, AppState>, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
ide_host::ops::lsp::apply_workspace_edit(&state.host, window.label(), edit)
|
||||
}
|
||||
|
||||
/// Runs a server command (`workspace/executeCommand`), e.g. a completion item's
|
||||
|
||||
@@ -182,7 +182,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
caches::caches_schedule_invalidation,
|
||||
caches::app_restart,
|
||||
nav::index_status,
|
||||
nav::spring_route_sources,
|
||||
nav::find_files,
|
||||
nav::find_symbols,
|
||||
nav::mark_recent,
|
||||
@@ -228,9 +227,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_resend_diagnostics,
|
||||
lsp::lsp_restart,
|
||||
lsp::apply_workspace_edit,
|
||||
lsp::prepare_workspace_edit,
|
||||
lsp::undo_workspace_edit,
|
||||
lsp::redo_workspace_edit,
|
||||
lsp::lsp_execute_command,
|
||||
lsp::lsp_resolve_command,
|
||||
lsp::lsp_execute_code_action,
|
||||
|
||||
@@ -22,16 +22,6 @@ pub fn find_files(window: Window, state: State<'_, AppState>, query: String, lim
|
||||
ide_host::ops::nav::find_files(&state.host, window.label(), query, limit)
|
||||
}
|
||||
|
||||
/// Spring Web mapping sources for the request-path index of Search Everywhere.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn spring_route_sources(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<ide_host::ops::routes::RouteSource>> {
|
||||
ide_host::ops::routes::spring_route_sources(&state.host, window.label())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn find_symbols(
|
||||
|
||||
@@ -210,7 +210,6 @@ pub fn run() {
|
||||
let _ = &early_opens;
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.host.clear_workspace_edit_history_on_exit();
|
||||
state.host.shutdown_notebooks_on_exit();
|
||||
}
|
||||
// Cleanup must finish before update/restart replaces this process.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.34",
|
||||
"version": "0.1.33",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+2
-25
@@ -310,8 +310,6 @@ export const commands = {
|
||||
/** 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")),
|
||||
/** Spring Web mapping sources for the request-path index of Search Everywhere. */
|
||||
springRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("spring_route_sources")),
|
||||
findFiles: (query: string, limit: number) => typedError<FileMatch[], IdeError>(__TAURI_INVOKE("find_files", { query, limit })),
|
||||
findSymbols: (query: string, filter: SymbolFilter, limit: number) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("find_symbols", { query, filter, limit })),
|
||||
markRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("mark_recent", { path })),
|
||||
@@ -426,9 +424,6 @@ export const commands = {
|
||||
lspRestart: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_restart", { server })),
|
||||
/** Applies a (previewed) workspace edit, e.g. after rename confirmation. */
|
||||
applyWorkspaceEdit: (edit: WorkspaceEdit) => typedError<null, IdeError>(__TAURI_INVOKE("apply_workspace_edit", { edit })),
|
||||
prepareWorkspaceEdit: (edit: WorkspaceEdit) => typedError<WorkspaceEdit, IdeError>(__TAURI_INVOKE("prepare_workspace_edit", { edit })),
|
||||
undoWorkspaceEdit: (id: number) => typedError<null, IdeError>(__TAURI_INVOKE("undo_workspace_edit", { id })),
|
||||
redoWorkspaceEdit: (id: number) => typedError<null, IdeError>(__TAURI_INVOKE("redo_workspace_edit", { id })),
|
||||
/**
|
||||
* Runs a server command (`workspace/executeCommand`), e.g. a completion item's
|
||||
* follow-up command. Edits the server requests arrive via `workspace/applyEdit`.
|
||||
@@ -3091,9 +3086,7 @@ export type FileCoverage = {
|
||||
branchesCovered: number,
|
||||
};
|
||||
|
||||
export type FileEdit = { kind: "edit"; path: IpcPath; edits: TextEdit[];
|
||||
/** LSP TextDocumentEdit version; null/unversioned edits use content preconditions. */
|
||||
version?: number | null } | { kind: "create"; path: IpcPath; overwrite: boolean } | { kind: "rename"; from: IpcPath; to: IpcPath } | { kind: "delete"; path: IpcPath; recursive: boolean };
|
||||
export type FileEdit = { kind: "edit"; path: IpcPath; edits: TextEdit[] } | { kind: "create"; path: IpcPath; overwrite: boolean } | { kind: "rename"; from: IpcPath; to: IpcPath } | { kind: "delete"; path: IpcPath; recursive: boolean };
|
||||
|
||||
export type FileEntry = {
|
||||
name: string,
|
||||
@@ -3608,13 +3601,9 @@ export type IdeEvent =
|
||||
* The backend changed a document (reload from disk, formatting, refactoring).
|
||||
* The UI applies `changes` on top of `base_version`, yielding `version`.
|
||||
*/
|
||||
{ type: "docPatched"; doc: DocId; baseVersion: number; version: number; changes: TextChange[];
|
||||
/** Part of a grouped transaction; the editor must not record a file-local undo. */
|
||||
workspaceEdit?: boolean } |
|
||||
{ type: "docPatched"; doc: DocId; baseVersion: number; version: number; changes: TextChange[] } |
|
||||
/** A document's dirty flag changed (saved / modified externally). */
|
||||
{ type: "docDirty"; doc: DocId; dirty: boolean } |
|
||||
/** A complete workspace edit can be undone as one operation. */
|
||||
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[] } |
|
||||
/**
|
||||
* An open document's language changed (Settings › File Types, Override File
|
||||
* Type), or its UI mode (a framework's root marker appeared or went).
|
||||
@@ -5323,11 +5312,6 @@ export type RevisionChange = {
|
||||
|
||||
export type RootKind = "source" | "test" | "resources" | "testResources" | "excluded";
|
||||
|
||||
export type RouteSource = {
|
||||
path: string,
|
||||
text: string,
|
||||
};
|
||||
|
||||
export type RunConfig = RunConfig_Serialize | RunConfig_Deserialize;
|
||||
|
||||
export type RunConfig_Deserialize = {
|
||||
@@ -6489,13 +6473,6 @@ export type Workspace = Workspace_Serialize | Workspace_Deserialize;
|
||||
/** Edits to many files, applied atomically from the user's point of view. */
|
||||
export type WorkspaceEdit = {
|
||||
files: FileEdit[],
|
||||
/** Content fingerprints captured before presenting an edit for confirmation. */
|
||||
preconditions?: WorkspaceEditPrecondition[],
|
||||
};
|
||||
|
||||
export type WorkspaceEditPrecondition = {
|
||||
path: IpcPath,
|
||||
hash: string,
|
||||
};
|
||||
|
||||
export type WorkspaceSymbol = {
|
||||
|
||||
@@ -619,37 +619,3 @@ export function codePreviewExtensions(path: string): Promise<Extension> {
|
||||
export function _provideCodePreview(provider: ((path: string) => Promise<Extension>) | null) {
|
||||
codePreviewProvider = provider;
|
||||
}
|
||||
|
||||
let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null;
|
||||
|
||||
/** Undo/redo a refactoring through the same history used by editor commands. */
|
||||
export function workspaceEditHistory(id: number, redo = false): Promise<void> {
|
||||
return workspaceHistory ? workspaceHistory(id, redo) : Promise.reject(new Error("Editor history is unavailable"));
|
||||
}
|
||||
|
||||
/** @internal editor/core only. */
|
||||
export function _provideWorkspaceHistory(run: (id: number, redo: boolean) => Promise<void>): () => void {
|
||||
workspaceHistory = run;
|
||||
return () => {
|
||||
if (workspaceHistory === run) workspaceHistory = null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface WorkspaceEditHistoryState {
|
||||
id: number;
|
||||
undone: boolean;
|
||||
}
|
||||
const workspaceHistoryListeners = new Set<(state: WorkspaceEditHistoryState) => void>();
|
||||
|
||||
/** Successful workspace Undo/Redo, including commands invoked from an editor. */
|
||||
export function onWorkspaceEditHistory(listener: (state: WorkspaceEditHistoryState) => void): () => void {
|
||||
workspaceHistoryListeners.add(listener);
|
||||
return () => {
|
||||
workspaceHistoryListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal editor/core only. */
|
||||
export function _emitWorkspaceEditHistory(state: WorkspaceEditHistoryState) {
|
||||
for (const listener of workspaceHistoryListeners) listener(state);
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import { customRegions } from "./cm/regions";
|
||||
export type LanguageInfo = LanguageInfo_Serialize;
|
||||
|
||||
export interface DocPatchedEvent {
|
||||
workspaceEdit?: boolean;
|
||||
doc: DocId;
|
||||
baseVersion: number;
|
||||
version: number;
|
||||
@@ -336,7 +335,7 @@ function lineIndex(text: string) {
|
||||
|
||||
export interface MemoryBackend extends DocBackend {
|
||||
/** Test/dev hook: apply a backend-originated change and emit `docPatched`. */
|
||||
patch(doc: DocId, changes: TextChange[], workspaceEdit?: boolean): void;
|
||||
patch(doc: DocId, changes: TextChange[]): void;
|
||||
/** Seed file contents before opening. */
|
||||
files: Map<string, string>;
|
||||
docs: Map<DocId, MemDoc>;
|
||||
@@ -583,13 +582,13 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
dirtyHandlers.add(h);
|
||||
return () => dirtyHandlers.delete(h);
|
||||
},
|
||||
patch(doc, changes, workspaceEdit = false) {
|
||||
patch(doc, changes) {
|
||||
const d = get(doc);
|
||||
const before = d.text !== d.saved;
|
||||
const baseVersion = d.version;
|
||||
d.text = applyChanges(d.text, changes);
|
||||
d.version++;
|
||||
const e = { doc, baseVersion, version: d.version, changes, workspaceEdit };
|
||||
const e = { doc, baseVersion, version: d.version, changes };
|
||||
patched.forEach((h) => h(e));
|
||||
setDirty(d, before);
|
||||
},
|
||||
|
||||
@@ -29,19 +29,9 @@ export async function attachDocument(manager: DocumentManager, path: string): Pr
|
||||
const target = new AttachedView();
|
||||
model.attach(target);
|
||||
let released = false;
|
||||
const historyTarget = {
|
||||
path,
|
||||
state: () => target.view!.state,
|
||||
dispatch: (tr: Transaction) => target.view?.dispatch(tr),
|
||||
};
|
||||
|
||||
const plugin = ViewPlugin.define((view) => {
|
||||
target.view = view;
|
||||
let detachHistory = () => {};
|
||||
let destroyed = false;
|
||||
queueMicrotask(() => {
|
||||
if (!destroyed) detachHistory = model.manager.workspaceHistory.attach(historyTarget);
|
||||
});
|
||||
const handle: TextEditorHandle = { view, ctx: model.ctx() };
|
||||
_addEditor(handle);
|
||||
// The model may have moved on between `text()` and the view's creation.
|
||||
@@ -56,8 +46,6 @@ export async function attachDocument(manager: DocumentManager, path: string): Pr
|
||||
});
|
||||
return {
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
detachHistory();
|
||||
_removeEditor(handle);
|
||||
if (target.view === view) target.view = null;
|
||||
},
|
||||
@@ -69,7 +57,6 @@ export async function attachDocument(manager: DocumentManager, path: string): Pr
|
||||
text: () => model.sync.localText.toString(),
|
||||
readOnly: model.getMeta().readOnly || model.virtual,
|
||||
extension: [
|
||||
model.manager.workspaceHistory.extension(historyTarget),
|
||||
plugin,
|
||||
documentSynced.of(() => model.sync.whenIdle()),
|
||||
EditorView.updateListener.of((u) => {
|
||||
|
||||
@@ -62,7 +62,6 @@ import {
|
||||
import { setMethodLines, softWrapActive } from "../cm/prefs";
|
||||
import type { EditorSlot } from "./slot";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { WorkspaceHistory } from "./workspaceHistory";
|
||||
|
||||
export type Banner = "binary" | "tooLarge" | "readOnly" | "library" | null;
|
||||
|
||||
@@ -262,7 +261,7 @@ export class DocModel {
|
||||
snapshot: () => manager.backend.snapshot(this.doc),
|
||||
},
|
||||
{
|
||||
applyRemote: (cs, grouped) => this.applyRemote(cs, grouped),
|
||||
applyRemote: (cs) => this.applyRemote(cs),
|
||||
onDiscarded: () =>
|
||||
manager.notify({
|
||||
level: "warning",
|
||||
@@ -345,14 +344,14 @@ export class DocModel {
|
||||
this.scheduleRefresh();
|
||||
}
|
||||
|
||||
private applyRemote(cs: ChangeSet, grouped = false) {
|
||||
private applyRemote(cs: ChangeSet) {
|
||||
this.modified.map(cs);
|
||||
this.changeCounter++;
|
||||
const primary = this.primarySlot();
|
||||
for (const s of this.slots)
|
||||
s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(!grouped && s === primary)]);
|
||||
s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(s === primary)]);
|
||||
// Without a tab, the first attached view keeps backend edits (Replace in Files…) undoable.
|
||||
let first = !grouped && !primary;
|
||||
let first = !primary;
|
||||
for (const a of this.attachments) {
|
||||
a.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(first)]);
|
||||
first = false;
|
||||
@@ -626,12 +625,6 @@ export interface ManagerHost {
|
||||
}
|
||||
|
||||
export class DocumentManager {
|
||||
readonly workspaceHistory = new WorkspaceHistory(
|
||||
async () => {
|
||||
await Promise.all([...this.byPath.values()].map((m) => m.sync.whenIdle()));
|
||||
},
|
||||
(n) => this.notify(n),
|
||||
);
|
||||
readonly byPath = new Map<string, DocModel>();
|
||||
readonly byId = new Map<DocId, DocModel>();
|
||||
private opening = new Map<string, Promise<DocModel>>();
|
||||
@@ -654,7 +647,6 @@ export class DocumentManager {
|
||||
|
||||
start() {
|
||||
this.disposers.push(
|
||||
this.workspaceHistory.start(),
|
||||
this.backend.onPatched((e) => this.byId.get(e.doc)?.sync.remote(e)),
|
||||
this.backend.onLanguage?.((e) => this.byId.get(e.doc)?.setLanguage(e.language, e.uiMode)) ?? (() => {}),
|
||||
this.backend.onDirty((e) => {
|
||||
|
||||
@@ -30,7 +30,6 @@ import { showContextMenu } from "@/ui";
|
||||
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
import type { DocModel } from "./document";
|
||||
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
|
||||
import { isNavigation } from "./navHistory";
|
||||
|
||||
export interface SlotHost {
|
||||
@@ -53,8 +52,6 @@ export interface Reveal {
|
||||
|
||||
export class EditorSlot {
|
||||
state: EditorState;
|
||||
private historyTarget: WorkspaceHistoryTarget;
|
||||
private detachHistory: () => void;
|
||||
view: EditorView | null = null;
|
||||
handle: TextEditorHandle | null = null;
|
||||
private scroll: StateEffect<unknown> | null = null;
|
||||
@@ -74,14 +71,6 @@ export class EditorSlot {
|
||||
private host: SlotHost,
|
||||
init?: { from?: EditorSlot; reveal?: Reveal },
|
||||
) {
|
||||
this.historyTarget = {
|
||||
path: model.path,
|
||||
state: () => this.currentState(),
|
||||
dispatch: (tr) => {
|
||||
if (this.view) this.view.dispatch(tr);
|
||||
else this.state = tr.state;
|
||||
},
|
||||
};
|
||||
const source = init?.from;
|
||||
this.state = EditorState.create({
|
||||
doc: model.sync.localText,
|
||||
@@ -102,7 +91,6 @@ export class EditorSlot {
|
||||
else if (source) this.scroll = source.scroll;
|
||||
if (init?.reveal) this.pendingReveal = init.reveal;
|
||||
model.addSlot(this);
|
||||
this.detachHistory = model.manager.workspaceHistory.attach(this.historyTarget);
|
||||
}
|
||||
|
||||
get ctx(): EditorDocContext {
|
||||
@@ -115,7 +103,6 @@ export class EditorSlot {
|
||||
|
||||
private slotExtensions() {
|
||||
return [
|
||||
this.model.manager.workspaceHistory.extension(this.historyTarget),
|
||||
documentSynced.of(() => this.model.sync.whenIdle()),
|
||||
EditorView.updateListener.of((u) => {
|
||||
for (const l of this.listeners) l(u);
|
||||
@@ -183,7 +170,6 @@ export class EditorSlot {
|
||||
|
||||
dispose() {
|
||||
if (this.disposed) return;
|
||||
this.detachHistory();
|
||||
this.unmount();
|
||||
this.disposed = true;
|
||||
this.model.removeSlot(this);
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { workspaceEditHistory } from "@/editor/api";
|
||||
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { createMemoryBackend, type MemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
import { DocumentManager } from "./document";
|
||||
import { EditorSlot, type SlotHost } from "./slot";
|
||||
import { attachDocument } from "./attachment";
|
||||
|
||||
const commands = vi.hoisted(() => ({ undoWorkspaceEdit: vi.fn(), redoWorkspaceEdit: vi.fn() }));
|
||||
vi.mock("@/bindings", () => ({ commands }));
|
||||
const host: SlotHost = { onFocus() {}, onBlur() {}, onSelection() {}, onUserEdit() {}, onContextMenu() {} };
|
||||
let manager: DocumentManager;
|
||||
let backend: MemoryBackend;
|
||||
let notify = vi.fn<(n: { level: "info" | "warning" | "error"; title: string; body?: string }) => void>();
|
||||
let slots: EditorSlot[];
|
||||
let attached: EditorView | null;
|
||||
|
||||
beforeEach(() => {
|
||||
_resetLanguages();
|
||||
backend = createMemoryBackend({ "/p/A.java": "old", "/p/B.java": "old", "/p/closed.java": "old" });
|
||||
notify = vi.fn();
|
||||
manager = new DocumentManager(backend, { settings: () => ({ files: { autoSave: false } }), notify });
|
||||
manager.start();
|
||||
slots = [];
|
||||
attached = null;
|
||||
commands.undoWorkspaceEdit.mockReset().mockImplementation(async () => {
|
||||
await replace("old");
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
commands.redoWorkspaceEdit.mockReset().mockImplementation(async () => {
|
||||
await replace("new");
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
attached?.destroy();
|
||||
slots.forEach((s) => s.dispose());
|
||||
manager.stop();
|
||||
});
|
||||
|
||||
async function open(path: string, from?: EditorSlot) {
|
||||
const slot = new EditorSlot(await manager.acquire(path), String(slots.length), host, from ? { from } : undefined);
|
||||
slots.push(slot);
|
||||
return slot;
|
||||
}
|
||||
async function replace(text: string) {
|
||||
for (const d of backend.docs.values()) {
|
||||
backend.patch(d.id, [{ from: 0, to: 3, insert: text }], true);
|
||||
await backend.save(d.id);
|
||||
}
|
||||
backend.files.set("/p/closed.java", text);
|
||||
}
|
||||
async function rename() {
|
||||
await replace("new");
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 9, paths: ["/p/A.java", "/p/B.java", "/p/closed.java"] });
|
||||
}
|
||||
function historyStep(slot: EditorSlot, forward = false) {
|
||||
return (forward ? redo : undo)({
|
||||
state: slot.currentState(),
|
||||
dispatch: (tr) => {
|
||||
slot.state = tr.state;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
it("editor Undo and Redo restore the entire Java rename, with one step in every split and background tab", async () => {
|
||||
const a = await open("/p/A.java");
|
||||
const split = await open("/p/A.java");
|
||||
const b = await open("/p/B.java");
|
||||
await rename();
|
||||
for (const s of slots) expect(undoDepth(s.currentState())).toBe(1);
|
||||
expect(historyStep(split)).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.files.get("/p/closed.java")).toBe("old"));
|
||||
for (const s of slots) {
|
||||
expect(s.currentState().doc.toString()).toBe("old");
|
||||
expect(undoDepth(s.currentState())).toBe(0);
|
||||
expect(redoDepth(s.currentState())).toBe(1);
|
||||
}
|
||||
expect(commands.undoWorkspaceEdit).toHaveBeenCalledExactlyOnceWith(9);
|
||||
historyStep(b, true);
|
||||
await vi.waitFor(() => expect(backend.files.get("/p/closed.java")).toBe("new"));
|
||||
expect(a.currentState().doc.toString()).toBe("new");
|
||||
expect(undoDepth(a.currentState())).toBe(1);
|
||||
expect(commands.redoWorkspaceEdit).toHaveBeenCalledExactlyOnceWith(9);
|
||||
});
|
||||
|
||||
it("notification Undo consumes the same marker and never makes Cmd+Z reapply a single file", async () => {
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
await workspaceEditHistory(9);
|
||||
expect(a.currentState().doc.toString()).toBe("old");
|
||||
expect(historyStep(a)).toBe(false);
|
||||
expect(redoDepth(a.currentState())).toBe(1);
|
||||
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("preserves earlier local history and refuses the notification until later typing is undone", async () => {
|
||||
const a = await open("/p/A.java");
|
||||
a.dispatchLocal({ changes: { from: 3, insert: "!" }, userEvent: "input.type" });
|
||||
await a.model.sync.whenIdle();
|
||||
await rename();
|
||||
a.dispatchLocal({ changes: { from: 4, insert: "?" }, userEvent: "input.type" });
|
||||
await expect(workspaceEditHistory(9)).rejects.toThrow("Undo newer editor changes");
|
||||
expect(commands.undoWorkspaceEdit).not.toHaveBeenCalled();
|
||||
undo({ state: a.currentState(), dispatch: (tr) => a.dispatchLocal(tr) });
|
||||
await a.model.sync.whenIdle();
|
||||
await workspaceEditHistory(9);
|
||||
expect(a.currentState().doc.toString()).toBe("old!");
|
||||
expect(undoDepth(a.currentState())).toBe(1);
|
||||
});
|
||||
|
||||
it("restores the editor marker when backend guards refuse Undo", async () => {
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
commands.undoWorkspaceEdit.mockResolvedValue({
|
||||
status: "error",
|
||||
error: { kind: "outOfSync", message: "external write" },
|
||||
});
|
||||
historyStep(a);
|
||||
await vi.waitFor(() => expect(notify).toHaveBeenCalled());
|
||||
expect(a.currentState().doc.toString()).toBe("new");
|
||||
expect(undoDepth(a.currentState())).toBe(1);
|
||||
expect(redoDepth(a.currentState())).toBe(0);
|
||||
});
|
||||
|
||||
it("supports direct CodeMirror Undo from an attached diff view", async () => {
|
||||
const att = await attachDocument(manager, "/p/A.java");
|
||||
attached = new EditorView({ doc: att.text(), extensions: [att.extension, history()] });
|
||||
await Promise.resolve();
|
||||
await rename();
|
||||
undo(attached);
|
||||
await vi.waitFor(() => expect(attached!.state.doc.toString()).toBe("old"));
|
||||
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
|
||||
expect(undoDepth(attached.state)).toBe(0);
|
||||
attached.destroy();
|
||||
attached = null;
|
||||
att.release();
|
||||
});
|
||||
|
||||
it.each(["closed file", "new split"])("can redo after a %s opens following Undo", async (kind) => {
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
await workspaceEditHistory(9);
|
||||
const next = await open(kind === "closed file" ? "/p/B.java" : "/p/A.java", kind === "new split" ? a : undefined);
|
||||
expect(next.currentState().doc.toString()).toBe("old");
|
||||
historyStep(a, true);
|
||||
await vi.waitFor(() => expect(commands.redoWorkspaceEdit).toHaveBeenCalledExactlyOnceWith(9));
|
||||
await vi.waitFor(() => expect(next.currentState().doc.toString()).toBe("new"));
|
||||
expect(undoDepth(next.currentState())).toBe(1);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the refactoring notification in sync with editor Undo and Redo", async () => {
|
||||
const notices: Parameters<NotificationService["notify"]>[0][] = [];
|
||||
provideNotificationService({
|
||||
notify: (n) => {
|
||||
notices.push(n);
|
||||
},
|
||||
});
|
||||
const stop = installWorkspaceEditUndo();
|
||||
try {
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
expect(notices.at(-1)?.actions?.[0]?.label).toBe("Undo");
|
||||
historyStep(a);
|
||||
await vi.waitFor(() => expect(notices.at(-1)?.actions?.[0]?.label).toBe("Redo"));
|
||||
historyStep(a, true);
|
||||
await vi.waitFor(() => expect(notices.at(-1)?.actions?.[0]?.label).toBe("Undo"));
|
||||
await notices.at(-1)!.actions![0]!.run();
|
||||
expect(notices.at(-1)?.actions?.[0]?.label).toBe("Redo");
|
||||
await notices.at(-1)!.actions![0]!.run();
|
||||
expect(a.currentState().doc.toString()).toBe("new");
|
||||
expect(notices.at(-1)?.actions?.[0]?.label).toBe("Undo");
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("rebuilds multiple redo markers in order when a closed file opens", async () => {
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
await replace("alt");
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"] });
|
||||
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
|
||||
await replace(id === 10 ? "new" : "old");
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
commands.redoWorkspaceEdit.mockImplementation(async (id: number) => {
|
||||
await replace(id === 10 ? "alt" : "new");
|
||||
return { status: "ok", data: null };
|
||||
});
|
||||
await workspaceEditHistory(10);
|
||||
await workspaceEditHistory(9);
|
||||
const b = await open("/p/B.java");
|
||||
expect(redoDepth(b.currentState())).toBe(2);
|
||||
historyStep(b, true);
|
||||
await vi.waitFor(() => expect(a.currentState().doc.toString()).toBe("new"));
|
||||
historyStep(a, true);
|
||||
await vi.waitFor(() => expect(b.currentState().doc.toString()).toBe("alt"));
|
||||
expect(commands.redoWorkspaceEdit.mock.calls.map(([id]) => id)).toEqual([9, 10]);
|
||||
});
|
||||
|
||||
it("refuses redo when a newly opened affected editor has newer typing", async () => {
|
||||
await open("/p/A.java");
|
||||
await rename();
|
||||
await workspaceEditHistory(9);
|
||||
const b = await open("/p/B.java");
|
||||
b.dispatchLocal({ changes: { from: 3, insert: " own" }, userEvent: "input.type" });
|
||||
await expect(workspaceEditHistory(9, true)).rejects.toThrow("Undo newer editor changes");
|
||||
expect(commands.redoWorkspaceEdit).not.toHaveBeenCalled();
|
||||
expect(b.currentState().doc.toString()).toBe("old own");
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
/** Workspace edits contribute history markers; their text patches never enter local history. */
|
||||
import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/commands";
|
||||
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
|
||||
import { EditorView, keymap } from "@codemirror/view";
|
||||
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
interface Marker {
|
||||
id: number;
|
||||
redo: boolean;
|
||||
}
|
||||
const marker = StateEffect.define<Marker>();
|
||||
|
||||
export interface WorkspaceHistoryTarget {
|
||||
path: string;
|
||||
state(): EditorState;
|
||||
dispatch(tr: Transaction): void;
|
||||
}
|
||||
|
||||
export class WorkspaceHistory {
|
||||
private targets = new Set<WorkspaceHistoryTarget>();
|
||||
private records = new Map<number, { paths: string[]; undone: boolean }>();
|
||||
private project = useProject.getState().project;
|
||||
private busy = false;
|
||||
private moving = false;
|
||||
|
||||
constructor(
|
||||
private synced: () => Promise<void>,
|
||||
private notify: (n: { level: "error"; title: string; body: string }) => void,
|
||||
) {}
|
||||
|
||||
start(): () => void {
|
||||
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
|
||||
if (this.project !== useProject.getState().project) {
|
||||
this.records.clear();
|
||||
this.project = useProject.getState().project;
|
||||
}
|
||||
// A new edit invalidates redo for any overlapping workspace transaction.
|
||||
for (const [key, record] of this.records)
|
||||
if (
|
||||
record.undone &&
|
||||
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
|
||||
)
|
||||
this.records.delete(key);
|
||||
this.records.set(id, { paths, undone: false });
|
||||
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
|
||||
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
|
||||
});
|
||||
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
|
||||
return () => {
|
||||
stop();
|
||||
unprovide();
|
||||
this.records.clear();
|
||||
};
|
||||
}
|
||||
|
||||
private affects(paths: string[], path: string) {
|
||||
return paths.some((root) => path === root || path.startsWith(`${root}/`));
|
||||
}
|
||||
|
||||
attach(target: WorkspaceHistoryTarget): () => void {
|
||||
this.targets.add(target);
|
||||
const records = [...this.records].filter(([, record]) => this.affects(record.paths, target.path));
|
||||
for (const [id] of records) this.mark(target, id);
|
||||
// Build the same done/undone marker stacks as existing editors, without
|
||||
// replaying any backend operation or changing the newly opened text.
|
||||
for (const [id, record] of records.reverse()) {
|
||||
if (!record.undone) continue;
|
||||
const tr = this.step(target, id, false);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
return () => this.targets.delete(target);
|
||||
}
|
||||
|
||||
extension(target: WorkspaceHistoryTarget): Extension {
|
||||
return [
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
{ key: "Mod-z", run: () => this.busy },
|
||||
{ key: "Mod-Shift-z", run: () => this.busy },
|
||||
{ key: "Mod-y", run: () => this.busy },
|
||||
]),
|
||||
),
|
||||
Prec.highest(
|
||||
EditorView.domEventHandlers({
|
||||
beforeinput: (event) => {
|
||||
if (this.busy && (event.inputType === "historyUndo" || event.inputType === "historyRedo")) {
|
||||
event.preventDefault();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
),
|
||||
invertedEffects.of((tr) =>
|
||||
tr.effects.filter((e) => e.is(marker)).map((e) => marker.of({ id: e.value.id, redo: !e.value.redo })),
|
||||
),
|
||||
// History commands disable transaction filters. An extender observes the
|
||||
// effect-only history step, including native beforeinput and direct CM undo.
|
||||
EditorState.transactionExtender.of((tr) => {
|
||||
if (!this.moving && (tr.isUserEvent("undo") || tr.isUserEvent("redo"))) {
|
||||
const entry = tr.effects.find((e) => e.is(marker));
|
||||
if (entry)
|
||||
void this.run(entry.value.id, entry.value.redo, target).catch((error: unknown) => {
|
||||
this.notify({
|
||||
level: "error",
|
||||
title: "Cannot undo refactoring",
|
||||
body: String(error instanceof Error ? error.message : error),
|
||||
});
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
EditorState.changeFilter.of((tr) => !this.busy || isExternalChange(tr)),
|
||||
];
|
||||
}
|
||||
|
||||
private mark(target: WorkspaceHistoryTarget, id: number) {
|
||||
target.dispatch(
|
||||
target.state().update({ effects: marker.of({ id, redo: true }), annotations: isolateHistory.of("full") }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Inspect the next history step without dispatching it or starting another request. */
|
||||
private step(target: WorkspaceHistoryTarget, id: number, forward: boolean): Transaction | null {
|
||||
let result: Transaction | null = null;
|
||||
this.moving = true;
|
||||
try {
|
||||
(forward ? redo : undo)({
|
||||
state: target.state(),
|
||||
dispatch: (tr) => {
|
||||
if (tr.effects.some((e) => e.is(marker) && e.value.id === id && e.value.redo === forward)) result = tr;
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
this.moving = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async run(id: number, forward = false, source?: WorkspaceHistoryTarget): Promise<void> {
|
||||
if (this.busy) throw new Error("A refactoring history operation is in progress");
|
||||
this.busy = true;
|
||||
try {
|
||||
// Yield before reading a source: its marker transaction is still being built.
|
||||
await this.synced();
|
||||
if (this.project !== useProject.getState().project)
|
||||
throw new Error("The project for this refactoring is no longer open");
|
||||
const record = this.records.get(id);
|
||||
if (!record || record.undone !== forward) throw new Error("The refactoring can no longer be undone");
|
||||
const targets = [...this.targets].filter((t) => t !== source && this.affects(record.paths, t.path));
|
||||
for (const target of targets)
|
||||
if (!this.step(target, id, forward))
|
||||
throw new Error("Undo newer editor changes before undoing this refactoring");
|
||||
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
|
||||
await this.synced();
|
||||
for (const target of targets) {
|
||||
if (!this.targets.has(target)) continue;
|
||||
const tr = this.step(target, id, forward);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
record.undone = !forward;
|
||||
_emitWorkspaceEditHistory({ id, undone: record.undone });
|
||||
} catch (error) {
|
||||
// A refused backend restore must leave the initiating editor's history intact.
|
||||
if (source && this.targets.has(source)) {
|
||||
const tr = this.step(source, id, !forward);
|
||||
if (tr) source.dispatch(tr);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export interface SyncTransport {
|
||||
|
||||
export interface SyncHost {
|
||||
/** Apply a change set (in local-text coordinates) to every view, annotated as remote. */
|
||||
applyRemote(changes: ChangeSet, workspaceEdit?: boolean): void;
|
||||
applyRemote(changes: ChangeSet): void;
|
||||
/** Called after a hard resync discarded local changes the backend never saw. */
|
||||
onDiscarded?(reason: unknown): void;
|
||||
/** Non-recoverable transport errors (logged by default). */
|
||||
@@ -73,7 +73,6 @@ export function toTextChanges(cs: ChangeSet): TextChange[] {
|
||||
}
|
||||
|
||||
interface RemotePatch {
|
||||
workspaceEdit?: boolean;
|
||||
baseVersion: number;
|
||||
version: number;
|
||||
changes: TextChange[];
|
||||
@@ -299,7 +298,7 @@ export class DocSync {
|
||||
}
|
||||
if (p.empty) return;
|
||||
this.localText = p.apply(this.localText);
|
||||
this.host.applyRemote(p, patch.workspaceEdit);
|
||||
this.host.applyRemote(p);
|
||||
}
|
||||
|
||||
/** Last resort: adopt the backend text, dropping unacknowledged local changes. */
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type WorkspaceEdit,
|
||||
} from "@/platform/ipc";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api";
|
||||
import { whenSynced, type EditorDocContext } from "@/editor/api";
|
||||
import { structure } from "@/editor/structure";
|
||||
import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp";
|
||||
import { comparePos, offsetToPos, rangeToOffsets } from "./positions";
|
||||
@@ -44,7 +44,6 @@ import { tx } from "@/platform/i18n";
|
||||
|
||||
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
|
||||
try {
|
||||
await whenAllSynced();
|
||||
await lspRequest(() => commands.applyWorkspaceEdit(edit));
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
|
||||
@@ -417,29 +417,6 @@ describe("rename wiring", () => {
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toContain("only local variables");
|
||||
});
|
||||
|
||||
it.each(["typescript", "java"])("previews a %s multi-file rename and retains version guards", async (language) => {
|
||||
cmd.lspPrepareRename.mockReturnValueOnce(ok(r(0, 0, 3)));
|
||||
const edit = {
|
||||
files: ["/p/Main.java", "/p/Use.java"].map((path) => ({
|
||||
kind: "edit",
|
||||
path,
|
||||
version: 7,
|
||||
edits: [{ range: r(0, 0, 3), new_text: "new" }],
|
||||
})),
|
||||
preconditions: [{ path: "/p/Main.java", hash: "original" }],
|
||||
};
|
||||
cmd.lspRename.mockReturnValueOnce(ok({ edit, incomplete: null }));
|
||||
const view = editor("old", language, 0);
|
||||
await renameNamePart(view, { from: 0, to: 3 }, "new");
|
||||
const preview = useLspPopup.getState().popup;
|
||||
expect(preview?.kind).toBe("preview");
|
||||
expect(cmd.applyWorkspaceEdit).not.toHaveBeenCalled();
|
||||
if (preview?.kind !== "preview") throw new Error("missing rename preview");
|
||||
expect(preview.summary.files).toBe(2);
|
||||
preview.onConfirm();
|
||||
await vi.waitFor(() => expect(cmd.applyWorkspaceEdit).toHaveBeenCalledExactlyOnceWith(edit));
|
||||
});
|
||||
|
||||
describe("Typo: Rename to (issue #42)", () => {
|
||||
it("renames the whole name through the server, references included", async () => {
|
||||
cmd.lspPrepareRename.mockReturnValueOnce(ok(r(0, 0, 12)));
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type DuplicateOptions,
|
||||
type StructuralFile,
|
||||
type StructuralLanguage,
|
||||
type WorkspaceEdit,
|
||||
} from "@/platform/ipc";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { activeProfileId, listProfiles, validateInspections, type ProfileId } from "@/platform/inspections";
|
||||
@@ -30,7 +29,6 @@ import {
|
||||
} from "./structural";
|
||||
import styles from "./Analysis.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
function InspectCodeDialog({ onClose }: { onClose: () => void }) {
|
||||
const [scope, setScope] = useState<ScopeChoice>(() => defaultScope());
|
||||
@@ -256,7 +254,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
} else if (!result.files.length) {
|
||||
await showStructuralResults(form.pattern, result.files, result.summary);
|
||||
} else {
|
||||
await showReplacePreview(result.files);
|
||||
showReplacePreview(result.files);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -324,15 +322,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
);
|
||||
}
|
||||
|
||||
function ReplacePreviewDialog({
|
||||
files,
|
||||
preconditions,
|
||||
onClose,
|
||||
}: {
|
||||
files: StructuralFile[];
|
||||
preconditions: WorkspaceEdit["preconditions"];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
function ReplacePreviewDialog({ files, onClose }: { files: StructuralFile[]; onClose: () => void }) {
|
||||
const [excluded, setExcluded] = useState<Set<string>>(() => new Set());
|
||||
const edit = useMemo(() => buildReplaceEdit(files, excluded), [files, excluded]);
|
||||
const count = edit.files.reduce((n, f) => n + (f.kind === "edit" ? f.edits.length : 0), 0);
|
||||
@@ -361,7 +351,7 @@ function ReplacePreviewDialog({
|
||||
disabled: count === 0,
|
||||
onClick: () => {
|
||||
onClose();
|
||||
void applyStructuralReplace({ ...edit, preconditions });
|
||||
void applyStructuralReplace(edit);
|
||||
},
|
||||
},
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
@@ -399,18 +389,5 @@ export const showDuplicatesDialog = () => openDialog((close) => <DuplicatesDialo
|
||||
export const showCodeCleanupDialog = () => openDialog((close) => <CodeCleanupDialog onClose={close} />);
|
||||
export const showStructuralDialog = (replace: boolean) =>
|
||||
openDialog((close) => <StructuralDialog replace={replace} onClose={close} />);
|
||||
export const showReplacePreview = async (files: StructuralFile[]) => {
|
||||
try {
|
||||
const edit = buildReplaceEdit(files, new Set());
|
||||
const prepared = isTauri() ? await call(commands.prepareWorkspaceEdit(edit)) : edit;
|
||||
openDialog((close) => (
|
||||
<ReplacePreviewDialog files={files} preconditions={prepared.preconditions} onClose={close} />
|
||||
));
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot preview replacements",
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
};
|
||||
export const showReplacePreview = (files: StructuralFile[]) =>
|
||||
openDialog((close) => <ReplacePreviewDialog files={files} onClose={close} />);
|
||||
@@ -1,77 +0,0 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { StructuralFile, WorkspaceEdit } from "@/platform/ipc";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import { AnalysisDialogHost } from "./dialogs";
|
||||
import { showReplacePreview } from "./AnalysisDialogs";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ prepare: vi.fn(), apply: vi.fn(), synced: vi.fn(), notify: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const actual = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: { ...actual.commands, prepareWorkspaceEdit: mocks.prepare, applyWorkspaceEdit: mocks.apply },
|
||||
};
|
||||
});
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
...(await original<typeof import("@/editor/api")>()),
|
||||
whenAllSynced: mocks.synced,
|
||||
}));
|
||||
const files: StructuralFile[] = ["a.ts", "b.ts"].map((name) => ({
|
||||
path: `/p/${name}`,
|
||||
relPath: name,
|
||||
matches: [
|
||||
{
|
||||
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 3 } },
|
||||
text: "old",
|
||||
lineText: "old",
|
||||
replacement: "new",
|
||||
},
|
||||
],
|
||||
}));
|
||||
const preconditions = files.map((f) => ({ path: f.path, hash: `preview:${f.path}` }));
|
||||
beforeEach(() => {
|
||||
mocks.prepare
|
||||
.mockReset()
|
||||
.mockImplementation(async (edit: WorkspaceEdit) => ({ status: "ok", data: { ...edit, preconditions } }));
|
||||
mocks.apply.mockReset().mockResolvedValue({ status: "ok", data: null });
|
||||
mocks.synced.mockReset().mockResolvedValue(undefined);
|
||||
mocks.notify.mockReset();
|
||||
provideNotificationService({ notify: mocks.notify });
|
||||
});
|
||||
afterEach(() => {
|
||||
if (screen.queryByRole("button", { name: "Cancel" })) fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("captures guards before preview and preserves them when the user excludes a file", async () => {
|
||||
render(<AnalysisDialogHost />);
|
||||
await act(() => showReplacePreview(files));
|
||||
expect(mocks.prepare).toHaveBeenCalledOnce();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Replace in b.ts:1" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Replace" }));
|
||||
await waitFor(() => expect(mocks.apply).toHaveBeenCalledOnce());
|
||||
expect(mocks.apply.mock.calls[0]![0]).toEqual({
|
||||
files: [{ kind: "edit", path: "/p/a.ts", edits: [{ range: files[0]!.matches[0]!.range, new_text: "new" }] }],
|
||||
preconditions,
|
||||
});
|
||||
expect(mocks.synced).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reports a stale preview without refreshing guards or retrying the edits", async () => {
|
||||
mocks.apply.mockResolvedValue({
|
||||
status: "error",
|
||||
error: { kind: "outOfSync", message: "a.ts changed; request again" },
|
||||
});
|
||||
render(<AnalysisDialogHost />);
|
||||
await act(() => showReplacePreview(files));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Replace" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "error", title: "Replace Structurally", body: "a.ts changed; request again" }),
|
||||
),
|
||||
);
|
||||
expect(mocks.prepare).toHaveBeenCalledOnce();
|
||||
expect(mocks.apply).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
* one workspace edit.
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { activeEditor, whenAllSynced } from "@/editor/api";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import {
|
||||
call,
|
||||
@@ -160,7 +160,6 @@ export async function showStructuralResults(
|
||||
|
||||
export async function applyStructuralReplace(edit: WorkspaceEdit): Promise<void> {
|
||||
try {
|
||||
await whenAllSynced();
|
||||
await call(commands.applyWorkspaceEdit(edit));
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import type { BuildModel, MavenModel, ProjectInfo } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { changedOutsideIde, loadModel, noteExternalBuildChange, noteIdeSave, useBuild } from "./store";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ model: vi.fn(), sync: vi.fn() }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
call: (value: unknown) => value,
|
||||
commands: {
|
||||
...real.commands,
|
||||
buildModel: mocks.model,
|
||||
runConfigs: () => Promise.resolve([]),
|
||||
buildSync: mocks.sync,
|
||||
cancelRequest: () => Promise.resolve(),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: unknown = null;
|
||||
},
|
||||
}));
|
||||
|
||||
const maven = (stale: boolean) =>
|
||||
({ syncedAt: 1, stale, syncError: null, profiles: [], projects: [] }) as unknown as MavenModel;
|
||||
const model = (stale: boolean): BuildModel => ({ maven: maven(stale), gradle: null });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.sync.mockImplementation(() => new Promise(() => {}));
|
||||
useBuild.setState({ syncing: {} });
|
||||
useProject.setState({ project: { root: "/p", trusted: true } as ProjectInfo });
|
||||
});
|
||||
|
||||
it("reloads a build made stale by a change outside the editor, not by an edit in it", async () => {
|
||||
mocks.model.mockResolvedValue(model(true));
|
||||
await loadModel();
|
||||
expect(mocks.sync).not.toHaveBeenCalled();
|
||||
|
||||
noteExternalBuildChange();
|
||||
await loadModel();
|
||||
expect(mocks.sync).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.sync.mock.calls[0]![0]).toBe("maven");
|
||||
expect(useBuild.getState().model?.maven?.stale).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves an up-to-date build alone after an external change", async () => {
|
||||
mocks.model.mockResolvedValue(model(false));
|
||||
noteExternalBuildChange();
|
||||
await loadModel();
|
||||
expect(mocks.sync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tells the IDE's own saves of a build file apart from changes made outside it", () => {
|
||||
noteIdeSave("/p/pom.xml", 1000);
|
||||
expect(changedOutsideIde(["/p/pom.xml"], 2000)).toBe(false);
|
||||
// A tool rewrites the same file later, while it is still open in a tab.
|
||||
expect(changedOutsideIde(["/p/pom.xml"], 10_000)).toBe(true);
|
||||
// Never saved by the IDE: a VCS update.
|
||||
expect(changedOutsideIde(["/p/core/pom.xml"], 2000)).toBe(true);
|
||||
noteIdeSave("/p/pom.xml", 20_000);
|
||||
expect(changedOutsideIde(["/p/pom.xml", "/p/core/pom.xml"], 20_500)).toBe(true);
|
||||
});
|
||||
@@ -3,7 +3,6 @@
|
||||
* project has that build system, like IDEA. The model is re-read when build
|
||||
* files change; running goals / tasks goes through the run feature's actions.
|
||||
*/
|
||||
import { onEditorEvent } from "@/editor/api";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { onIdeEvent, type BuildModel, type BuildTool } from "@/platform/ipc";
|
||||
@@ -26,9 +25,6 @@ import {
|
||||
unlinkProjects,
|
||||
cancelSync,
|
||||
loadModel,
|
||||
changedOutsideIde,
|
||||
noteExternalBuildChange,
|
||||
noteIdeSave,
|
||||
openAnalyzer,
|
||||
resetBuild,
|
||||
setExpanded,
|
||||
@@ -162,16 +158,8 @@ export function activate(): () => void {
|
||||
resetBuild();
|
||||
if (s.project) void loadModel();
|
||||
}),
|
||||
onEditorEvent((e) => {
|
||||
if (e.type === "docSaved" && BUILD_FILE.test(e.path)) noteIdeSave(e.path);
|
||||
}),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
const changed = [...e.created, ...e.modified, ...e.removed].filter((p) => BUILD_FILE.test(p));
|
||||
if (!changed.length) return;
|
||||
// Changes the IDE's own saves didn't make came from outside (a VCS update, another tool),
|
||||
// also for a build file open in a tab.
|
||||
if (changedOutsideIde(changed)) noteExternalBuildChange();
|
||||
scheduleLoad();
|
||||
if ([...e.created, ...e.modified, ...e.removed].some((p) => BUILD_FILE.test(p))) scheduleLoad();
|
||||
}),
|
||||
onIdeEvent("projectRootsChanged", scheduleLoad),
|
||||
// Project JDK / Maven home and options are applied to the model's launchers.
|
||||
|
||||
@@ -142,41 +142,6 @@ export function pushHistory(tool: BuildTool, line: string) {
|
||||
// Model
|
||||
|
||||
let generation = 0;
|
||||
let externalChange = false;
|
||||
|
||||
/**
|
||||
* A build file changed outside the editor (VCS update, another tool): the next model load
|
||||
* reloads a build it finds stale, IDEA's default "Reload after external changes". Edits in
|
||||
* the editor only show "Load … Changes".
|
||||
*/
|
||||
export function noteExternalBuildChange() {
|
||||
externalChange = true;
|
||||
}
|
||||
|
||||
/** How long after the IDE saves a build file its file-system events still count as that save. */
|
||||
const IDE_SAVE_WINDOW_MS = 5000;
|
||||
/** Build files the IDE saved, with when: their file-system events are edits made in the IDE. */
|
||||
const savedByIde = new Map<string, number>();
|
||||
|
||||
/** The IDE saved `path` (an editor save, not a tool rewriting it). */
|
||||
export function noteIdeSave(path: string, now = Date.now()) {
|
||||
savedByIde.set(path, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether any of the changed build files was written by something other than the IDE's own
|
||||
* save: a VCS update or a tool, also when the file is open in an editor tab.
|
||||
*/
|
||||
export function changedOutsideIde(paths: readonly string[], now = Date.now()): boolean {
|
||||
let external = false;
|
||||
for (const path of paths) {
|
||||
const at = savedByIde.get(path);
|
||||
if (at !== undefined && now - at <= IDE_SAVE_WINDOW_MS) continue;
|
||||
savedByIde.delete(path);
|
||||
external = true;
|
||||
}
|
||||
return external;
|
||||
}
|
||||
|
||||
/** Re-reads the build model (and the run configurations) of the open project. */
|
||||
export async function loadModel(): Promise<void> {
|
||||
@@ -202,11 +167,6 @@ export async function loadModel(): Promise<void> {
|
||||
]);
|
||||
if (gen !== generation) return;
|
||||
useBuild.setState({ model, configs, loading: false, error: null });
|
||||
if (externalChange) {
|
||||
externalChange = false;
|
||||
const maven = model.maven;
|
||||
if (maven?.stale && maven.syncedAt !== null && !useBuild.getState().syncing.maven) void syncTool("maven");
|
||||
}
|
||||
} catch (e) {
|
||||
if (gen === generation) useBuild.setState({ loading: false, error: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import { resetHierarchy, showHierarchy } from "./hierarchy";
|
||||
import { installServerEvents } from "./servers";
|
||||
import { goConstraintExcluded } from "./goConstraints";
|
||||
import { ServerStatus } from "./ServerStatus";
|
||||
import { installWorkspaceEditUndo } from "./workspaceUndo";
|
||||
|
||||
const EDITOR_WHEN = "textEditorActive && (editorFocus || popupOpen || !toolWindowFocus)";
|
||||
|
||||
@@ -61,7 +60,6 @@ export function activate(): () => void {
|
||||
installProblemsEvents(),
|
||||
installProblemDecorations(),
|
||||
installServerEvents(),
|
||||
installWorkspaceEditUndo(),
|
||||
registerToolWindow({
|
||||
id: "problems",
|
||||
title: "Problems",
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { installWorkspaceEditUndo } from "./workspaceUndo";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ undo: vi.fn(), synced: vi.fn(), history: vi.fn(() => () => {}) }));
|
||||
vi.mock("@/editor/api", () => ({
|
||||
whenAllSynced: mocks.synced,
|
||||
workspaceEditHistory: mocks.undo,
|
||||
onWorkspaceEditHistory: mocks.history,
|
||||
}));
|
||||
|
||||
let stop: () => void;
|
||||
let notices: Parameters<NotificationService["notify"]>[0][];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.undo.mockReset().mockResolvedValue(undefined);
|
||||
mocks.synced.mockReset().mockResolvedValue(undefined);
|
||||
notices = [];
|
||||
provideNotificationService({
|
||||
notify: (notice) => {
|
||||
notices.push(notice);
|
||||
},
|
||||
});
|
||||
stop = installWorkspaceEditUndo();
|
||||
});
|
||||
|
||||
afterEach(() => stop());
|
||||
|
||||
it("waits for pending typing before undoing the entire backend transaction", async () => {
|
||||
let release: () => void = () => {};
|
||||
mocks.synced.mockReturnValue(
|
||||
new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [] });
|
||||
const action = notices[0]!.actions![0]!;
|
||||
expect(action.label).toBe("Undo");
|
||||
const pending = action.run();
|
||||
expect(mocks.undo).not.toHaveBeenCalled();
|
||||
release();
|
||||
await pending;
|
||||
expect(mocks.undo).toHaveBeenCalledExactlyOnceWith(17);
|
||||
});
|
||||
|
||||
it("reports a refused undo instead of discarding newer work", async () => {
|
||||
mocks.undo.mockRejectedValue(new Error("a.txt changed"));
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [] });
|
||||
await notices[0]!.actions![0]!.run();
|
||||
expect(notices[1]).toMatchObject({ level: "error", title: "Cannot undo refactoring", body: "a.txt changed" });
|
||||
});
|
||||
|
||||
it("does not apply an old notification's id to a different project", async () => {
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [] });
|
||||
const previous = useProject.getState().project;
|
||||
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
|
||||
try {
|
||||
await notices[0]!.actions![0]!.run();
|
||||
expect(mocks.undo).not.toHaveBeenCalled();
|
||||
expect(notices[1]).toMatchObject({ level: "error", body: "The project for this refactoring is no longer open" });
|
||||
} finally {
|
||||
useProject.setState({ project: previous });
|
||||
}
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { onWorkspaceEditHistory, whenAllSynced, workspaceEditHistory } from "@/editor/api";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
/** The notification follows the same history state as editor Undo/Redo. */
|
||||
export function installWorkspaceEditUndo(): () => void {
|
||||
let current: { id: number; project: ReturnType<typeof useProject.getState>["project"]; undone: boolean } | null =
|
||||
null;
|
||||
const show = () => {
|
||||
if (!current) return;
|
||||
const entry = current;
|
||||
const { id, project, undone } = entry;
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: undone ? "Refactoring undone" : "Refactoring applied",
|
||||
key: "refactor.workspaceEdit",
|
||||
actions: [
|
||||
{
|
||||
label: undone ? "Redo" : "Undo",
|
||||
run: async () => {
|
||||
try {
|
||||
await whenAllSynced();
|
||||
if (project !== useProject.getState().project)
|
||||
throw new Error("The project for this refactoring is no longer open");
|
||||
if (current !== entry || current.undone !== undone) return;
|
||||
if (undone) await workspaceEditHistory(id, true);
|
||||
else await workspaceEditHistory(id);
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot undo refactoring",
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id }) => {
|
||||
current = { id, project: useProject.getState().project, undone: false };
|
||||
show();
|
||||
});
|
||||
const stopHistory = onWorkspaceEditHistory(({ id, undone }) => {
|
||||
if (!current || current.id !== id || current.project !== useProject.getState().project) return;
|
||||
current = { ...current, undone };
|
||||
show();
|
||||
});
|
||||
return () => {
|
||||
stopApplied();
|
||||
stopHistory();
|
||||
current = null;
|
||||
};
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
menuGroupItems,
|
||||
springEditorExtension,
|
||||
} from "./spring/editor";
|
||||
import { registerSpringEndpointProvider } from "./spring/routeIndex";
|
||||
|
||||
const SPRING_WHEN = "editorLangId == java || editorLangId == kotlin";
|
||||
|
||||
@@ -113,7 +112,6 @@ async function newRequest(directory?: string) {
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerSpringEndpointProvider(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) resetHttpClient();
|
||||
}),
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { commands, emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { searchEndpoints } from "@/workbench/contributions";
|
||||
import { clearRouteIndex, isRouteSource, registerSpringEndpointProvider, routeIndex } from "./routeIndex";
|
||||
|
||||
const scanSources = vi.spyOn(commands, "springRouteSources");
|
||||
|
||||
const source = (method = "searchMenus", url = "/menu/search") => ({
|
||||
path: "/p/DeepLinkController.java",
|
||||
text: `@RestController
|
||||
@RequestMapping("/deeplink")
|
||||
class DeepLinkController {
|
||||
@PostMapping("${url}")
|
||||
String ${method}() { return "ok"; }
|
||||
}`,
|
||||
});
|
||||
|
||||
let dispose: (() => void) | undefined;
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
dispose = undefined;
|
||||
clearRouteIndex();
|
||||
scanSources.mockReset();
|
||||
});
|
||||
|
||||
describe("the request-path index follows the workspace", () => {
|
||||
it("is invalidated by a change to a mapping source", () => {
|
||||
for (const [path, expected] of [
|
||||
["/p/A.java", true],
|
||||
["/p/B.kt", true],
|
||||
["/p/C.kts", true],
|
||||
["/p/pom.xml", false],
|
||||
["/p/notes.md", false],
|
||||
] as const) {
|
||||
expect(isRouteSource(path), path).toBe(expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("the Spring endpoint provider", () => {
|
||||
it("scans once per root with method coordinates and rescans for another root", async () => {
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [source()] });
|
||||
expect(await routeIndex(null)).toEqual([]);
|
||||
const first = await routeIndex("/p");
|
||||
expect(first).toEqual([
|
||||
{
|
||||
method: "POST",
|
||||
url: "/deeplink/menu/search",
|
||||
controller: "DeepLinkController",
|
||||
methodName: "searchMenus",
|
||||
path: "/p/DeepLinkController.java",
|
||||
rel: "DeepLinkController.java",
|
||||
line: 4,
|
||||
col: 11,
|
||||
},
|
||||
]);
|
||||
expect(await routeIndex("/p")).toBe(first);
|
||||
expect(scanSources).toHaveBeenCalledTimes(1);
|
||||
expect(await routeIndex("/other")).toEqual([]);
|
||||
expect(scanSources).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(["created", "modified", "removed"] as const)("invalidates on %s mapping sources", async (kind) => {
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [source()] });
|
||||
dispose = registerSpringEndpointProvider();
|
||||
expect((await searchEndpoints("/p"))[0]?.methodName).toBe("searchMenus");
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [ipcPath("/p/pom.xml")], removed: [] });
|
||||
await searchEndpoints("/p");
|
||||
expect(scanSources).toHaveBeenCalledTimes(1);
|
||||
scanSources.mockResolvedValue({ status: "ok", data: [source("listMenus", "/menu/list")] });
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [], [kind]: [ipcPath("/p/A.java")] });
|
||||
expect((await searchEndpoints("/p"))[0]?.url).toBe("/deeplink/menu/list");
|
||||
expect(scanSources).toHaveBeenCalledTimes(2);
|
||||
dispose();
|
||||
expect(await searchEndpoints("/p")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
/** Spring request-path index, cached per project until a mapping source changes. */
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { springControllers } from "./endpoints";
|
||||
|
||||
export function registerSpringEndpointProvider(): () => void {
|
||||
clearRouteIndex();
|
||||
const unregister = registerEndpointProvider({ id: "http.spring", endpoints: routeIndex });
|
||||
const unsubscribe = onIdeEvent("fsChanged", (e) => {
|
||||
if ([...e.created, ...e.modified, ...e.removed].some((p) => isRouteSource(String(p)))) clearRouteIndex();
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unregister();
|
||||
clearRouteIndex();
|
||||
};
|
||||
}
|
||||
|
||||
let cached: { root: string; promise: Promise<EndpointEntry[]> } | null = null;
|
||||
|
||||
/** Whether `path` is a source a mapping can live in (a Java or Kotlin file). */
|
||||
export function isRouteSource(path: string): boolean {
|
||||
return /\.(java|kt|kts)$/i.test(path);
|
||||
}
|
||||
|
||||
/** Forgets the index, so the next search rescans the project. */
|
||||
export function clearRouteIndex() {
|
||||
cached = null;
|
||||
}
|
||||
|
||||
/** The project's routes, scanned once per project and kept in memory. */
|
||||
export function routeIndex(root: string | null): Promise<EndpointEntry[]> {
|
||||
if (!root) return Promise.resolve([]);
|
||||
if (cached?.root === root) return cached.promise;
|
||||
const promise = scan(root);
|
||||
cached = { root, promise };
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function scan(root: string): Promise<EndpointEntry[]> {
|
||||
const sources = await call(commands.springRouteSources());
|
||||
const routes: EndpointEntry[] = [];
|
||||
for (const source of sources) {
|
||||
if (!source.path.startsWith(root)) continue;
|
||||
for (const controller of springControllers(source.text)) {
|
||||
for (const endpoint of controller.endpoints) {
|
||||
const at = lineCol(source.text, endpoint.offset);
|
||||
// A mapping without a path answers nothing to look up by URL; the method
|
||||
// itself is still reachable through the symbol index.
|
||||
for (const url of endpoint.paths) {
|
||||
routes.push({
|
||||
method: endpoint.httpMethod,
|
||||
url,
|
||||
controller: controller.name,
|
||||
methodName: endpoint.methodName,
|
||||
path: source.path,
|
||||
rel: source.path.slice(root.length + 1),
|
||||
line: at.line,
|
||||
col: at.col,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
function lineCol(text: string, offset: number): { line: number; col: number } {
|
||||
let line = 0;
|
||||
let col = 0;
|
||||
for (let i = 0; i < offset && i < text.length; i++) {
|
||||
if (text.charCodeAt(i) === 10 /* \n */) {
|
||||
line++;
|
||||
col = 0;
|
||||
} else {
|
||||
col++;
|
||||
}
|
||||
}
|
||||
return { line, col };
|
||||
}
|
||||
@@ -138,7 +138,7 @@ function PreviewDialog({ request }: { request: PreviewRequest }) {
|
||||
label: "Do Refactor",
|
||||
role: "default",
|
||||
autoFocus: true,
|
||||
onClick: () => request.resolve({ ...request.edit, files: kept }),
|
||||
onClick: () => request.resolve({ files: kept }),
|
||||
},
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
|
||||
@@ -22,16 +22,6 @@ const edit = (path: string, ...ranges: [number, number, number, string][]): Work
|
||||
});
|
||||
|
||||
describe("file refactoring edits", () => {
|
||||
it("retains version guards and both sources' preview fingerprints", () => {
|
||||
const lsp: WorkspaceEdit = {
|
||||
files: [{ kind: "edit", path: "/p/main.ts", edits: [{ range: r(0, 0, 3), new_text: "new" }], version: 7 }],
|
||||
preconditions: [{ path: "/p/main.ts", hash: "source" }],
|
||||
};
|
||||
const text: WorkspaceEdit = { files: [], preconditions: [{ path: "/p/README.md", hash: "text" }] };
|
||||
const merged = mergeEdits(lsp, text);
|
||||
expect(merged.files[0]).toMatchObject({ version: 7 });
|
||||
expect(merged.preconditions).toEqual([...lsp.preconditions!, ...text.preconditions!]);
|
||||
});
|
||||
it("merges text occurrences that no server edit covers and drops file operations", () => {
|
||||
const lsp: WorkspaceEdit = {
|
||||
files: [edit("/p/main.ts", [0, 20, 26, "./b/util"]), { kind: "rename", from: "/p/a", to: "/p/b" }],
|
||||
@@ -68,10 +58,7 @@ describe("runFileRefactoring", () => {
|
||||
backend = {
|
||||
calls: [],
|
||||
edits: vi.fn(async () => ({
|
||||
edit: {
|
||||
files: [edit("/p/main.ts", [0, 20, 26, "./b/util"])],
|
||||
preconditions: [{ path: "/p/main.ts", hash: "preview" }],
|
||||
},
|
||||
edit: { files: [edit("/p/main.ts", [0, 20, 26, "./b/util"])] },
|
||||
errors: ["tsserver: busy"],
|
||||
})),
|
||||
move: vi.fn(async (moves: FileMove[], e: WorkspaceEdit) => {
|
||||
@@ -99,11 +86,6 @@ describe("runFileRefactoring", () => {
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Do Refactor" }));
|
||||
expect(await status).toBe("done");
|
||||
expect(backend.calls).toEqual(["move 1 1"]);
|
||||
expect(backend.move).toHaveBeenCalledWith(
|
||||
moves,
|
||||
expect.objectContaining({ preconditions: [{ path: "/p/main.ts", hash: "preview" }] }),
|
||||
"Move",
|
||||
);
|
||||
expect(lastFileRefactoring()?.id).toBe(7);
|
||||
// Server failures are reported; the result offers Undo.
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "warning", body: "tsserver: busy" }));
|
||||
|
||||
@@ -129,15 +129,9 @@ function overlaps(a: { start: { line: number; col: number }; end: { line: number
|
||||
* Only text edits are kept: the move itself is the refactoring's file operation.
|
||||
*/
|
||||
export function mergeEdits(lsp: WorkspaceEdit, text: WorkspaceEdit): WorkspaceEdit {
|
||||
const versions = new Map<string, number | null | undefined>();
|
||||
const guards: WorkspaceEdit["files"] = [];
|
||||
const byPath = new Map<string, Extract<WorkspaceEdit["files"][number], { kind: "edit" }>["edits"]>();
|
||||
for (const f of lsp.files) {
|
||||
if (f.kind !== "edit") continue;
|
||||
const previous = versions.get(f.path);
|
||||
if (previous != null && f.version != null && previous !== f.version)
|
||||
guards.push({ ...f, edits: [], version: previous });
|
||||
versions.set(f.path, f.version ?? previous);
|
||||
byPath.set(f.path, [...(byPath.get(f.path) ?? []), ...f.edits]);
|
||||
}
|
||||
for (const f of text.files) {
|
||||
@@ -146,15 +140,7 @@ export function mergeEdits(lsp: WorkspaceEdit, text: WorkspaceEdit): WorkspaceEd
|
||||
const extra = f.edits.filter((t) => !existing.some((e) => overlaps(e.range, t.range)));
|
||||
if (extra.length) byPath.set(f.path, [...existing, ...extra]);
|
||||
}
|
||||
return {
|
||||
files: [
|
||||
...guards,
|
||||
...[...byPath]
|
||||
.filter(([, e]) => e.length)
|
||||
.map(([path, edits]) => ({ kind: "edit" as const, path, edits, version: versions.get(path) })),
|
||||
],
|
||||
preconditions: [...(lsp.preconditions ?? []), ...(text.preconditions ?? [])],
|
||||
};
|
||||
return { files: [...byPath].filter(([, e]) => e.length).map(([path, edits]) => ({ kind: "edit", path, edits })) };
|
||||
}
|
||||
|
||||
/** Whether `edit` changes files other than the moved ones (IDEA previews those refactorings). */
|
||||
|
||||
@@ -158,9 +158,6 @@ describe("context configuration", () => {
|
||||
expect(fileRole("src/a.test.ts")).toBe("test");
|
||||
expect(fileRole("pkg/x_test.go")).toBe("test");
|
||||
expect(fileRole("tests/test_api.py")).toBe("test");
|
||||
// Django's default test module (pattern `test*.py`); a script outside Django projects.
|
||||
expect(fileRole("polls/tests.py", undefined, false, true)).toBe("test");
|
||||
expect(fileRole("polls/tests.py")).toBe("script");
|
||||
expect(fileRole("src/test/kotlin/OrderControllerTest.kt")).toBe("test");
|
||||
expect(fileRole("tests/integration.rs")).toBe("test");
|
||||
expect(fileRole("src/main.rs")).toBe("main");
|
||||
@@ -188,27 +185,6 @@ describe("context configuration", () => {
|
||||
expect(contextConfig("internal/calc/calc_test.go", configs)!.args).toEqual(["test", "./internal/calc"]);
|
||||
expect(contextConfig("tests/api.rs", configs)!.args).toEqual(["test", "--test", "api"]);
|
||||
expect(contextConfig("tests/test_math.py", configs)!.args).toEqual(["run", "pytest", "tests/test_math.py"]);
|
||||
// `tests.py` is a test module in Django projects only.
|
||||
expect(contextConfig("polls/tests.py", configs)).toMatchObject({
|
||||
kind: "python",
|
||||
isTest: false,
|
||||
command: ".venv/bin/python",
|
||||
args: ["polls/tests.py"],
|
||||
});
|
||||
const django = cfg({
|
||||
id: "django:test",
|
||||
kind: "django-test",
|
||||
command: "uv",
|
||||
args: ["run", "python", "manage.py", "test"],
|
||||
isTest: true,
|
||||
});
|
||||
expect(contextConfig("polls/tests.py", [django])!.args).toEqual([
|
||||
"run",
|
||||
"python",
|
||||
"manage.py",
|
||||
"test",
|
||||
"polls.tests",
|
||||
]);
|
||||
expect(contextConfig("src/test/kotlin/OrderControllerTest.kt", configs)!.args).toEqual([
|
||||
"test",
|
||||
"--tests",
|
||||
|
||||
@@ -4,20 +4,17 @@
|
||||
* direct interpreter invocation for main files. Best effort, IDEA-style.
|
||||
*/
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes";
|
||||
import { goTestParts } from "./goArguments";
|
||||
import { isWindows } from "./jvmTypes";
|
||||
|
||||
export type FileRole = "test" | "main" | "script" | null;
|
||||
|
||||
/** `django`: a Django project, whose default test module is `tests.py` (elsewhere a script). */
|
||||
export function fileRole(relPath: string, content?: string, windows = isWindows(), django = false): FileRole {
|
||||
export function fileRole(relPath: string, content?: string, windows = isWindows()): FileRole {
|
||||
const name = relPath.split("/").pop() ?? relPath;
|
||||
if (
|
||||
/\.(test|spec)\.[cm]?[jt]sx?$/.test(name) ||
|
||||
/(^|\/)__tests__\//.test(relPath) ||
|
||||
/^test_.*\.py$|_test\.py$/.test(name) ||
|
||||
(django && name === "tests.py") ||
|
||||
/_test\.go$/.test(name) ||
|
||||
/(Test|Tests|Spec|IT)\.(kt|java|scala|groovy)$/.test(name) ||
|
||||
(/(^|\/)tests\/[^/]+\.rs$/.test(relPath) && name !== "mod.rs")
|
||||
@@ -38,7 +35,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, "");
|
||||
/** Kinds whose test configs can run a file of this extension. */
|
||||
function testKinds(relPath: string): string[] {
|
||||
if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun"];
|
||||
if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"];
|
||||
if (/\.py$/.test(relPath)) return ["pytest", "python"];
|
||||
if (/\.go$/.test(relPath)) return ["go"];
|
||||
if (/\.rs$/.test(relPath)) return ["cargo"];
|
||||
if (/\.(kt|java|scala|groovy)$/.test(relPath)) return ["gradle", "maven"];
|
||||
@@ -64,8 +61,7 @@ function closest(configs: RunConfig[], relPath: string): RunConfig | undefined {
|
||||
return allClosest(configs, relPath)[0];
|
||||
}
|
||||
|
||||
/** `relPath` relative to the working directory of `config`. */
|
||||
export function relToCwd(relPath: string, config: RunConfig): string {
|
||||
function relToCwd(relPath: string, config: RunConfig): string {
|
||||
const cwd = (config.kind === "go" ? (config.params?.module ?? config.cwd ?? "") : (config.cwd ?? ""))
|
||||
.replace(/^\.\/?/, "")
|
||||
.replace(/\/+$/, "");
|
||||
@@ -160,10 +156,6 @@ export function testConfigFor(relPath: string, configs: RunConfig[], base?: RunC
|
||||
case "pytest":
|
||||
case "python":
|
||||
return derived(base, relPath, { args: [...base.args, file] });
|
||||
case "django-test": {
|
||||
const tests = djangoTestsOf(base, [djangoLabel(file)]);
|
||||
return tests ? derived(base, relPath, tests) : null;
|
||||
}
|
||||
case "go": {
|
||||
const dir = dirOf(file);
|
||||
const target = dir ? `./${dir}` : ".";
|
||||
@@ -256,7 +248,7 @@ export function contextConfig(
|
||||
content?: string,
|
||||
windows = isWindows(),
|
||||
): RunConfig | null {
|
||||
const role = fileRole(relPath, content, windows, hasDjangoTests(configs));
|
||||
const role = fileRole(relPath, content, windows);
|
||||
if (role === "test") return testConfigFor(relPath, configs);
|
||||
if (role === "main") return mainConfigFor(relPath, configs) ?? scriptConfigFor(relPath, configs, windows);
|
||||
if (role === "script") return scriptConfigFor(relPath, configs, windows);
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* Django tests (PyCharm's "Django tests" configuration): `manage.py test` with a
|
||||
* target (app labels, modules or dotted test paths), a settings module and
|
||||
* further options. The command is the interpreter (`python3`, `.venv/bin/python`,
|
||||
* `uv`), the runner args its leading arguments (`run python` for uv / poetry).
|
||||
*/
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import type { RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { formatArgs, parseArgs } from "./configs";
|
||||
|
||||
/** A Django project: it has a Django tests configuration (detected from `manage.py`, or made in the form). */
|
||||
export const hasDjangoTests = (configs: readonly RunConfig[]) => configs.some((c) => c.kind === "django-test");
|
||||
|
||||
/** Index of `manage.py` when `test` follows it, else -1. */
|
||||
function manageTest(args: readonly string[]): number {
|
||||
return args.findIndex((a, i) => /(^|[/\\])manage\.py$/.test(a) && args[i + 1] === "test");
|
||||
}
|
||||
|
||||
/** Number of leading positional arguments (the test labels). */
|
||||
const labelCount = (args: readonly string[]) => {
|
||||
const n = args.findIndex((a) => a.startsWith("-"));
|
||||
return n < 0 ? args.length : n;
|
||||
};
|
||||
|
||||
/** Dotted test label of a module file: `polls/tests.py` → `polls.tests`, `polls/tests/__init__.py` → `polls.tests`. */
|
||||
export function djangoLabel(relPath: string): string {
|
||||
return relPath
|
||||
.replace(/\.py$/, "")
|
||||
.replace(/(^|\/)__init__$/, "")
|
||||
.replace(/\//g, ".");
|
||||
}
|
||||
|
||||
/**
|
||||
* `args` of a `manage.py test` command line running `labels` in place of its
|
||||
* own target (the labels right after `test`); null for other command lines.
|
||||
*/
|
||||
function withDjangoLabels(args: readonly string[], labels: readonly string[]): string[] | null {
|
||||
const at = manageTest(args);
|
||||
if (at < 0) return null;
|
||||
const rest = args.slice(at + 2);
|
||||
return [...args.slice(0, at + 2), ...labels, ...rest.slice(labelCount(rest))];
|
||||
}
|
||||
|
||||
/**
|
||||
* The command line (and, for a configuration made in the form, the Target field)
|
||||
* of `config` running `labels`; null when it doesn't run `manage.py test`.
|
||||
*/
|
||||
export function djangoTestsOf(config: RunConfig, labels: readonly string[]): Pick<RunConfig, "args" | "params"> | null {
|
||||
const args = withDjangoLabels(config.args, labels);
|
||||
if (!args) return null;
|
||||
return config.params?.target === undefined
|
||||
? { args }
|
||||
: { args, params: { ...config.params, target: formatArgs([...labels]) } };
|
||||
}
|
||||
|
||||
export const djangoTestType: RunConfigTypeContribution = {
|
||||
id: "django-test",
|
||||
label: "Django tests",
|
||||
icon: "file-python",
|
||||
description: "Run Django tests with manage.py test",
|
||||
defaults: { command: "python3" },
|
||||
debugAdapter: "debugpy",
|
||||
fields: [
|
||||
{
|
||||
key: "command",
|
||||
label: "Command",
|
||||
mono: true,
|
||||
placeholder: "python3",
|
||||
required: true,
|
||||
hint: "e.g. python3, .venv/bin/python, uv, poetry",
|
||||
},
|
||||
{
|
||||
key: "runnerArgs",
|
||||
label: "Runner arguments",
|
||||
mono: true,
|
||||
placeholder: "run python",
|
||||
hint: "e.g. `run python` for uv/poetry; empty calls the interpreter itself",
|
||||
},
|
||||
{
|
||||
key: "target",
|
||||
label: "Target",
|
||||
mono: true,
|
||||
placeholder: "polls.tests",
|
||||
hint: "App labels, modules or dotted test paths; empty runs every test",
|
||||
},
|
||||
{
|
||||
key: "settings",
|
||||
label: "Settings module",
|
||||
mono: true,
|
||||
placeholder: "mysite.settings_test",
|
||||
hint: "Passed as --settings; empty keeps DJANGO_SETTINGS_MODULE or the default in manage.py",
|
||||
},
|
||||
{ key: "options", label: "Options", mono: true, placeholder: "e.g. --keepdb --parallel" },
|
||||
],
|
||||
commandLine(p) {
|
||||
const args = [...parseArgs(p.runnerArgs ?? ""), "manage.py", "test", ...parseArgs(p.target ?? "")];
|
||||
if (p.settings?.trim()) args.push("--settings", p.settings.trim());
|
||||
args.push(...parseArgs(p.options ?? ""));
|
||||
return { command: p.command?.trim() || "python3", args };
|
||||
},
|
||||
paramsFrom(c) {
|
||||
if (c.kind !== "django-test") return null;
|
||||
const at = manageTest(c.args);
|
||||
if (at < 0) return null;
|
||||
const rest = c.args.slice(at + 2);
|
||||
const n = labelCount(rest);
|
||||
let options = rest.slice(n);
|
||||
let settings = "";
|
||||
if (options[0] === "--settings" && options[1] !== undefined) {
|
||||
settings = options[1];
|
||||
options = options.slice(2);
|
||||
}
|
||||
return {
|
||||
command: c.command,
|
||||
runnerArgs: formatArgs(c.args.slice(0, at)),
|
||||
target: formatArgs(rest.slice(0, n)),
|
||||
settings,
|
||||
options: formatArgs(options),
|
||||
};
|
||||
},
|
||||
};
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача