Compare commits

..
522 changed files with 3840 additions and 17187 deletions

No files matched your search

Generated
+22 -5
View File
@@ -4180,6 +4180,8 @@ dependencies = [
"rayon",
"serde",
"specta",
"tracing",
"tree-sitter",
]
[[package]]
@@ -4189,6 +4191,7 @@ dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
@@ -4250,7 +4253,6 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
@@ -4275,6 +4277,7 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"tracing",
]
[[package]]
@@ -4313,6 +4316,7 @@ dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
"dirs 6.0.0",
"dunce",
"flate2",
"futures",
@@ -4378,6 +4382,7 @@ dependencies = [
"blake3",
"dunce",
"ed25519-dalek",
"ide-core",
"parking_lot",
"semver",
"serde",
@@ -4432,7 +4437,6 @@ version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
"ide-heap",
"libc",
"memmap2",
"proptest",
@@ -4536,6 +4540,7 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
@@ -4548,7 +4553,6 @@ dependencies = [
"dunce",
"globset",
"ide-core",
"ide-index",
"ide-language",
"ignore",
"nucleo-matcher",
@@ -4579,6 +4583,7 @@ name = "ide-jsonrpc"
version = "0.1.50"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
"serde",
@@ -4721,6 +4726,7 @@ dependencies = [
name = "ide-notebook"
version = "0.1.50"
dependencies = [
"futures",
"ide-core",
"ide-vfs",
"jupyter-protocol",
@@ -4733,6 +4739,7 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4752,6 +4759,7 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
@@ -4838,7 +4846,6 @@ dependencies = [
name = "ide-sdk"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
@@ -4850,7 +4857,6 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
@@ -6700,11 +6706,14 @@ dependencies = [
"dunce",
"gtk",
"ide-agent",
"ide-analysis",
"ide-android",
"ide-build",
"ide-cli",
"ide-clipboard",
"ide-command",
"ide-core",
"ide-coverage",
"ide-dap",
"ide-db",
"ide-docker",
@@ -6714,16 +6723,24 @@ dependencies = [
"ide-github",
"ide-host",
"ide-http",
"ide-index",
"ide-jsonrpc",
"ide-language",
"ide-lsp",
"ide-mcp",
"ide-notebook",
"ide-plugin",
"ide-profiler",
"ide-remote",
"ide-run",
"ide-scaffold",
"ide-sdk",
"ide-search",
"ide-spell",
"ide-ssh",
"ide-syntax",
"ide-terminal",
"ide-text",
"ide-tools",
"ide-vcs",
"ide-vfs",
+2
View File
@@ -69,11 +69,13 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
tokio-util = { version = "0.7", features = ["rt"] }
parking_lot = "0.12"
rayon = "1"
dashmap = "6"
futures = "0.3"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
# errors & diagnostics
thiserror = "2"
anyhow = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+6 -9
View File
@@ -169,12 +169,9 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
let (tx, rx) = mpsc::unbounded_channel();
manager.subscribe_as(
"",
Arc::new(move |event| {
let _ = tx.send(event);
}),
);
manager.subscribe(Arc::new(move |event| {
let _ = tx.send(event);
}));
rx
}
@@ -492,7 +489,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
set.reply.send(Err("Sign in required".into())).unwrap();
let error = switching.await.unwrap_err().to_string();
assert!(error.contains("Sign in required"), "{error}");
assert_eq!(manager.subscribe_as("", Arc::new(|_| {})).remove(0).config, before_config);
assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config);
assert!(harness.pending.try_recv().is_err());
manager.shutdown();
return;
@@ -501,7 +498,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
manager.set_config(&task.id, "model", "old".into()).await.unwrap();
set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap();
switching.await.unwrap();
let task = manager.subscribe_as("", Arc::new(|_| {})).remove(0);
let task = manager.subscribe(Arc::new(|_| {})).remove(0);
assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old"));
assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low"));
assert!(harness.pending.try_recv().is_err());
@@ -532,7 +529,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
let effort = update.config.iter().find(|o| o.id == "effort").unwrap();
assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["quick", "thorough"]);
}
let snapshot = |manager: &AgentManager| manager.subscribe_as("", Arc::new(|_| {})).remove(0);
let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0);
let current = snapshot(&manager);
assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new"));
assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" }));
+7 -6
View File
@@ -647,8 +647,12 @@ impl AgentManager {
Self { shared, tasks: RwLock::new(tasks) }
}
/// Routes events to `sink`, replacing only the sink `subscriber` (a view of the project) had;
/// returns every task.
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
self.subscribe_as("", sink)
}
/// Routes events to `sink` too, replacing only the sink `subscriber` (a view of the project) had.
pub fn subscribe_as(&self, subscriber: &str, sink: AgentSink) -> Vec<AgentTask> {
self.shared.sinks.write().insert(subscriber.to_owned(), sink);
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().snapshot()).collect();
@@ -4230,11 +4234,8 @@ fn file_uri(path: &Path) -> String {
out
}
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
/// block opens with a code fence (```` ```text ````), which names no task.
fn title_of(prompt: &AgentPrompt) -> String {
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty());
let line = match line {
Some(l) => l.to_owned(),
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
+98 -1
View File
@@ -941,10 +941,107 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
out
}
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
pub(crate) fn strip_jsonc(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
i += 2;
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
if bytes[i] == b'\n' {
out.push('\n');
i += 1;
} else {
let ch = input[i..].chars().next().unwrap();
i += ch.len_utf8();
}
}
i = (i + 2).min(bytes.len());
continue;
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
remove_trailing_commas(&out)
}
fn remove_trailing_commas(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b',' {
let mut j = i + 1;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
i += 1;
continue;
}
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
let trimmed = raw.trim().trim_start_matches('\u{feff}');
serde_json::from_str::<Value>(trimmed)
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
.map_err(|e| format!("Invalid JSON: {e}"))
}
+1 -1
View File
@@ -769,7 +769,7 @@ pub struct AgentModelCatalog {
pub error: Option<String>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
+1 -1
View File
@@ -406,7 +406,7 @@ fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkil
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&crate::mcp::strip_jsonc(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
+23 -31
View File
@@ -1153,7 +1153,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
@@ -1443,17 +1443,14 @@ async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
let permission = *handle.permissions.lock().keys().next().unwrap();
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
let weak = Arc::downgrade(&handle);
mgr.subscribe_as(
"",
Arc::new(move |event| {
if let AgentEvent::Task { task } = event
&& task.queue.is_empty()
&& let Some(handle) = weak.upgrade()
{
let _ = tx.send(handle.turns.load(Ordering::Acquire));
}
}),
);
mgr.subscribe(Arc::new(move |event| {
if let AgentEvent::Task { task } = event
&& task.queue.is_empty()
&& let Some(handle) = weak.upgrade()
{
let _ = tx.send(handle.turns.load(Ordering::Acquire));
}
}));
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
@@ -1734,8 +1731,6 @@ fn prompts_become_acp_content_blocks() {
assert_eq!(old["entries"][0]["attachments"], json!([]));
assert!(old["entries"][1].get("attachments").is_none());
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
assert_eq!(title_of(&pasted), "## Fix the tab title");
assert!(clean(text(" ")).is_none());
}
@@ -3043,7 +3038,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
let events = Arc::new(Mutex::new(Vec::new()));
let events_sink = events.clone();
mgr.subscribe_as("", Arc::new(move |ev| events_sink.lock().push(ev)));
mgr.subscribe(Arc::new(move |ev| events_sink.lock().push(ev)));
let toml = format!(
"name = \"GitHub Copilot\"\ncommand = {:?}\nargs = [\"--acp\", \"--stdio\"]\n",
@@ -3462,17 +3457,14 @@ async fn config_choice_shows_before_the_agent_answers() {
let mgr = manager(tempfile::tempdir().unwrap().path(), agent.clone());
let shown: Arc<Mutex<Option<std::time::Instant>>> = Arc::default();
let mark = shown.clone();
mgr.subscribe_as(
"",
Arc::new(move |e| {
if let AgentEvent::Task { task } = e
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
&& mark.lock().is_none()
{
*mark.lock() = Some(std::time::Instant::now());
}
}),
);
mgr.subscribe(Arc::new(move |e| {
if let AgentEvent::Task { task } = e
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
&& mark.lock().is_none()
{
*mark.lock() = Some(std::time::Instant::now());
}
}));
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -4316,7 +4308,7 @@ async fn attention_finished_not_cancelled() {
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let done = mgr
.create(NewAgentTask {
@@ -4370,7 +4362,7 @@ async fn attention_failed() {
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -4395,7 +4387,7 @@ async fn attention_input_not_auto_bypass() {
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
let asked = mgr
.create(NewAgentTask {
@@ -4460,7 +4452,7 @@ async fn attention_not_emitted_on_restore() {
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
let tasks = restored.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
let tasks = restored.subscribe(Arc::new(move |e| sink.lock().push(e)));
assert!(tasks.iter().any(|t| t.id == task.id));
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(attention_reasons(&events.lock()).is_empty(), "snapshot restore must not re-notify: {:?}", *events.lock());
@@ -4613,7 +4605,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
// Persisted task file preserves `skill_overrides` across restart.
let restored_mgr = manager(root, Arc::new(FakeAgent::default()));
let restored = restored_mgr.subscribe_as("", Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
let restored = restored_mgr.subscribe(Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
assert_eq!(restored.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
assert_eq!(restored.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
restored_mgr.shutdown();
+2
View File
@@ -10,6 +10,8 @@ ide-core.workspace = true
ide-language.workspace = true
serde.workspace = true
specta.workspace = true
tree-sitter.workspace = true
rayon.workspace = true
tracing.workspace = true
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
ast-grep-core = "=0.40.1"
+3
View File
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+6
View File
@@ -91,6 +91,12 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
pub fn platform_tools_dir() -> Option<&'static Path> {
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
+134 -216
View File
@@ -1,18 +1,101 @@
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
//! that are handed over in batches (logcat is far too chatty for one message a line).
pub(crate) use ide_core::cli_process::Output;
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
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};
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
pub(crate) struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
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));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
ide_core::output_encoding::decode_tool_output(&buf)
})
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
ADB.run(cmd, timeout, cancel)
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("adb did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(bool, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = ide_core::output_encoding::decode_tool_output(pending);
pending.clear();
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
@@ -26,22 +109,41 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
/// tail for the error message. Returns whether the child exited successfully.
pub(crate) fn stream_batched<T>(
cmd: Command,
mut cmd: Command,
cancel: &CancellationToken,
idle: Duration,
max: usize,
mut parse: impl FnMut(&str) -> Option<T>,
on_batch: &mut dyn FnMut(Vec<T>),
) -> IdeResult<(bool, Vec<String>)> {
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), true);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), false);
open += 1;
}
drop(tx);
let mut stderr_tail: Vec<String> = Vec::new();
let mut batch: Vec<T> = Vec::with_capacity(max);
// When the first line of the waiting batch arrived.
let mut since = Instant::now();
loop {
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
match lines.poll(cancel, wait)? {
Poll::Line(Stream::Stdout, line) => {
match rx.recv_timeout(wait) {
Ok(Event::Line(true, line)) => {
if let Some(item) = parse(&line) {
if batch.is_empty() {
since = Instant::now();
@@ -52,25 +154,36 @@ pub(crate) fn stream_batched<T>(
}
}
}
Poll::Line(Stream::Stderr, line) => {
Ok(Event::Line(false, line)) => {
if !line.trim().is_empty() {
keep_stderr_line(&mut stderr_tail, line);
stderr_tail.push(line);
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
}
}
Poll::Closed => {}
Poll::Timeout => flush(&mut batch, on_batch),
Poll::Finished => break,
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
flush(&mut batch, on_batch);
Ok((lines.finish(cancel)?, stderr_tail))
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
#[test]
fn a_steady_stream_is_handed_over_while_it_runs() {
@@ -90,199 +203,4 @@ mod tests {
assert_eq!(sizes.iter().sum::<usize>(), 20);
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
}
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "adb did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
/// parsing stdout lines unless they are `skip`.
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
let mut batches = Vec::new();
let (ok, tail) = stream_batched(
sh(script),
&CancellationToken::new(),
LONG,
max,
|line| (line != "skip").then(|| line.to_owned()),
&mut |batch| batches.push(batch),
)
.unwrap();
(ok, batches, tail)
}
#[test]
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
assert!(ok);
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
}
#[test]
fn lines_the_parser_rejects_are_dropped() {
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
assert_eq!(batches, [vec!["1", "2"]]);
}
#[test]
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
assert_eq!(batches, [vec!["a", "bc", "d"]]);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(batches("exit 0", 10).0);
assert!(!batches("exit 2", 10).0);
}
#[test]
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
let (_, batches, tail) =
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
assert_eq!(batches, [vec!["out"]]);
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&cancel,
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&CancellationToken::new(),
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
}
+2
View File
@@ -17,4 +17,6 @@ serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true
+14 -62
View File
@@ -483,6 +483,11 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
vec![s]
}
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
fn package_manager(dir: &Path) -> &'static str {
ide_core::project_roots::package_manager(dir)
}
fn has_build_script(dir: &Path) -> bool {
std::fs::read(dir.join("package.json"))
.ok()
@@ -520,12 +525,7 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
return vec![BuildStep::new(
ide_core::project_roots::package_manager(dir),
&["run", "build"],
dir,
Format::Tsc,
)];
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
}
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
@@ -1008,7 +1008,12 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
maven_launch_projects(root, m, module, test)
.iter()
.flat_map(|p| {
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
})
.collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1016,60 +1021,6 @@ pub fn build_for_launches(
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
}
/// Maven output directories for a launch, including directories that have yet to be created.
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
maven_launch_projects(root, model, module, test)
.into_iter()
.flat_map(|p| {
let dir = subdir(root, &p.dir);
maven_output_dirs(&dir, test && dir == module)
})
.collect()
}
/// The class directories of a Maven launch that must hold classes after its build: those of
/// the launch projects with sources in a conventional JVM source root. One that is missing
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
fn has_sources(dir: &Path, depth: u32) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && has_sources(&p, depth - 1)
} else {
// A package-info.java without annotations compiles to nothing.
p.file_name() != Some("package-info.java".as_ref())
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
}
})
}
let compiles = |dir: &Path, set: &str| {
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
};
let Some(m) = &model.maven else { return Vec::new() };
let mut dirs = Vec::new();
for p in maven_launch_projects(root, m, module, test) {
let dir = subdir(root, &p.dir);
if test && dir == module && compiles(&dir, "test") {
dirs.push(subdir(&dir, "target/test-classes"));
}
if compiles(&dir, "main") {
dirs.push(subdir(&dir, "target/classes"));
}
}
dirs
}
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if test {
dirs.push(subdir(module, "target/test-classes"));
}
dirs.push(subdir(module, "target/classes"));
dirs
}
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
let dirs: Vec<PathBuf> = match system {
@@ -1080,7 +1031,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven => maven_output_dirs(module, test),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
+34
View File
@@ -31,6 +31,40 @@ pub const LOCAL_REPO_TRACKING_ARG: &str = "-Daether.enhancedLocalRepository.trac
pub const LIFECYCLE: &[&str] =
&["clean", "validate", "compile", "test", "package", "verify", "install", "site", "deploy"];
/// Every phase of the clean, default and site lifecycles (Execute Maven Goal completion).
pub const ALL_PHASES: &[&str] = &[
"pre-clean",
"clean",
"post-clean",
"validate",
"initialize",
"generate-sources",
"process-sources",
"generate-resources",
"process-resources",
"compile",
"process-classes",
"generate-test-sources",
"process-test-sources",
"generate-test-resources",
"process-test-resources",
"test-compile",
"process-test-classes",
"test",
"prepare-package",
"package",
"pre-integration-test",
"integration-test",
"post-integration-test",
"verify",
"install",
"deploy",
"pre-site",
"site",
"post-site",
"site-deploy",
];
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MavenModel {
+13 -263
View File
@@ -3,13 +3,7 @@
use super::MavenProject;
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::collections::HashSet;
use std::fs::{self, File};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
const SOURCE_REFRESH_WORKERS: usize = 4;
#[derive(Debug, PartialEq, Eq)]
pub struct Artifact {
@@ -17,29 +11,6 @@ pub struct Artifact {
pub name: String,
pub version: String,
pub sources: PathBuf,
binary: PathBuf,
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part != "."
&& part != ".."
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}
fn modified_file(path: &Path) -> Option<SystemTime> {
let metadata = fs::metadata(path).ok()?;
if metadata.is_file() { metadata.modified().ok() } else { None }
}
impl Artifact {
fn stale_binary(&self) -> Option<SystemTime> {
if !self.version.ends_with("-SNAPSHOT") {
return None;
}
let binary = modified_file(&self.binary)?;
(modified_file(&self.sources)? < binary).then_some(binary)
}
}
/// Resolve only jars inside the selected local repository, including custom repositories.
@@ -57,14 +28,16 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
}
let n = parts.len();
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
let valid = |s: &str| {
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
};
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
return None;
}
Some(Artifact {
group: parts[..n - 3].join("."),
name: name.into(),
version: version.into(),
binary: jar.to_owned(),
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
})
}
@@ -75,58 +48,26 @@ pub fn download(
artifact: &Artifact,
repository: &Path,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
}
fn resolve(
root: &Path,
project: &MavenProject,
artifact: &Artifact,
repository: &Path,
profile_args: &[String],
stale: Option<SystemTime>,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if stale.is_none() && artifact.sources.is_file() {
if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
args.extend(project.options.iter().cloned());
args.extend(profile_args.iter().cloned());
args.push(format!("-Dmaven.repo.local={}", repository.display()));
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
let stage = if let Some(binary) = stale {
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
let stage =
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
args.extend([
"-U".into(),
"-Daether.artifactResolver.snapshotNormalization=false".into(),
format!("{DEPENDENCY_PLUGIN}:copy"),
coordinate,
"-Dmdep.useBaseVersion=true".into(),
format!("-DoutputDirectory={}", stage.path().display()),
]);
Some((stage, binary))
} else {
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
None
};
args.extend(project.options.clone());
args.extend([
format!("-Dmaven.repo.local={}", repository.display()),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
"-Dtransitive=false".into(),
]);
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if let Some((stage, binary)) = stage {
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
if output.success && resolved.is_file() {
return replace_stale_sources(artifact, &resolved, binary, cancel);
}
} else if artifact.sources.is_file() {
if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
@@ -142,115 +83,6 @@ fn resolve(
))
}
fn replace_stale_sources(
artifact: &Artifact,
resolved: &Path,
binary: SystemTime,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
// the same bytes so a later reload can retry when newer sources are available.
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
if hash(resolved)? == hash(&artifact.sources)? {
return Ok(None);
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match artifact.stale_binary() {
Some(current) if current == binary => {
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
fs::rename(resolved, &artifact.sources)?;
Ok(Some(artifact.sources.clone()))
}
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
_ => Ok(None),
}
}
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
/// updating during import, so freshness is checked when the refresh runs.
pub fn cached_snapshots<'a>(
repository: &Path,
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
) -> Vec<(usize, Artifact)> {
let mut seen = HashSet::new();
let mut candidates = Vec::new();
for (owner, project) in projects {
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
while let Some(dep) = dependencies.pop() {
if !dep.resolved() {
continue;
}
dependencies.extend(&dep.children);
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
continue;
};
if dep.scope == "system"
|| dep.classifier.is_some()
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|| !valid_part(&dep.artifact_id)
|| !dep.group_id.split('.').all(valid_part)
{
continue;
}
let name = &dep.artifact_id;
let jar = repository
.join(dep.group_id.replace('.', "/"))
.join(name)
.join(version)
.join(format!("{name}-{version}.jar"));
if let Some(artifact) = artifact(&jar, repository)
&& artifact.sources.is_file()
&& seen.insert(jar)
{
candidates.push((owner, artifact));
}
}
}
candidates
}
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
/// and share the build reload's cancellation token.
pub fn refresh_snapshots(
root: &Path,
projects: &[MavenProject],
repository: &Path,
candidates: &[(usize, Artifact)],
profiles: &[String],
cancel: &CancellationToken,
) -> Vec<PathBuf> {
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
let profile_args = &profile_args;
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
std::thread::scope(|scope| {
let workers: Vec<_> = stale
.chunks(batch_size)
.map(|batch| {
scope.spawn(move || {
let mut refreshed = Vec::new();
for (owner, artifact) in batch.iter().copied() {
if cancel.is_cancelled() {
break;
}
let Some(binary) = artifact.stale_binary() else { continue };
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
{
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
Ok(None) => {}
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
}
}
refreshed
})
})
.collect();
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -289,86 +121,4 @@ mod tests {
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
}
}
#[test]
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
use crate::maven::{MavenDependency, Omission};
let repo = tempfile::tempdir().unwrap();
let dependency = |name: &str, version: &str, cached: bool| {
if cached {
let dir = repo.path().join("example").join(name).join(version);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
}
MavenDependency {
group_id: "example".into(),
artifact_id: name.into(),
version: Some(version.into()),
kind: "jar".into(),
..Default::default()
}
};
let transitive = dependency("transitive", "1-SNAPSHOT", true);
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
let omitted =
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
let projects = [
MavenProject {
dependencies: vec![
direct,
omitted,
dependency("missing", "1-SNAPSHOT", false),
dependency("release", "1", true),
],
..Default::default()
},
MavenProject { dependencies: vec![transitive], ..Default::default() },
];
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
.into_iter()
.map(|(owner, artifact)| (owner, artifact.name))
.collect();
found.sort();
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
}
#[cfg(unix)]
#[test]
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
use std::fs::FileTimes;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let dir = tempfile::tempdir().unwrap();
let repository = dir.path().join("repository");
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
fs::create_dir_all(jar.parent().unwrap()).unwrap();
fs::write(&jar, b"new binary").unwrap();
let artifact = artifact(&jar, &repository).unwrap();
fs::write(&artifact.sources, b"old sources").unwrap();
File::open(&artifact.sources)
.unwrap()
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
.unwrap();
let launcher = dir.path().join("mvn");
fs::write(
&launcher,
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
)
.unwrap();
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
let cancel = CancellationToken::new();
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"new sources");
assert_eq!(
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
Some(path)
);
}
}
-1
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
-319
View File
@@ -1,319 +0,0 @@
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
//! its output, and cancellable streams that hand over its output line by line.
//!
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
//! before `SIGKILL`.
use crate::process::{own_group, prepare, terminate_tree};
use crate::{CancellationToken, IdeError, IdeResult};
use std::borrow::Cow;
use std::io::{Read, Write};
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 gets to exit on `SIGTERM`
/// before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
const STDERR_TAIL: usize = 20;
/// How a tool's output bytes become text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decoding {
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
/// Windows the system code page for what is not.
ToolOutput,
/// UTF-8, invalid bytes replaced by U+FFFD.
Utf8Lossy,
}
impl Decoding {
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
match self {
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
}
}
}
/// What a child's stdin is fed with, and how.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Input<'a> {
/// Written before the output is read, then closed: only for input small enough
/// (a password) to fit the pipe, as a full pipe blocks the caller.
Inline(&'a str),
/// Written by a thread of its own, then closed: a large body must not block on a full
/// pipe while the child is not reading yet.
Threaded(&'a str),
}
/// How a streamed child's `\r` is read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CarriageReturn {
/// Ends a line like `\n`: progress output rewrites its line in place.
EndsLine,
/// Is dropped; only `\n` ends a line.
Dropped,
}
/// What a bounded run collected.
pub struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
/// Which pipe a streamed line came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
/// One tool's CLI: its name for error messages and how its output is decoded.
#[derive(Clone, Copy, Debug)]
pub struct CliTool {
name: &'static str,
decoding: Decoding,
}
impl CliTool {
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
Self { name, decoding }
}
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
}
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
fn configure(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
prepare(own_group(cmd));
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
self.run_with_input(cmd, None, timeout, cancel)
}
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
pub fn run_with_input(
self,
mut cmd: Command,
input: Option<Input>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
Self::configure(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = self.spawn(&mut cmd)?;
match (input, child.stdin.take()) {
(Some(Input::Inline(text)), Some(mut stdin)) => {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = stdin.write_all(text.as_bytes());
}
(Some(Input::Threaded(text)), Some(mut stdin)) => {
let text = text.to_owned();
std::thread::spawn(move || {
let _ = stdin.write_all(text.as_bytes());
});
}
_ => {}
}
let decoding = self.decoding;
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub fn stream(
self,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
let mut stderr_tail: Vec<String> = Vec::new();
loop {
match lines.poll(cancel, Duration::from_millis(50))? {
Poll::Line(stream, line) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
keep_stderr_line(&mut stderr_tail, line.clone());
}
on_line(stream, line);
}
Poll::Closed | Poll::Timeout => {}
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Self::configure(&mut cmd);
let mut child = self.spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
open += 1;
}
drop(tx);
Ok(Lines { child, rx, open })
}
}
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
tail.push(line);
if tail.len() > STDERR_TAIL {
tail.remove(0);
}
}
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
decoding.decode(&buf).into_owned()
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(
mut pipe: impl Read + Send + 'static,
tx: mpsc::Sender<Event>,
stream: Stream,
decoding: Decoding,
cr: CarriageReturn,
) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = decoding.decode(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
pub struct Lines {
child: Child,
rx: mpsc::Receiver<Event>,
/// Pipes whose reader has not reported its end yet.
open: usize,
}
/// What [`Lines::poll`] saw.
pub enum Poll {
Line(Stream, String),
/// A pipe reached its end.
Closed,
/// Nothing arrived within the wait.
Timeout,
/// Every pipe is at its end.
Finished,
}
impl Lines {
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
if self.open == 0 {
return Ok(Poll::Finished);
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match self.rx.recv_timeout(wait) {
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
Ok(Event::Closed) => {
self.open -= 1;
Ok(Poll::Closed)
}
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
Err(mpsc::RecvTimeoutError::Disconnected) => {
self.open = 0;
Ok(Poll::Finished)
}
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
}
}
-2
View File
@@ -324,8 +324,6 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
@@ -71,11 +71,6 @@ pub struct SpellingSettings {
pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<String>,
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
/// project when one is open, application otherwise.
#[specta(optional)]
pub default_dictionary: Option<String>,
}
/// Changes to one inspection; absent fields keep the inspection's defaults.
-122
View File
@@ -1,122 +0,0 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+1 -54
View File
@@ -40,10 +40,6 @@ pub fn strip(src: &str) -> String {
if prev == '*' && n == '/' {
break;
}
// Keep the comment's line breaks so parse errors report the original line.
if n == '\n' {
out.push('\n');
}
prev = n;
}
}
@@ -69,7 +65,7 @@ pub fn strip(src: &str) -> String {
in_str = true;
cleaned.push(c);
} else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace());
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c);
}
@@ -99,53 +95,4 @@ mod tests {
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
assert_eq!(v["a"], 1);
}
#[test]
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
assert_eq!(err.line(), 3);
// A comment is whitespace, not a join: `1 2` stays invalid.
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
}
#[test]
fn line_comments_keep_their_line_break_and_may_end_the_input() {
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
}
#[test]
fn unterminated_block_comment_drops_the_rest() {
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
assert_eq!(strip("/*"), "");
assert_eq!(strip("/*/ x"), "");
assert_eq!(strip("/**/{}"), "{}");
assert_eq!(strip("/***/{}"), "{}");
}
#[test]
fn comment_markers_inside_strings_survive_including_after_escapes() {
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
}
#[test]
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
assert_eq!(strip("[1,/*c*/]"), "[1]");
assert_eq!(strip("[1,//c\n]"), "[1\n]");
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
assert_eq!(strip("[1,2]"), "[1,2]");
}
#[test]
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
}
}
-4
View File
@@ -4,7 +4,6 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod cli_process;
pub mod editor_settings;
pub mod error;
pub mod event;
@@ -13,7 +12,6 @@ pub mod ids;
pub mod ignored;
pub mod input;
pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
@@ -32,7 +30,6 @@ pub mod task;
pub mod text;
pub mod tool_path;
pub mod updates;
pub mod utf8;
pub mod version_managers;
pub mod workflow_settings;
pub mod wsl;
@@ -40,7 +37,6 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
-39
View File
@@ -1334,45 +1334,6 @@ mod tests {
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
}
#[test]
fn unix_uses_the_name_as_is() {
assert_eq!(executable_names("kotlinc", false, Some(".BAT")), ["kotlinc"]);
}
#[test]
fn windows_appends_pathext_extensions() {
assert_eq!(
executable_names("kotlinc", true, None),
["kotlinc.com", "kotlinc.exe", "kotlinc.bat", "kotlinc.cmd"]
);
assert_eq!(executable_names("npx", true, Some(".EXE;.CMD;;")), ["npx.exe", "npx.cmd"]);
assert_eq!(executable_names("npx", true, Some(" ")), executable_names("npx", true, None));
// Already has an executable extension (any case): only that file.
assert_eq!(executable_names("rustc.EXE", true, None), ["rustc.EXE"]);
assert_eq!(executable_names("gradlew.bat", true, None), ["gradlew.bat"]);
// A dot that is not an executable extension (`clang++`, `python3.12`).
assert_eq!(executable_names("python3.12", true, Some(".EXE")), ["python3.12.exe"]);
}
#[test]
fn finds_batch_files_and_skips_extensionless_scripts_on_windows() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a");
let b = dir.path().join("b");
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
// `node_modules/.bin` style: a POSIX script next to its `.cmd` shim.
std::fs::write(a.join("tsx"), "#!/bin/sh\n").unwrap();
std::fs::write(b.join("tsx.cmd"), "@echo off\n").unwrap();
std::fs::write(b.join("kotlinc.bat"), "@echo off\n").unwrap();
let search = std::env::join_paths([&a, &b]).unwrap();
assert_eq!(find_executable_in("tsx", &search, true, None), Some(b.join("tsx.cmd")));
assert_eq!(find_executable_in("kotlinc", &search, true, None), Some(b.join("kotlinc.bat")));
assert_eq!(find_executable_in("tsx", &search, false, None), Some(a.join("tsx")));
assert_eq!(find_executable_in("kotlinc", &search, false, None), None);
assert_eq!(find_executable_in("nope", &search, true, None), None);
}
#[test]
fn find_executable_finds_bare_names_on_the_given_path() {
let dir = tempfile::tempdir().unwrap();
+1 -13
View File
@@ -1208,7 +1208,6 @@ pub struct LanguagesSettings {
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
@@ -1236,10 +1235,6 @@ impl Default for LanguagesSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
black: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
java: JavaSettings::default(),
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
@@ -1309,7 +1304,6 @@ impl LanguagesSettings {
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
}
}
@@ -1322,7 +1316,6 @@ pub enum ExternalFormatter {
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1333,7 +1326,6 @@ impl ExternalFormatter {
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
Self::Black => "black",
}
}
}
@@ -1342,7 +1334,7 @@ impl ExternalFormatter {
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
/// An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
@@ -1404,9 +1396,6 @@ pub struct PythonSettings {
pub hide_other_project_interpreters: bool,
/// Show each interpreter's path under its name on the interpreters page.
pub show_interpreter_paths: bool,
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
}
impl Default for PythonSettings {
@@ -1418,7 +1407,6 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
+1
View File
@@ -12,6 +12,7 @@ quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
[dev-dependencies]
tempfile.workspace = true
+1
View File
@@ -27,6 +27,7 @@ tiberius.workspace = true
oracledb.workspace = true
bb8.workspace = true
tokio-util = { workspace = true, features = ["compat"] }
dirs.workspace = true
ide-ssh.workspace = true
ide-http.workspace = true
reqwest = { workspace = true, features = ["query"] }
+17
View File
@@ -46,6 +46,23 @@ pub fn databases(templates: bool) -> &'static str {
/// Databases of managed services that their users cannot use (hidden unless connected to).
pub const INTERNAL_DATABASES: &[&str] = &["rdsadmin", "azure_maintenance", "azure_sys", "cloudsqladmin"];
/// Oracle system accounts hidden unless `show_system` (see the Schemas tab).
pub const ORACLE_SYSTEM_SCHEMAS: &[&str] = &[
"CTXSYS",
"DBSFWUSER",
"DVSYS",
"GSMADMIN_INTERNAL",
"LBACSYS",
"MDDATA",
"MDSYS",
"OLAPSYS",
"OUTLN",
"SYS",
"SYSTEM",
"XDB",
"XS$NULL",
];
/// Databases available to this login; offline/restoring databases cannot be selected.
pub fn sqlserver_databases() -> &'static str {
"SELECT name FROM sys.databases WHERE state = 0 AND HAS_DBACCESS(name) = 1 ORDER BY name"
+151 -187
View File
@@ -1,216 +1,180 @@
//! The docker CLI as a child process: bounded runs and cancellable line streams.
//! Child processes of the docker CLI: bounded runs and cancellable line streams.
use ide_core::cli_process::{CliTool, Decoding, Input};
pub(crate) use ide_core::cli_process::{Output, Stream};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::Duration;
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};
const DOCKER: CliTool = CliTool::new("docker", Decoding::ToolOutput);
/// 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,
pub success: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
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));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
ide_core::output_encoding::decode_tool_output(&buf)
})
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
DOCKER.run(cmd, timeout, cancel)
run_with_input(cmd, timeout, cancel, None)
}
/// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`).
pub(crate) fn run_with_input(
cmd: Command,
mut cmd: Command,
timeout: Duration,
cancel: Option<&CancellationToken>,
input: Option<&str>,
) -> IdeResult<Output> {
DOCKER.run_with_input(cmd, input.map(Input::Inline), timeout, cancel)
prepare(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = spawn(&mut cmd)?;
if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = std::io::Write::write_all(&mut stdin, text.as_bytes());
}
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("docker did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = ide_core::output_encoding::decode_tool_output(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
// `\r` too: pull / build progress rewrites its line in place.
if b == b'\n' || b == b'\r' {
flush(&mut pending);
} else {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub(crate) fn stream(
cmd: Command,
mut cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
DOCKER.stream(cmd, cancel, on_line)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
use std::time::Instant;
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout);
open += 1;
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr);
open += 1;
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
drop(tx);
let mut stderr_tail: Vec<String> = Vec::new();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(Event::Line(stream, line)) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
stderr_tail.push(line.clone());
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
}
on_line(stream, line);
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn without_input_stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn input_reaches_the_child_stdin_and_is_then_closed() {
let out = run_with_input(sh("cat"), LONG, None, Some("secret\nmore")).unwrap();
assert_eq!(out.stdout, "secret\nmore");
assert!(out.success);
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-docker"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "docker did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
let mut lines = Vec::new();
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
(ok, lines, tail)
}
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
}
#[test]
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
assert!(ok);
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
assert!(of(&lines, Stream::Stderr).is_empty());
}
#[test]
fn a_stream_labels_each_line_with_its_pipe() {
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(collect("exit 0").0);
assert!(!collect("exit 2").0);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, lines, _) = collect("printf 'a\\377b\\n'");
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
}
#[test]
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream(Command::new("/nonexistent/openidea-docker"), &cancel, &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream(Command::new("/nonexistent/openidea-docker"), &CancellationToken::new(), &mut |_, _| {})
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
}
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
}
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+4
View File
@@ -382,6 +382,10 @@ impl Ledger {
}
grant.binaries.get(&key).cloned()
}
pub fn subjects(&self) -> impl Iterator<Item = (&Subject, &Grant)> {
self.grants.iter()
}
}
/// What a confirmation page shows: every capability with its risk, high risk first.
+4
View File
@@ -116,6 +116,10 @@ impl ExtensionRegistry {
Ok(())
}
pub fn point_ids(&self) -> Vec<&'static str> {
self.points.read().keys().copied().collect()
}
pub fn placement(&self, point: &str) -> Option<Placement> {
self.points.read().get(point).map(|p| p.placement())
}
+155 -193
View File
@@ -1,222 +1,184 @@
//! The gh CLI as a child process: bounded runs and cancellable line streams.
//! Child processes of the gh CLI: bounded runs and cancellable line streams.
use ide_core::cli_process::{CliTool, Decoding, Input};
pub(crate) use ide_core::cli_process::{Output, Stream};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::Duration;
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};
const GH: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
/// 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,
pub success: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
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));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
})
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
GH.run(cmd, timeout, cancel)
run_with_input(cmd, None, timeout, cancel)
}
/// [`run`] with `input` written to the child's stdin (then closed).
pub(crate) fn run_with_input(
cmd: Command,
mut cmd: Command,
input: Option<&str>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
GH.run_with_input(cmd, input.map(Input::Threaded), timeout, cancel)
prepare(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = spawn(&mut cmd)?;
if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
let input = input.to_owned();
// A writer thread: a large body must not block on a full pipe while gh is not reading yet.
std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(input.as_bytes());
});
}
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("gh did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = String::from_utf8_lossy(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
// `\r` too: git progress rewrites its line in place.
if b == b'\n' || b == b'\r' {
flush(&mut pending);
} else {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub(crate) fn stream(
cmd: Command,
mut cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
GH.stream(cmd, cancel, on_line)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
use std::time::Instant;
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout);
open += 1;
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr);
open += 1;
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
drop(tx);
let mut stderr_tail: Vec<String> = Vec::new();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(Event::Line(stream, line)) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
stderr_tail.push(line.clone());
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
}
on_line(stream, line);
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn without_input_stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn input_reaches_the_child_stdin_and_is_then_closed() {
let out = run_with_input(sh("cat"), Some("secret\nmore"), LONG, None).unwrap();
assert_eq!(out.stdout, "secret\nmore");
assert!(out.success);
}
#[test]
fn a_body_larger_than_the_pipe_does_not_block_the_child_output() {
let body = "0123456789abcdef".repeat(64 * 1024);
let out = run_with_input(sh("cat"), Some(&body), LONG, None).unwrap();
assert_eq!(out.stdout.len(), body.len());
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-gh"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "gh did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
let mut lines = Vec::new();
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
(ok, lines, tail)
}
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
}
#[test]
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
assert!(ok);
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
assert!(of(&lines, Stream::Stderr).is_empty());
}
#[test]
fn a_stream_labels_each_line_with_its_pipe() {
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(collect("exit 0").0);
assert!(!collect("exit 2").0);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, lines, _) = collect("printf 'a\\377b\\n'");
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
}
#[test]
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream(Command::new("/nonexistent/openidea-gh"), &cancel, &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err =
stream(Command::new("/nonexistent/openidea-gh"), &CancellationToken::new(), &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
}
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
}
-6
View File
@@ -18,13 +18,7 @@ uuid.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[features]
# `testing`: the `.hprof` fixture builders, for tests and benches of this crate and of crates built on it.
testing = []
[dev-dependencies]
# Self dev-dependency: turns `testing` on for this crate's benches, so a plain `cargo bench -p ide-heap` builds them.
ide-heap = { workspace = true, features = ["testing"] }
criterion = { version = "0.5", default-features = false }
proptest.workspace = true
tempfile.workspace = true
+1 -1
View File
@@ -20,7 +20,7 @@ mod strings;
#[cfg(test)]
mod test_index;
/// Fixture builders shared by this crate's tests and by dependants' tests and benches; not API.
#[cfg(any(test, feature = "testing"))]
#[doc(hidden)]
pub mod testing;
pub use analysis::{AnalyzeOptions, analyze};
-1
View File
@@ -78,7 +78,6 @@ zip.workspace = true
quick-xml = "0.42"
[dev-dependencies]
ide-heap = { workspace = true, features = ["testing"] }
ide-ssh = { workspace = true, features = ["testing"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
criterion = { version = "0.5", default-features = false }
+1 -1
View File
@@ -33,7 +33,7 @@ impl AgentSecrets {
)
}
fn with_store(store: SecretFile, local: PathBuf) -> Self {
pub fn with_store(store: SecretFile, local: PathBuf) -> Self {
Self { store, local, lock: Mutex::new(()) }
}
+3
View File
@@ -66,6 +66,9 @@ impl EventSink for RecordingSink {
}
}
/// A sink whose diagnostics are recorded; the store outlives every project.
pub type RecordSinkFactory = Box<dyn Fn(&str) -> SharedSink + Send + Sync>;
/// Wraps a sink factory so every sink it creates records diagnostics.
pub fn recording_sink_factory(store: Arc<DiagnosticsStore>, inner: crate::SinkFactory) -> crate::SinkFactory {
Box::new(move |window| {
+37 -427
View File
@@ -3,9 +3,7 @@
use crate::Host;
use ide_core::event::NotifyLevel;
use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings};
use ide_core::{
CancellationToken, ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit,
};
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit};
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
@@ -31,131 +29,18 @@ fn biome_formats(file: &Path) -> bool {
}
}
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
fn black_pyproject(file: &Path) -> Option<PathBuf> {
let mut dirs = file.parent()?.ancestors();
let root = dirs
.find(|d| {
d.join(".git").exists()
|| d.join(".hg").is_dir()
|| ide_sdk::apply::toml_has_table(&d.join("pyproject.toml"), "tool.black")
})
.or_else(|| file.parent()?.ancestors().last())?;
Some(root.join("pyproject.toml")).filter(|p| p.is_file())
}
/// Black formats files whose project configures it (`[tool.black]`).
fn black_configured(file: &Path) -> bool {
black_pyproject(file).is_some_and(|p| ide_sdk::apply::toml_has_table(&p, "tool.black"))
}
/// The single user configuration directory the formatter searches.
fn user_config_dir(tool: &str, cwd: &Path) -> Option<PathBuf> {
if cfg!(windows) {
return if tool == "black" { dirs::home_dir() } else { dirs::config_dir() };
}
let xdg = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
xdg_user_config_dir(tool, cwd, xdg.as_deref(), dirs::home_dir().as_deref())
}
fn xdg_user_config_dir(tool: &str, cwd: &Path, xdg: Option<&Path>, home: Option<&Path>) -> Option<PathBuf> {
if let Some(dir) = xdg.filter(|dir| tool == "black" || dir.is_absolute()) {
if let Ok(relative) = dir.strip_prefix("~") {
return home.map(|home| home.join(relative));
}
return Some(cwd.join(dir));
}
home.map(|home| home.join(".config"))
}
fn user_configured(tool: &str, dir: Option<&Path>) -> bool {
let Some(dir) = dir else { return false };
let names: &[&str] = match tool {
"ruff" => &["ruff/.ruff.toml", "ruff/ruff.toml", "ruff/pyproject.toml"],
"black" if cfg!(windows) => &[".black"],
"black" => &["black"],
_ => &[],
};
names.iter().any(|name| dir.join(name).is_file())
}
/// Whether Ruff finds a configuration of the project for `file`: `ruff.toml`, `.ruff.toml` or a
/// `pyproject.toml` with `[tool.ruff]` in its folder or above.
fn ruff_project_configured(file: &Path) -> bool {
file.parent().into_iter().flat_map(Path::ancestors).any(|dir| {
dir.join("ruff.toml").is_file()
|| dir.join(".ruff.toml").is_file()
|| ide_sdk::apply::toml_has_table(&dir.join("pyproject.toml"), "tool.ruff")
})
}
/// The indentation and line length for `tool`, unless a configuration of the project or the user
/// decides them (or the Ruff configuration directory is set): the file's `.editorconfig`, then
/// what was set on the Code Style › Python page, as the editor indents.
fn python_style_for(
tool: &str,
file: &Path,
configured: bool,
settings: &Settings,
editorconfig: Option<&ide_workspace::editorconfig::EditorConfigProps>,
user_dir: Option<&Path>,
) -> formatter::PythonStyle {
let has_config = configured
|| match tool {
"ruff" => ruff_project_configured(file) || user_configured("ruff", user_dir),
// Black reads the user's configuration only when its project root has no pyproject.toml.
"black" => match black_pyproject(file) {
Some(pyproject) => ide_sdk::apply::toml_has_table(&pyproject, "tool.black"),
None => user_configured("black", user_dir),
},
_ => true,
};
if has_config {
return formatter::PythonStyle::default();
}
// Only what was set: the global hard wrap (120) is not Ruff's or Black's default (88).
let page = settings.editor.code_style.languages.get("python");
let ec = editorconfig;
formatter::PythonStyle {
line_length: ec.and_then(|e| e.max_line_length).or(page.and_then(|s| s.hard_wrap_at)),
indent_width: ec.and_then(|e| e.indent_size.or(e.tab_width)).or(page.and_then(|s| s.indent.or(s.tab_size))),
use_tabs: ec
.and_then(|e| e.indent_style)
.map(|style| style == ide_workspace::editorconfig::IndentStyle::Tab)
.or(page.and_then(|s| s.use_tab)),
}
}
/// `tool` installed in the environment of the interpreter nearest to `near` (`svc/.venv/bin/ruff` or
/// `svc/.venv/bin/black`), or in `Scripts` for conda and pixi environments on Windows.
fn interpreter_tool(root: &Path, near: Option<&Path>, settings: &Settings, tool: &str) -> Option<PathBuf> {
let python = ide_sdk::apply::python_interpreter_near(root, near, settings)?;
let dir = python.parent()?;
let exe = if cfg!(windows) { format!("{tool}.exe") } else { tool.to_owned() };
[dir.join(&exe), dir.join("Scripts").join(&exe)].into_iter().find(|p| p.is_file())
}
/// Formatters print nothing for a file their configuration excludes (Black's `force-exclude`):
/// that output must not replace the file.
fn excluded_output(text: &str, formatted: &str) -> bool {
formatted.is_empty() && !text.trim().is_empty()
}
fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) -> bool {
match language.formatter.as_ref().map(|f| f.tool.as_str()) {
Some("prettier") if tool == ExternalFormatter::Biome => BIOME_LANGUAGES.contains(&language.id.as_str()),
Some("prettier") => matches!(tool, ExternalFormatter::Prettier | ExternalFormatter::Oxfmt),
Some("ruff") => matches!(tool, ExternalFormatter::Ruff | ExternalFormatter::Black),
Some("ruff") => tool == ExternalFormatter::Ruff,
_ => false,
}
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
/// then oxfmt, can replace Prettier for their
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, or Ruff). Ruff is
/// the base formatter for Python; Biome, then oxfmt, can replace Prettier for their
/// languages when configured or selected. A tool that cannot format the language is
/// rejected even when explicitly requested.
fn external_tool(
@@ -164,7 +49,7 @@ fn external_tool(
file: &Path,
settings: &LanguagesSettings,
) -> IdeResult<Option<ExternalFormatter>> {
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
let Some(language) = language.filter(|l| l.formatter.is_some()) else {
return match forced {
Some(tool) => Err(IdeError::invalid(format!(
@@ -188,11 +73,7 @@ fn external_tool(
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
} else {
enabled(Ruff).then_some(Ruff)
});
return Ok(enabled(Ruff).then_some(Ruff));
}
let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
let biome = enabled(Biome) && supports_external_format(language, Biome);
@@ -493,10 +374,8 @@ async fn provider_edits(
return Ok(Some(edits));
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
if let Some(tool) = selected
&& options.tool.is_none()
&& tool != ExternalFormatter::Black
&& !settings.languages.formatter(tool).prefer
&& match doc {
Some(doc) => project.lsp.can_format(doc).await?,
@@ -519,10 +398,7 @@ async fn provider_edits(
.map_err(|e| IdeError::internal(e.to_string()));
};
let tool_settings = settings.languages.formatter(selected);
// Black takes over from the language server in its projects, so Format on save runs it too.
let runs_on_save =
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
if options.on_save && !runs_on_save {
if options.on_save && !tool_settings.run_on_save {
return Ok(None);
}
host.require_trust(window)?;
@@ -532,21 +408,12 @@ async fn provider_edits(
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
let tool = selected.name();
let name = formatter::display_name(tool);
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
if custom.is_none() && matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let (root, near, settings) =
(project.root.clone(), snap.path.parent().map(Path::to_path_buf), settings.clone());
custom = tokio::task::spawn_blocking(move || interpreter_tool(&root, near.as_deref(), &settings, tool))
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
let tools = Tools::new(&host.local_data_dir);
let unsupported_range = range.is_some() && !formatter::supports_range(tool, &config);
let whole_selection = range.is_some() && !formatter::supports_range(tool, &config);
let project_root = project.root.clone();
let configuration_directory = settings.languages.ruff.configuration_directory.clone();
let style_settings = settings.clone();
let documents = project.documents.clone();
let result: IdeResult<(Vec<TextEdit>, bool, bool)> = tokio::task::spawn_blocking(move || {
let edits: IdeResult<Vec<TextEdit>> = tokio::task::spawn_blocking(move || {
let text = ide_text::Document::new(&snap.text);
let range = range.map(|range| format_range(&text, range));
let config_file = if tool == "ruff" {
@@ -554,133 +421,47 @@ async fn provider_edits(
} else {
None
};
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
let dir = snap.path.parent().ok_or_else(|| IdeError::invalid(format!("{name}: file has no directory")))?;
let style = if matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let editorconfig = style_settings
.editor
.code_style
.editorconfig
.then(|| documents.editorconfig().resolve(&snap.path))
.flatten();
python_style_for(
tool,
&snap.path,
config_file.is_some(),
&style_settings,
editorconfig.as_ref(),
user_config_dir(tool, dir).as_deref(),
)
} else {
formatter::PythonStyle::default()
};
let run = |range| {
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
command.current_dir(dir);
let args = formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
);
command.args(formatter::with_python_style(tool, args, style));
formatter::run(tool, command, &snap.text, &Default::default())
};
let mut old_black = false;
let formatted = match run(range) {
// Black before 23.11 has no `--line-ranges`: format the whole file instead.
Err(e) if tool == "black" && range.is_some() && e.message.contains("--line-ranges") => {
old_black = true;
run(None)?
}
result => result?,
};
if excluded_output(&snap.text, &formatted) {
return Ok((Vec::new(), false, true));
}
let edits = diff_edits(&text, &formatted);
Ok((edits, old_black, false))
command.current_dir(dir);
command.args(formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
));
let formatted = formatter::run(tool, command, &snap.text, &Default::default())?;
Ok(text
.diff(&formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
let (edits, old_black, excluded) = match result {
Ok((edits, old_black, excluded)) => (Ok(edits), old_black, excluded),
Err(e) => (Err(e), false, false),
};
// Notification titles are translated, and the catalog has "Black" as the colour.
let title = if selected == ExternalFormatter::Black { "Black formatter" } else { name };
if excluded && !options.on_save {
if edits.is_ok() && whole_selection {
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Info,
title: title.into(),
body: Some(format!("{name} left the file unchanged: its configuration excludes it")),
title: name.into(),
body: Some(format!(
"{name} does not support selection formatting for this language; formatted the whole file"
)),
});
}
let whole_selection = if old_black {
Some("This Black cannot format a selection (Black 23.11 or later can); formatted the whole file".to_owned())
} else {
(edits.is_ok() && unsupported_range).then(|| {
format!("{name} does not support selection formatting for this language; formatted the whole file")
})
};
if let Some(body) = whole_selection {
project.sink.emit(IdeEvent::Notify { level: NotifyLevel::Info, title: title.into(), body: Some(body) });
}
edits.map(Some).map_err(|e| e.with_tool(tool))
}
/// The edits that turn `text` into `formatted`, one per changed region.
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
text.diff(formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect()
}
/// Optimize Imports for a Python document no language server organizes (the Ruff server starts
/// only below a Ruff configuration): Ruff's CLI removes the unused imports and sorts the rest, with
/// the project's Ruff settings when there are any. `None` for other documents and untrusted projects.
pub async fn python_import_edits(
host: &Host,
window: &str,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<(ide_core::IpcPath, Vec<TextEdit>)>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" || snap.read_only || project.require_trust().is_err() {
return Ok(None);
}
let settings = project.settings.effective();
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.ruff.path);
let configured = settings.languages.ruff.configuration_directory.clone();
let root = project.root.clone();
let tools = Tools::new(&host.local_data_dir);
tokio::task::spawn_blocking(move || {
let config_file = ide_sdk::apply::ruff_configuration(&root, &configured)?;
let custom = custom.or_else(|| interpreter_tool(&root, snap.path.parent(), &settings, "ruff"));
let mut command = tools.formatter_command("ruff", &snap.path, custom.as_deref())?;
if let Some(dir) = snap.path.parent() {
command.current_dir(dir);
}
command.args(formatter::ruff_organize_imports_arguments(&snap.path, config_file.as_deref()));
let fixed = formatter::run("ruff", command, &snap.text, &cancel)?;
Ok(Some((snap.path, diff_edits(&ide_text::Document::new(&snap.text), &fixed))))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
#[cfg(test)]
mod tests {
use super::*;
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
@@ -725,177 +506,6 @@ mod tests {
assert_eq!(oxfmt.message, "oxfmt cannot format Python files");
let biome = tool(Some(Biome), "python", file, &settings).unwrap_err();
assert_eq!(biome.message, "Biome cannot format Python files");
assert_eq!(tool(Some(Black), "python", file, &settings).unwrap(), Some(Black));
let black = tool(Some(Black), "typescript", Path::new("/project/app.ts"), &settings).unwrap_err();
assert_eq!(black.message, "Black cannot format TypeScript files");
}
#[test]
#[cfg(not(windows))]
fn an_xdg_override_hides_fallback_python_formatter_configs() {
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
let home = cwd.join("home");
let fallback = home.join(".config");
let xdg = cwd.join("config override");
for (tool, name) in [("ruff", "ruff/ruff.toml"), ("black", "black")] {
let config = fallback.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
let probe = |xdg| xdg_user_config_dir(tool, cwd, xdg, Some(&home));
assert!(user_configured(tool, probe(None).as_deref()), "{tool} should find its default config");
assert!(!user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should skip its default config");
let config = xdg.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
assert!(user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should find its XDG config");
}
let relative = Some(Path::new("config override"));
assert_eq!(xdg_user_config_dir("ruff", cwd, relative, Some(&home)), Some(fallback));
assert_eq!(xdg_user_config_dir("black", cwd, relative, Some(&home)), Some(xdg));
assert_eq!(xdg_user_config_dir("black", cwd, Some(Path::new("~/alt")), Some(&home)), Some(home.join("alt")));
}
#[test]
fn code_style_reaches_ruff_and_black_only_without_their_configuration() {
use ide_workspace::editorconfig::{EditorConfigProps, IndentStyle};
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repo");
let user = dir.path().join("user config");
std::fs::create_dir_all(root.join("app/src")).unwrap();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(user.join("ruff")).unwrap();
let file = root.join("app/src/main.py");
let mut settings = Settings::default();
let style = |tool, settings: &Settings, editorconfig: Option<&EditorConfigProps>| {
python_style_for(tool, &file, false, settings, editorconfig, Some(&user))
};
let none = formatter::PythonStyle::default();
// Nothing set: the tools keep their defaults.
assert_eq!(style("ruff", &settings, None), none);
let page = ide_core::editor_settings::LanguageCodeStyle {
hard_wrap_at: Some(100),
tab_size: Some(2),
..Default::default()
};
settings.editor.code_style.languages.insert("python".into(), page);
let set = formatter::PythonStyle { line_length: Some(100), indent_width: Some(2), use_tabs: None };
assert_eq!(style("ruff", &settings, None), set);
assert_eq!(style("black", &settings, None), set);
assert_eq!(python_style_for("ruff", &file, true, &settings, None, Some(&user)), none);
// The file's .editorconfig wins over the page, as in the editor.
let editorconfig =
EditorConfigProps { indent_size: Some(4), indent_style: Some(IndentStyle::Space), ..Default::default() };
let indented = formatter::PythonStyle { line_length: Some(100), indent_width: Some(4), use_tabs: Some(false) };
assert_eq!(style("ruff", &settings, Some(&editorconfig)), indented);
// The user's configurations: Ruff's always counts, Black's only when the project root
// (here the repository) has no pyproject.toml.
let (black_config, ignored_black_config) =
if cfg!(windows) { (".black", "black") } else { ("black", ".black") };
std::fs::write(user.join(ignored_black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join(black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join("ruff/ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
std::fs::remove_file(user.join("ruff/ruff.toml")).unwrap();
// The project's configurations.
std::fs::write(root.join("app/pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join(".ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
}
#[test]
fn empty_output_for_a_file_with_code_is_an_exclusion_not_an_empty_file() {
assert!(excluded_output("x = 1\n", ""));
assert!(!excluded_output("\n\n", ""));
assert!(!excluded_output("x = 1\n", "x = 1\n"));
}
#[test]
fn ruff_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
let settings = Settings::default();
let near = root.join("svc/src");
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), None);
std::fs::write(bin.join(exe("ruff")), "").unwrap();
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), Some(bin.join(exe("ruff"))));
}
#[test]
fn black_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\n").unwrap();
let settings = Settings::default();
assert_eq!(interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"), None);
std::fs::write(bin.join(exe("black")), "").unwrap();
assert_eq!(
interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"),
Some(bin.join(exe("black")))
);
}
#[test]
fn black_config_or_preference_selects_black_for_python() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("svc/src")).unwrap();
std::fs::create_dir_all(root.join("api")).unwrap();
let (svc, api) = (root.join("svc/src/main.py"), root.join("api/main.py"));
let mut settings = LanguagesSettings::default();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Black));
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Ruff));
settings.black.prefer = true;
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Black));
settings.black.languages.clear();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
}
#[test]
fn black_finds_its_configuration_like_black_does() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().join("repo");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(repo.join("pkg/src")).unwrap();
let file = repo.join("pkg/src/m.py");
assert_eq!(black_pyproject(&file), None);
// A pyproject without [tool.black] is passed over, up to the repository root.
std::fs::write(repo.join("pkg/pyproject.toml"), "[project]\nname = \"pkg\"\n").unwrap();
std::fs::write(repo.join("pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(black_configured(&file));
// The repository root's pyproject is Black's even without [tool.black]; nothing above counts.
std::fs::write(repo.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
std::fs::write(dir.path().join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(!black_configured(&file));
std::fs::write(repo.join("pkg/pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
}
#[test]
+11 -22
View File
@@ -58,27 +58,6 @@ pub struct HostConfig {
pub project_environment: bool,
}
#[cfg(test)]
impl HostConfig {
/// A host under `base` for unit tests: `config`, `data` and `data` again for the machine-local
/// directory, built-in languages, no grammars, a sink that drops events, the window as its own
/// owner, the current tokio runtime and no project environment. Override fields with
/// `HostConfig { sink_for: .., ..HostConfig::for_test(base) }`. Call it inside a runtime.
pub(crate) fn for_test(base: &Path) -> Self {
Self {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}
}
}
pub struct Host {
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
@@ -643,7 +622,17 @@ mod tests {
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = Arc::downgrade(&host.open_project("main", &root).unwrap());
host.close_project_detached("main");
assert!(host.project("main").is_err());
+7 -1
View File
@@ -42,9 +42,15 @@ impl Fixture {
}
let syntax: Arc<std::sync::OnceLock<Arc<ide_language::Syntax>>> = Arc::default();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: syntax.clone(),
..HostConfig::for_test(&base)
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let fixture = Self { host, base, syntax, _tmp: tmp };
fixture.set("enabled", json!(true));
+1 -10
View File
@@ -10,7 +10,6 @@
use super::diff::{ChangedFileText, MAX_DIFF_LINES, build_unified_diff};
use super::{edits_for, open_document, requested_files, whole_range};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use crate::ops::lsp::RUFF_ORGANIZE_IMPORTS;
use ide_core::{DocId, IdeError, IdeResult};
use std::path::Path;
@@ -158,7 +157,7 @@ async fn format(call: &Call, doc: DocId, info: &ide_workspace::DocumentInfo) ->
.await
}
/// Runs the document's `source.organizeImports` code action, including the host's Ruff fallback.
/// Runs the `source.organizeImports` code action of the document's language server.
/// Nothing offered: nothing to do, unless the server says it has no such action at all.
pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> IdeResult<()> {
let host = call.host();
@@ -174,20 +173,12 @@ pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> Id
}
};
let organizes = |kind: &str| kind == ORGANIZE_IMPORTS || kind.starts_with("source.organizeImports.");
let ruff_unavailable = query
.actions
.iter()
.find(|a| a.kind.as_deref() == Some(RUFF_ORGANIZE_IMPORTS))
.and_then(|a| a.disabled_reason.clone());
let action = query
.actions
.into_iter()
.filter(|a| a.disabled_reason.is_none() && a.kind.as_deref().is_some_and(organizes))
.max_by_key(|a| a.is_preferred);
let Some(action) = action else {
if let Some(reason) = ruff_unavailable {
return Err(IdeError::unavailable(reason));
}
let offered = query.advertised_kinds.is_none_or(|kinds| kinds.iter().any(|k| k == "source" || organizes(k)));
return if offered {
Ok(())
+67 -140
View File
@@ -9,16 +9,13 @@ use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{
CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit,
};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -284,35 +281,6 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec<String
set_gradle_projects(host, window, paths, false).await
}
struct MavenSourceRefresh {
root: PathBuf,
repository: PathBuf,
candidates: Vec<(usize, sources::Artifact)>,
}
fn cached_maven_sources(
model: &BuildModel,
scopes: Vec<workspace::Scope>,
window_root: &Path,
build_dir: Option<&str>,
) -> Vec<MavenSourceRefresh> {
let Some(maven) = &model.maven else { return Vec::new() };
scopes
.into_iter()
.filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir))
.filter_map(|scope| {
let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings)
.or_else(ide_build::maven::default_local_repo)?;
let projects = maven.projects.iter().enumerate().filter(|(_, project)| {
Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root
|| (project.project_root.is_none() && scope.root == window_root)
});
let candidates = sources::cached_snapshots(&repository, projects);
(!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates })
})
.collect()
}
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
/// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`.
/// Returns the refreshed model; a failed build is reported in its `syncError`.
@@ -409,122 +377,72 @@ pub async fn build_sync(
let scopes = workspace::scopes(&p, &config)?;
let model = workspace::load_scopes(&p.root, &scopes);
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
let snapshots = if tool == BuildTool::Maven && !offline {
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
} else {
Vec::new()
};
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates))
})
.await
.map_err(join_err);
let result = async {
let (mut model, reconfigure, updates, snapshots) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
// A reactor or Gradle build may have changed its external project folders.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
bridge.configure_maven(offline, bridge_profiles.clone());
}
let lsp = project.lsp.clone();
let documents = project.documents.clone();
if snapshots.is_empty() {
tokio::spawn(async move {
update_java_projects(&lsp, &updates, reconfigure, None).await;
refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await;
});
} else {
// JDT LS resolves the binary jars while importing Maven projects.
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
let cancel = completion_token.clone();
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
let mut refreshed = Vec::new();
if let Some(maven) = &model.maven {
for batch in snapshots {
if cancel.is_cancelled() {
break;
}
refreshed.extend(sources::refresh_snapshots(
&batch.root,
&maven.projects,
&batch.repository,
&batch.candidates,
&bridge_profiles,
&cancel,
));
}
}
(model, refreshed)
})
.await
.map_err(join_err)?;
model = updated;
tokio::spawn(async move {
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
});
}
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(model)
}
.await;
host.end_request(request);
result
let (model, profiles_changed, offline_changed, updates) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
// Gradle may report project folders outside the project (`includeFlat`), and a Maven
// reactor may have gained or dropped modules beside it: index and list them.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
// New source folders and dependency versions: the Project view and External Libraries reload.
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
bridge.configure_maven(offline, bridge_profiles);
}
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436). The same
// holds for Gradle: it reuses its cached classpath on restart, so a
// dependency added to `build.gradle` stays unresolved until told to sync.
let lsp = project.lsp.clone();
let documents = project.documents.clone();
tokio::spawn(async move {
if profiles_changed || offline_changed {
// jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`).
lsp.reconfigure().await;
}
let first = updates.first().cloned();
for file in updates {
let uri = ide_lsp::path_to_uri_string(&file);
if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
}
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
if let Some(file) = first
&& let Err(e) = lsp.java_refresh_archives(&file, &changed).await
{
tracing::debug!("openidea.java.refreshArchives: {e}");
}
refresh_library_classes(&lsp, &documents).await;
});
Ok(model)
}
async fn update_java_projects(
lsp: &ide_lsp::LspManager,
updates: &[PathBuf],
reconfigure: bool,
wait: Option<&CancellationToken>,
) {
if reconfigure {
// jdtls takes the profiles and offline mode from its Maven settings.
lsp.reconfigure().await;
}
// JDT LS caches its classpath and re-imports on build-file changes. Ask it to
// re-resolve dependencies even when the build files stayed the same (#436).
if let Err(e) = lsp.java_update_project_configs(updates, wait).await {
tracing::debug!("Updating Java project configurations: {e}");
}
}
/// Re-read open library classes whose binary or attached sources changed in place.
async fn refresh_library_archives(
lsp: &Arc<ide_lsp::LspManager>,
documents: &Arc<ide_workspace::Documents>,
updates: &[PathBuf],
refreshed: Vec<PathBuf>,
) {
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect();
if let Err(e) = lsp.java_refresh_archives(updates, &archives).await {
tracing::debug!("openidea.java.refreshArchives: {e}");
}
/// Open library classes whose jar was replaced in place (a SNAPSHOT installed
/// again keeps its path) show the new contents, like a reopened one.
async fn refresh_library_classes(lsp: &Arc<ide_lsp::LspManager>, documents: &Arc<ide_workspace::Documents>) {
let changed = {
let (lsp, documents) = (lsp.clone(), documents.clone());
tokio::task::spawn_blocking(move || {
lsp.invalidate_library_archives(&archives);
documents
.open_documents()
.into_iter()
.filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?)))
.filter(|(_, uri)| {
lsp.library_class_changed(uri)
|| ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive))
})
.filter(|(_, uri)| lsp.library_class_changed(uri))
.collect::<Vec<_>>()
})
.await
@@ -1446,8 +1364,17 @@ mod maven_completion_tests {
let path = root.join("pom.xml");
std::fs::write(&path, text).unwrap();
let host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
let host = Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
+12 -1
View File
@@ -646,6 +646,7 @@ mod tests {
use super::*;
use crate::HostConfig;
use ide_db::DbDriver;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
@@ -653,7 +654,17 @@ mod tests {
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let window = "main";
host.open_project(window, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
+1 -9
View File
@@ -44,15 +44,7 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
&& config.request == "launch"
&& let Ok(project) = host.project(window)
{
let python = super::python::debug_python(&config);
let paths = super::python::with_user_paths(
super::python::paths(&project),
&host.config_dir,
&project,
python.as_deref(),
config.cwd.as_deref(),
);
super::python::prepare_debug(&mut config, &paths)?;
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
@@ -31,11 +31,18 @@ impl Fixture {
let events = Arc::new(Mutex::new(Vec::new()));
let captured = events.clone();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = captured.clone();
Arc::new(move |event| events.lock().push(event))
}),
..HostConfig::for_test(&base)
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let missing = base.join("missing").join("kotlin-debug-adapter");
host.global_settings
+36 -34
View File
@@ -4,7 +4,7 @@ use ide_command::command;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId};
use ide_workspace::dependencies::{
DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm,
pypi, python,
python,
};
use std::collections::BTreeMap;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -301,39 +301,11 @@ pub async fn python_requirements(
result
}
/// A project on pypi.org by its exact name; `None` when PyPI has no such project.
#[command(trust = outside_restricted)]
pub async fn pypi_package(
host: &Host,
window: &str,
name: String,
request: RequestId,
) -> IdeResult<Option<pypi::PypiPackage>> {
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
let search_path = std::env::var_os("PATH").unwrap_or_default();
let text = ide_tools::Http::new(&search_path)?.https_only().get_text_limited_or_empty_on_404(
&url,
16 * 1024 * 1024,
&cancel,
)?;
// The helper's body for a 404.
if text == "[]" {
return Ok(None);
}
pypi::parse_project(&text).map(Some).ok_or_else(|| IdeError::internal("invalid PyPI response"))
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
use std::sync::Arc;
struct Source;
impl DependencyVersionSource for Source {
@@ -354,7 +326,17 @@ mod tests {
let text = "# 中文 😀\n[dependencies]\ntokio = { version = \"0.2\", features = [\"full\"] }\nserde = \"1.0.100\"\nlocal = { path = \"../x\", version = \"0.2\" }\n";
let path = root.join("Cargo.toml");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
for package in ["tokio", "serde"] {
@@ -400,7 +382,17 @@ mod tests {
let text = "# 中文\nopenidea-missing-xyz>=1\n-r other.txt\n";
let path = root.join("requirements.txt");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig { local_data_dir: base_dir.join("local"), ..HostConfig::for_test(&base_dir) });
let host = Host::new(HostConfig {
config_dir: base_dir.join("config"),
data_dir: base_dir.join("data"),
local_data_dir: base_dir.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
// Restricted Mode never runs the interpreter.
@@ -440,7 +432,17 @@ mod tests {
let text = "{\n \"devDependencies\": { \"@types/node\": \"^20\" }\n}\n";
let path = root.join("package.json");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
host.dependency_versions.versions(&CachedNpm, "@types/node", &CancellationToken::new()).unwrap();
@@ -456,4 +458,4 @@ mod tests {
}
}
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package);
ide_command::domain!(dependencies: dependency_versions, python_requirements);
+1 -25
View File
@@ -1,6 +1,6 @@
use crate::Host;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
@@ -195,29 +195,6 @@ pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResul
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
}
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python
/// for now); none when they already are or the language has no arrangement.
#[command(trust = always)]
pub async fn doc_rearrange(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let syntax = host.syntax();
let snap = project.documents.text_snapshot(doc)?;
blocking(move || {
let Some(rearranged) = syntax.rearranged(&snap.language, &snap.text) else { return Ok(Vec::new()) };
let text = ide_text::Document::new(&snap.text);
Ok(text
.diff(&rearranged)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
})
.await
}
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
/// Large documents fall back to word / line / document ranges.
#[command(trust = always)]
@@ -267,7 +244,6 @@ ide_command::domain!(
doc_open_virtual,
doc_outline,
doc_python_facts,
doc_rearrange,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+8 -24
View File
@@ -28,11 +28,18 @@ impl Fixture {
let events = Arc::new(Mutex::new(Vec::new()));
let captured = events.clone();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = captured.clone();
Arc::new(move |event| events.lock().push(event))
}),
..HostConfig::for_test(&base)
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
Self { _temp: temp, host, project, events, path, outside }
@@ -198,26 +205,3 @@ async fn synchronization_only_changes_the_calling_windows_documents() {
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "external change in shared file\n");
assert_eq!(other.documents.snapshot(other_doc.id).unwrap().text, other_doc.text);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
let f = Fixture::new();
let path = f.project.root.join("board.py");
let text = "class Board:\n def 移动(self):\n return '→'\n\n def __init__(self):\n self.名前 = 1 # 初始化\n";
std::fs::write(&path, text).unwrap();
let doc = f.open(&path).await.id;
let edits = doc_rearrange(&f.host, "main", doc).await.unwrap();
let mut rearranged = ide_text::Document::new(text);
rearranged.apply_edits(&edits).unwrap();
assert_eq!(
rearranged.text(),
"class Board:\n def __init__(self):\n self.名前 = 1 # 初始化\n\n def 移动(self):\n return '→'\n"
);
// Already in order, or broken: nothing to do.
std::fs::write(&path, rearranged.text()).unwrap();
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
std::fs::write(&path, "class A:\n def b(self\n def __init__(self): ...\n").unwrap();
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
+2 -2
View File
@@ -1,7 +1,7 @@
use super::Channel;
use crate::{Host, Project};
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcBytes, RequestId};
use ide_core::{IdeError, IdeResult, RequestId};
use ide_vfs::FileEntry;
use ide_workspace::DeletionUndo;
use std::path::{Path, PathBuf};
@@ -209,7 +209,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
}
#[command(trust = always)]
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
+11 -1
View File
@@ -26,7 +26,17 @@ impl Fixture {
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project(WINDOW, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
Self { host, base, root, _temp: temp }
+8 -267
View File
@@ -6,20 +6,14 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct Outputs {
fingerprint: Option<LaunchFingerprint>,
pub snapshot: PathBuf,
pub originals: Vec<PathBuf>,
/// Live output and snapshot metadata at publication. Older records may hold an
/// incomplete copy and are rebuilt once (#5404).
#[serde(default)]
output_stamps: Option<Vec<OutputStamp>>,
#[serde(skip)]
pub failure: Option<String>,
/// Whether this result replaces jdtls diagnostics with a clean Maven build or a
@@ -29,93 +23,12 @@ pub(super) struct Outputs {
}
impl Outputs {
fn reusable(
&self,
fingerprint: &Option<LaunchFingerprint>,
snapshots: &Path,
output_dirs: impl Iterator<Item = PathBuf>,
cancel: &CancellationToken,
) -> bool {
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
fingerprint.is_some()
&& self.fingerprint == *fingerprint
&& self.snapshot.parent() == Some(snapshots)
&& !self.originals.is_empty()
&& self.output_stamps.as_ref().is_some_and(|stamps| {
stamps.len() == self.originals.len()
&& output_dirs.eq(self.originals.iter().cloned())
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
})
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct OutputStamp {
live: u64,
// A launched app may write non-class files under its snapshot classpath root.
snapshot_classes: u64,
}
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
/// without reading class or resource bytes.
#[derive(Debug, PartialEq, Eq)]
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
impl Contents {
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
if !fs::metadata(root).ok()?.is_dir() {
return None;
}
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return None;
}
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
let path = entry.path();
if meta.is_dir() {
pending.push(path);
} else {
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
}
}
}
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Some(Self(files))
}
fn stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
}
fn class_stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
for file in self.classes() {
file.hash(&mut hasher);
}
hasher.finish()
}
fn matches_copy(&self, copy: &Self) -> bool {
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
self.0.len() == copy.0.len()
&& self
.0
.iter()
.zip(&copy.0)
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
}
}
@@ -367,23 +280,13 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& let Some(maven) = &model.maven
&& outputs.reusable(
&before,
&snapshots,
compile::maven_launch_output_dirs(root, maven, module, test).into_iter().filter(|dir| dir.is_dir()),
cancel,
)
&& !cancel.is_cancelled()
&& outputs.reusable(&before, &snapshots)
{
tracing::info!(module = %module.display(), test, "Reusing Maven launch snapshot");
let mut outputs = previous.unwrap();
outputs.authoritative = true;
return Ok(Ok(outputs));
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Retain a non-reusable record even on failure, so removing the final mixed
// source still delegates to Maven to clean its old classes on the next launch.
fs::create_dir_all(record.parent().unwrap())?;
@@ -414,7 +317,6 @@ impl Session {
let snapshot = tempfile::Builder::new().prefix("launch-").tempdir_in(&snapshots)?.keep();
// Retain every new snapshot even if copying or publishing its record fails.
self.unreferenced.push(snapshot.clone());
let scanned: Vec<_> = originals.iter().map(|dir| Contents::scan(dir, cancel)).collect();
for (i, source) in originals.iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -425,43 +327,8 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// The fingerprint covers build inputs only. Another build (an external `mvn`) can
// rewrite the outputs meanwhile without changing them (#5404): record the snapshot
// only if the outputs held still through the copy and hold every module's classes.
let copied: Option<Vec<Contents>> =
(0..originals.len()).map(|i| Contents::scan(&snapshot.join(i.to_string()), cancel)).collect();
let output_stamps: Option<Vec<OutputStamp>> = copied.as_ref().and_then(|copied| {
originals
.iter()
.zip(&scanned)
.zip(copied)
.map(|((dir, before), copy)| {
let before = before.as_ref()?;
let live = Contents::scan(dir, cancel)?;
(live == *before && before.matches_copy(copy))
.then(|| OutputStamp { live: live.stamp(), snapshot_classes: copy.class_stamp() })
})
.collect()
});
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let consistent = output_stamps.is_some();
let complete = copied.as_ref().is_some_and(|copied| {
compile::launch_required_class_dirs(root, model, &pending.module, test).iter().all(|dir| {
originals.iter().position(|o| o == dir).is_some_and(|i| copied[i].classes().next().is_some())
})
});
if failure.is_none() && !(consistent && complete) {
tracing::warn!(
module = %pending.module.display(),
consistent,
complete,
"Maven outputs changed or lacked classes while copying the launch snapshot; it will not be reused"
);
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, output_stamps, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after && consistent && complete {
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
outputs.fingerprint = pending.before;
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
@@ -855,7 +722,7 @@ mod tests {
assert!(reused.authoritative);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let rebuilt = session
.build(
root,
@@ -868,7 +735,6 @@ mod tests {
.unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
assert!(rebuilt.authoritative);
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "first");
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert_eq!(calls.lines().count(), 2);
assert!(calls.lines().last().unwrap().contains("clean"));
@@ -890,6 +756,8 @@ mod tests {
let second = build().unwrap();
assert_eq!(snapshot, second.snapshot);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
assert_eq!(snapshot, build().unwrap().snapshot);
assert_eq!(fs::read_to_string(snapshot.join("0/Main.class")).unwrap(), "first");
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let updated = build().unwrap();
@@ -1025,7 +893,6 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -1086,132 +953,6 @@ mod tests {
drop(session);
assert!(!outputs.snapshot.exists());
}
/// An external `mvn` removes a dependency module's classes (`clean`) while this launch
/// builds and copies the outputs, and compiles them again only after the copy (#5404).
/// The sources never change, so only the copied outputs can tell the snapshot is broken.
fn assert_outputs_cleaned_by_an_external_build_are_not_reused(clean: &str) {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = reactor_fixture(root);
let script = root.join("mvnw");
let mut text = fs::read_to_string(&script).unwrap();
text.push_str("echo resource > lib/target/classes/app.yml\n");
text.push_str(&format!("if [ -f external-build ]; then {clean}; fi\n"));
fs::write(&script, text).unwrap();
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let a = root.join("a");
fs::write(root.join("external-build"), "").unwrap();
let first = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert!(!first.snapshot.join("1/Main.class").exists());
// The external build finished: the classes are complete again, sources unchanged.
fs::remove_file(root.join("external-build")).unwrap();
fs::create_dir_all(root.join("lib/target/classes")).unwrap();
fs::write(root.join("lib/target/classes/Main.class"), "lib").unwrap();
let second = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(second.snapshot, first.snapshot, "the incomplete snapshot must not be reused");
assert_eq!(fs::read_to_string(second.snapshot.join("1/Main.class")).unwrap(), "lib");
assert_eq!(calls(root).len(), 2);
let third = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(third.snapshot, second.snapshot, "a complete snapshot is reused");
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_snapshot_of_classes_cleaned_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm lib/target/classes/Main.class");
}
#[test]
fn a_snapshot_missing_an_output_directory_removed_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm -r lib/target/classes");
}
#[test]
fn a_partially_recompiled_dependency_snapshot_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused(
"echo other > lib/target/classes/Other.class; rm lib/target/classes/Main.class",
);
}
#[test]
fn a_new_output_directory_invalidates_a_test_launch_snapshot() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let mut build =
|| session.build(root, &model, root, BuildOptions { test: true, ..Default::default() }, None, &cancel);
let first = build().unwrap();
assert_eq!(first.originals, [root.join("target/classes")]);
fs::create_dir_all(root.join("target/test-classes")).unwrap();
fs::write(root.join("target/test-classes/GeneratedTest.class"), "test").unwrap();
let second = build().unwrap();
assert_ne!(first.snapshot, second.snapshot);
assert!(second.snapshot.join("0/GeneratedTest.class").is_file());
assert_eq!(second.snapshot, build().unwrap().snapshot);
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_record_without_output_stamps_is_rebuilt_once() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
// A count-only record may still hold a partial copy.
let record = root.join("cache/java-launch/records/main.json");
let mut json: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
json.as_object_mut().unwrap().remove("output_stamps").unwrap();
json["contents"] = serde_json::json!([{ "files": 1, "bytes": 5, "classes": 1 }]);
fs::write(&record, serde_json::to_vec(&json).unwrap()).unwrap();
let rebuilt = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(reused.snapshot, rebuilt.snapshot);
// A file the launched app wrote under its classpath root keeps the snapshot.
fs::write(reused.snapshot.join("0/app.log"), "log").unwrap();
let kept = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(kept.snapshot, reused.snapshot);
// A snapshot that lost a class since it was recorded is rebuilt.
fs::remove_file(reused.snapshot.join("0/Main.class")).unwrap();
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(again.snapshot, reused.snapshot);
assert_eq!(calls(root).len(), 3);
}
#[test]
fn contents_tell_a_rewritten_output_from_its_copy() {
let dir = tempfile::tempdir().unwrap();
let classes = dir.path().join("classes");
let cancel = CancellationToken::new();
let scan = |path: &Path| Contents::scan(path, &cancel);
fs::create_dir_all(classes.join("pkg")).unwrap();
fs::write(classes.join("pkg/A.class"), "a").unwrap();
fs::write(classes.join("app.yml"), "yml").unwrap();
let class = fs::File::options().write(true).open(classes.join("pkg/A.class")).unwrap();
let resource = fs::File::options().write(true).open(classes.join("app.yml")).unwrap();
let before = SystemTime::now();
resource.set_modified(before + std::time::Duration::from_secs(10)).unwrap();
let contents = scan(&classes).unwrap();
ide_vfs::copy(&classes, &dir.path().join("copy")).unwrap();
assert!(contents.matches_copy(&scan(&dir.path().join("copy")).unwrap()));
// A rewrite can preserve both the class file's size and the tree's newest mtime.
class.set_modified(before + std::time::Duration::from_secs(1)).unwrap();
let rewritten = scan(&classes).unwrap();
assert!(contents.matches_copy(&rewritten));
assert_ne!(rewritten.stamp(), contents.stamp());
fs::rename(classes.join("pkg/A.class"), classes.join("pkg/B.class")).unwrap();
let renamed = scan(&classes).unwrap();
assert!(!rewritten.matches_copy(&renamed));
assert_ne!(renamed.stamp(), rewritten.stamp());
assert!(scan(&dir.path().join("missing")).is_none());
}
#[test]
fn deleting_the_last_mixed_source_keeps_maven_delegation_after_failure() {
let dir = tempfile::tempdir().unwrap();
+6 -216
View File
@@ -3,9 +3,7 @@ use crate::Host;
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
use ide_command::command;
use ide_core::error::ErrorKind;
use ide_core::{
CancellationToken, DocId, IdeError, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit,
};
use ide_core::{DocId, IdeError, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
use ide_lsp::types::*;
use ide_plugin::ProviderDocument;
use std::path::Path;
@@ -152,7 +150,7 @@ fn merge_language_highlights(
server
}
/// Items from plugins (and the host's own Ruff Optimize Imports) carry no server: commands don't apply, and a code
/// Items from plugins carry no server: commands don't apply, and a code
/// action is resolved by the plugin named in its `data` ([`PluginActionRef`]).
const PLUGIN_SERVER: ServerId = ServerId(0);
@@ -911,7 +909,6 @@ pub async fn lsp_code_actions(
let target = position_document(host, window, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = project.lsp.code_actions(target, range, only.clone()).await;
let result = with_ruff_organize_imports(host, window, doc, &only, result, CancellationToken::new()).await;
let plugin_actions = match plugin_providers(host, window, doc, ProviderKind::CodeActions) {
Some((plugins, d)) => plugin_call(move || plugins.provide_code_actions(&d, range)).await.unwrap_or_default(),
None => Vec::new(),
@@ -934,76 +931,6 @@ pub async fn lsp_code_actions(
prepare_actions(project, doc, version, actions).await
}
const ORGANIZE_IMPORTS: &str = "source.organizeImports";
pub(crate) const RUFF_ORGANIZE_IMPORTS: &str = "source.organizeImports.ruff";
/// `result` and, when organize imports is asked for and no server offers it, Ruff's Optimize
/// Imports for a Python file: for the editor and for the MCP tools alike.
async fn with_ruff_organize_imports(
host: &Host,
window: &str,
doc: DocId,
only: &[String],
result: IdeResult<Vec<CodeAction>>,
cancel: CancellationToken,
) -> IdeResult<Vec<CodeAction>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if !only.iter().any(|k| k == ORGANIZE_IMPORTS) || result.as_ref().is_ok_and(|a| a.iter().any(organizes_imports)) {
return result;
}
// A missing provider permits a fallback. Stale, invalid and cancelled requests must still fail.
if result.as_ref().is_err_and(|e| !matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable)) {
return result;
}
match ruff_organize_imports(host, window, doc, cancel).await? {
Some(action) => {
let mut actions = result.unwrap_or_default();
actions.push(action);
Ok(actions)
}
None => result,
}
}
fn organizes_imports(action: &CodeAction) -> bool {
action.kind.as_deref().is_some_and(|k| k == ORGANIZE_IMPORTS || k.starts_with("source.organizeImports."))
}
/// Optimize Imports with Ruff's CLI for a Python file no language server organizes; a missing Ruff
/// is a disabled action that says so. Like a plugin's, the action carries its edit and is applied as is.
async fn ruff_organize_imports(
host: &Host,
window: &str,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<CodeAction>> {
let (edit, disabled_reason) = match crate::formatter::python_import_edits(host, window, doc, cancel).await {
Ok(None) => return Ok(None),
Ok(Some((path, edits))) => {
let files = vec![ide_core::FileEdit::Edit { path, edits, version: None }];
(Some(WorkspaceEdit { files, preconditions: Vec::new() }), None)
}
Err(e) if matches!(e.data, Some(ide_core::error::ErrorData::Tool { missing: true, .. })) => {
(None, Some("Install Ruff to optimize imports in Python files".to_owned()))
}
Err(e) => return Err(e),
};
Ok(Some(CodeAction {
title: "Optimize Imports (Ruff)".into(),
diagnostics: Vec::new(),
original_diagnostics: None,
kind: Some(RUFF_ORGANIZE_IMPORTS.into()),
is_preferred: true,
disabled_reason,
edit,
command: None,
data: None,
server: PLUGIN_SERVER,
}))
}
/// Where a plugin's code action may change or open files: the project root and its content
/// roots (a group's members, extra Project Structure folders), never git's own files.
fn plugin_edit_roots(project: &crate::Project) -> Vec<std::path::PathBuf> {
@@ -1136,19 +1063,11 @@ pub async fn lsp_code_action_query(
let version = blocking(move || documents.version(doc)).await?;
let (target, cancel) = begin_position_request(host, window, request, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = async {
let result = project.lsp.code_action_query(target, range, only.clone(), cancel.clone()).await;
let (actions, advertised_kinds) = match result {
Ok(query) => (Ok(query.actions), query.advertised_kinds),
Err(e) => (Err(e), None),
};
let actions = with_ruff_organize_imports(host, window, doc, &only, actions, cancel).await?;
let actions = prepare_actions(project, doc, version, actions).await?;
Ok(CodeActionQuery { actions, advertised_kinds })
}
.await;
let result = project.lsp.code_action_query(target, range, only, cancel).await;
host.end_request(request);
result
let mut result = result?;
result.actions = prepare_actions(project, doc, version, result.actions).await?;
Ok(result)
}
/// Resolves a code action's edit without applying it (intention preview).
@@ -1834,23 +1753,6 @@ pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeRes
Ok(out)
}
/// Colors in a document from its language servers (Tailwind classes, CSS values…).
#[command(trust = trusted)]
pub async fn lsp_document_colors(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
host.project(window)?.lsp.document_colors(doc).await
}
/// How the server that reported `color` writes it with new components.
#[command(trust = trusted)]
pub async fn lsp_color_presentations(
host: &Host,
window: &str,
doc: DocId,
color: DocumentColor,
) -> IdeResult<Vec<ColorPresentation>> {
host.project(window)?.lsp.color_presentations(doc, color).await
}
#[command(trust = trusted)]
pub async fn lsp_call_hierarchy(
host: &Host,
@@ -2224,116 +2126,6 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[cfg(unix)]
#[tokio::test]
async fn python_optimize_imports_without_a_server_runs_ruff_on_the_unsaved_text() {
use super::*;
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let file = root.join("main.py");
std::fs::write(&file, "import os\n").unwrap();
std::fs::write(root.join("notes.txt"), "import sys\n").unwrap();
// A stand-in Ruff that checks its arguments and removes the unused import.
let ruff = base.join("ruff");
std::fs::write(
&ruff,
"#!/bin/sh\n[ \"$1 $2 $3 $4 $5\" = \"check --extend-select I --fixable I,F401\" ] || exit 2\nsed '/^import sys$/d'\n",
)
.unwrap();
std::fs::set_permissions(&ruff, std::fs::Permissions::from_mode(0o755)).unwrap();
let host = crate::Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: std::sync::Arc::default(),
sink_for: Box::new(|_| std::sync::Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
project
.settings
.set(
ide_workspace::settings::SettingsScope::Project,
"languages.ruff.path",
ruff.to_string_lossy().into_owned().into(),
)
.unwrap();
let doc = project.documents.open(&file).unwrap().id;
project
.documents
.apply_edits(
doc,
&[TextEdit { range: Range::new(Pos::default(), Pos::default()), new_text: "import sys\n".into() }],
)
.unwrap();
let cancel = CancellationToken::new();
let only = [ORGANIZE_IMPORTS.to_owned()];
// A server that offers organize imports keeps the request to itself.
let server = CodeAction { kind: Some(ORGANIZE_IMPORTS.into()), ..action_stub() };
let kept =
with_ruff_organize_imports(&host, "main", doc, &only, Ok(vec![server]), cancel.clone()).await.unwrap();
assert_eq!(kept.len(), 1);
assert_eq!(kept[0].server, ServerId(7));
// No server: the Ruff action, for the editor and the MCP tools alike.
let no_server = Err(ide_core::IdeError::unavailable("no server"));
let mut actions =
with_ruff_organize_imports(&host, "main", doc, &only, no_server, cancel.clone()).await.unwrap();
assert_eq!(actions.len(), 1);
let action = actions.remove(0);
assert_eq!(action.kind.as_deref(), Some("source.organizeImports.ruff"));
assert!(organizes_imports(&action) && action.disabled_reason.is_none());
let Some(ide_core::FileEdit::Edit { edits, .. }) = action.edit.unwrap().files.into_iter().next() else {
panic!("no edit")
};
// "import sys\nimport os\n" loses "sys\nimport " and keeps "import os\n".
assert_eq!(edits, [TextEdit { range: Range::new(Pos::new(0, 7), Pos::new(1, 7)), new_text: String::new() }]);
assert_eq!(std::fs::read_to_string(file).unwrap(), "import os\n");
let imports_only = root.join("imports_only.py");
std::fs::write(&imports_only, "import sys\n").unwrap();
let imports_only = project.documents.open(&imports_only).unwrap().id;
let (_, edits) =
crate::formatter::python_import_edits(&host, "main", imports_only, cancel.clone()).await.unwrap().unwrap();
assert_eq!(edits, [TextEdit { range: Range::new(Pos::default(), Pos::new(1, 0)), new_text: String::new() }]);
let text = project.documents.open(&root.join("notes.txt")).unwrap().id;
assert!(ruff_organize_imports(&host, "main", text, cancel.clone()).await.unwrap().is_none());
assert!(
with_ruff_organize_imports(&host, "main", doc, &[], Ok(Vec::new()), cancel.clone())
.await
.unwrap()
.is_empty()
);
for kind in [ErrorKind::Cancelled, ErrorKind::OutOfSync, ErrorKind::InvalidInput] {
let error = IdeError::new(kind, "must propagate");
let result = with_ruff_organize_imports(&host, "main", doc, &only, Err(error), cancel.clone()).await;
assert_eq!(result.unwrap_err().kind, kind);
}
cancel.cancel();
let result = with_ruff_organize_imports(&host, "main", doc, &only, Ok(Vec::new()), cancel).await;
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
}
fn action_stub() -> CodeAction {
CodeAction {
title: String::new(),
diagnostics: Vec::new(),
original_diagnostics: None,
kind: None,
is_preferred: false,
disabled_reason: None,
edit: None,
command: None,
data: None,
server: ServerId(7),
}
}
#[test]
fn language_features_merge_without_overwriting_lsp_ranges_or_masking_errors() {
use super::*;
@@ -3063,9 +2855,7 @@ ide_command::domain!(
lsp_code_action_query,
lsp_code_actions,
lsp_code_lens,
lsp_color_presentations,
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_document_links,
lsp_exception_class_at,
-1
View File
@@ -27,7 +27,6 @@ pub mod nav;
pub mod notebook;
pub mod project;
mod python;
pub mod python_stubs;
pub mod refactor;
pub mod routes;
pub mod run;
-49
View File
@@ -1,7 +1,4 @@
use super::doc::blocking;
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
@@ -386,51 +383,6 @@ pub async fn web_unresolved_references(host: &Host, window: &str, doc: DocId) ->
.await
}
/// The stub (`.pyi`) of a Python document, or the implementation of a stub, and the
/// functions and classes declared in both: PyCharm's stub gutter markers.
#[command(trust = always)]
pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResult<PythonStubLinks> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large {
return Ok(PythonStubLinks::default());
}
let path = PathBuf::from(snap.path.clone());
// Modules are found in the project's Python roots and its virtualenv's site-packages.
let mut search = super::python::paths(&project);
let settings = project.settings.effective();
if let Some(venv) =
ide_sdk::apply::python_interpreter(&project.root, &settings).and_then(|p| ide_sdk::venv_of(&p))
{
search.extend(site_packages(&venv));
}
let module = module_name(&path, &search);
let candidates = counterpart_candidates(&path, &stub_path(&project.root), module.as_deref(), &search);
let watched = candidates.iter().cloned().map(IpcPath::from).collect();
let Some(counterpart) = candidates.into_iter().find(|p| project.documents.text_of(p).is_some() || p.is_file())
else {
return Ok(PythonStubLinks { candidates: watched, ..Default::default() });
};
// A counterpart too large to parse still opens; it just gets no markers.
let other = match project.documents.text_of(&counterpart) {
Some(text) => Some(text).filter(|t| t.len() as u64 <= ide_vfs::LARGE_FILE_THRESHOLD),
None => std::fs::metadata(&counterpart)
.is_ok_and(|m| m.len() <= ide_vfs::LARGE_FILE_THRESHOLD)
.then(|| project.text_of(&counterpart))
.transpose()?,
};
let links = other
.map(|other| {
match_declarations(&syntax.outline(&snap.language, &snap.text), &syntax.outline(&snap.language, &other))
})
.unwrap_or_default();
Ok(PythonStubLinks { counterpart: Some(IpcPath::from(counterpart)), links, candidates: watched })
})
.await
}
ide_command::domain!(
nav:
find_dirs,
@@ -444,7 +396,6 @@ ide_command::domain!(
mark_recent,
nav_index_definitions,
nav_inheritance,
nav_python_stubs,
nav_resolve_module,
path_completions,
recent_files,
+1 -34
View File
@@ -3,7 +3,7 @@ use ide_core::IdeResult;
use ide_dap::LaunchConfig;
use ide_workspace::roots::RootKind;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
let mut paths = vec![project.root.clone()];
@@ -19,39 +19,6 @@ pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
paths
}
/// `paths` plus the folders added to the paths of the interpreter a launch uses (All
/// Interpreters › Show Paths): `command` when it names a Python executable, else the
/// interpreter of the project or workspace member at `near`. Run, Debug and the console
/// resolve it the same way, so the same file imports the same modules in each.
pub(super) fn with_user_paths(
mut paths: Vec<PathBuf>,
config_dir: &Path,
project: &Project,
command: Option<&str>,
near: Option<&Path>,
) -> Vec<PathBuf> {
let named = command
.filter(|c| ide_sdk::apply::is_python_command(c))
.map(PathBuf::from)
.filter(|p| p.is_absolute() && p.is_file())
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
if let Some(python) = python {
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
if !paths.contains(&path) {
paths.push(path);
}
}
}
paths
}
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
extra.get("python")?.as_str().map(str::to_owned)
}
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
// Adapter-specific env takes precedence over the common launch fields in DAP.
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
-230
View File
@@ -1,230 +0,0 @@
//! `.py` ↔ `.pyi` pairing for the stub gutter markers and Navigate › Stub / Implementation:
//! which file holds a module's stub (or implementation), and which declarations match.
use ide_core::{OutlineItem, Range, SymbolKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// A declaration of the document and its counterpart in the other file.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct StubLink {
/// Qualified name, `Class.method`.
pub name: String,
/// The declaration's identifier in the document.
pub range: Range,
/// The declaration's whole extent in the document.
pub extent: Range,
/// The counterpart's identifier in `PythonStubLinks::counterpart`.
pub target: Range,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonStubLinks {
/// The stub of a `.py` document, the implementation of a `.pyi` one.
pub counterpart: Option<ide_core::IpcPath>,
pub links: Vec<StubLink>,
/// Every place the counterpart was looked for: a change to one of them may change the answer.
pub candidates: Vec<ide_core::IpcPath>,
}
/// The stub folder basedpyright reads: `stubPath` from `pyrightconfig.json` or the
/// `[tool.basedpyright]` / `[tool.pyright]` table of `pyproject.toml`, else `typings`.
pub(crate) fn stub_path(root: &Path) -> PathBuf {
let json = || {
let text = std::fs::read_to_string(root.join("pyrightconfig.json")).ok()?;
serde_json::from_str::<serde_json::Value>(&text).ok()?.get("stubPath")?.as_str().map(str::to_owned)
};
let toml = || {
let text = std::fs::read_to_string(root.join("pyproject.toml")).ok()?;
let tool = text.parse::<toml::Table>().ok()?.remove("tool")?;
["basedpyright", "pyright"].iter().find_map(|t| tool.get(t)?.get("stubPath")?.as_str().map(str::to_owned))
};
root.join(json().or_else(toml).unwrap_or_else(|| "typings".to_owned()))
}
/// The `site-packages` folders of a virtualenv (`lib/python3.x/site-packages`, `Lib/site-packages`).
pub(crate) fn site_packages(venv: &Path) -> Vec<PathBuf> {
let mut out = vec![venv.join("Lib").join("site-packages")];
if let Ok(entries) = std::fs::read_dir(venv.join("lib")) {
out.extend(entries.flatten().map(|e| e.path().join("site-packages")));
}
out.retain(|p| p.is_dir());
out
}
/// The dotted module of a Python file, from the innermost `search` folder holding it
/// (`src/a/b.py` → `a.b`, `site-packages/a/__init__.py` → `a`).
pub(crate) fn module_name(path: &Path, search: &[PathBuf]) -> Option<String> {
let base = search.iter().filter(|b| path.starts_with(b)).max_by_key(|b| b.components().count())?;
let rel = path.strip_prefix(base).ok()?.with_extension("");
let rel = if rel.file_name()? == "__init__" { rel.parent()?.to_path_buf() } else { rel };
let parts: Vec<&str> = rel.iter().map(|c| c.to_str()).collect::<Option<_>>()?;
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!parts.is_empty() && parts.iter().all(|p| valid(p))).then(|| parts.join("."))
}
/// Where the counterpart of `path` may be, nearest first: beside it, in a PEP 561
/// `<package>-stubs` folder beside its package (or `<module>-stubs/__init__.pyi` for a
/// single module), and in the `stubs` folder, which mirrors module paths (`module` names a
/// `.py` file's module, `search` lists the folders modules are found in).
pub(crate) fn counterpart_candidates(
path: &Path,
stubs: &Path,
module: Option<&str>,
search: &[PathBuf],
) -> Vec<PathBuf> {
let stub = match path.extension().and_then(|e| e.to_str()) {
Some("pyi") => true,
Some("py") => false,
_ => return Vec::new(),
};
let other = if stub { "py" } else { "pyi" };
let mut out = vec![path.with_extension(other)];
// `a/pkg-stubs/m.pyi` ↔ `a/pkg/m.py`.
for dir in path.ancestors().skip(1) {
let (Some(parent), Some(name)) = (dir.parent(), dir.file_name().and_then(|n| n.to_str())) else { break };
let renamed = match (stub, name.strip_suffix("-stubs")) {
(true, Some(package)) => package.to_owned(),
(false, None) => format!("{name}-stubs"),
_ => continue,
};
if let Ok(rest) = path.strip_prefix(dir) {
out.push(parent.join(renamed).join(rest).with_extension(other));
}
}
// `a/six.py` ↔ `a/six-stubs/__init__.pyi`.
if let (Some(dir), Some(name)) = (path.parent(), path.file_stem().and_then(|n| n.to_str())) {
if !stub {
out.push(dir.join(format!("{name}-stubs")).join("__init__.pyi"));
} else if let (true, Some(package), Some(parent)) = (
name == "__init__",
dir.file_name().and_then(|n| n.to_str()).and_then(|n| n.strip_suffix("-stubs")),
dir.parent(),
) {
out.push(parent.join(package).with_extension("py"));
}
}
// `typings/a/b.pyi` ↔ the module `a.b`: `a/b.py` or `a/b/__init__.py` in a search folder.
let modules = |rel: &Path, base: &Path, ext: &str| {
[base.join(rel).with_extension(ext), base.join(rel).join("__init__").with_extension(ext)]
};
let module = if stub { module_name(path, &[stubs.to_path_buf()]) } else { module.map(str::to_owned) };
if let Some(module) = module {
let rel: PathBuf = module.split('.').collect();
if stub {
out.extend(search.iter().flat_map(|base| modules(&rel, base, "py")));
} else {
out.extend(modules(&rel, stubs, "pyi"));
}
}
let mut seen = std::collections::HashSet::new();
out.retain(|p| p != path && seen.insert(p.clone()));
out
}
/// The declarations of `doc` (functions and classes, recursing into classes) whose
/// qualified name `other` declares too; an overloaded name targets its first declaration.
pub(crate) fn match_declarations(doc: &[OutlineItem], other: &[OutlineItem]) -> Vec<StubLink> {
let mut targets: HashMap<String, Range> = HashMap::new();
walk(other, "", &mut |name, item| {
targets.entry(name).or_insert(item.selection_range);
});
let mut links = Vec::new();
walk(doc, "", &mut |name, item| {
if let Some(target) = targets.get(&name) {
links.push(StubLink { name, range: item.selection_range, extent: item.range, target: *target });
}
});
links
}
fn walk(items: &[OutlineItem], prefix: &str, f: &mut impl FnMut(String, &OutlineItem)) {
for item in items {
let class = item.kind == SymbolKind::Class;
if !class && !matches!(item.kind, SymbolKind::Function | SymbolKind::Method | SymbolKind::Constructor) {
continue;
}
let name = if prefix.is_empty() { item.name.clone() } else { format!("{prefix}.{}", item.name) };
f(name.clone(), item);
if class {
walk(&item.children, &name, f);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::LanguageId;
use ide_language::Syntax;
fn outline(text: &str) -> Vec<OutlineItem> {
Syntax::new().outline(&LanguageId::new("python"), text)
}
#[test]
fn candidates_cover_siblings_stub_packages_and_typings() {
let typings = Path::new("/p/typings");
let site = PathBuf::from("/p/.venv/lib/python3.12/site-packages");
let search = [PathBuf::from("/p"), PathBuf::from("/p/src"), site.clone()];
let module = |p: &str| module_name(Path::new(p), &search);
assert_eq!(module("/p/src/pkg/m.py").as_deref(), Some("pkg.m"));
assert_eq!(module("/p/.venv/lib/python3.12/site-packages/requests/__init__.py").as_deref(), Some("requests"));
assert_eq!(module("/elsewhere/x.py"), None);
let py = counterpart_candidates(Path::new("/p/src/pkg/m.py"), typings, Some("pkg.m"), &search);
assert_eq!(py[0], Path::new("/p/src/pkg/m.pyi"));
assert!(py.contains(&PathBuf::from("/p/src/pkg-stubs/m.pyi")));
assert!(py.contains(&PathBuf::from("/p/src/pkg/m-stubs/__init__.pyi")));
assert!(py.contains(&PathBuf::from("/p/typings/pkg/m.pyi")));
assert!(py.contains(&PathBuf::from("/p/typings/pkg/m/__init__.pyi")));
let stub = counterpart_candidates(Path::new("/lib/pkg-stubs/sub/m.pyi"), typings, None, &search);
assert_eq!(stub[0], Path::new("/lib/pkg-stubs/sub/m.py"));
assert!(stub.contains(&PathBuf::from("/lib/pkg/sub/m.py")));
assert!(!stub.iter().any(|p| p.to_string_lossy().contains("-stubs-stubs")));
// PEP 561 stubs of a single module: `six-stubs/__init__.pyi` ↔ `six.py`.
let six = counterpart_candidates(&site.join("six-stubs/__init__.pyi"), typings, None, &search);
assert!(six.contains(&site.join("six.py")));
// `typings/` stubs of an installed package resolve into site-packages.
let typed = counterpart_candidates(Path::new("/p/typings/requests/api.pyi"), typings, None, &search);
assert!(typed.contains(&site.join("requests/api.py")));
let installed = site.join("requests/api.py");
let back = counterpart_candidates(&installed, typings, module_name(&installed, &search).as_deref(), &search);
assert!(back.contains(&PathBuf::from("/p/typings/requests/api.pyi")));
let package = counterpart_candidates(Path::new("/p/typings/pkg/__init__.pyi"), typings, None, &search);
assert!(package.contains(&PathBuf::from("/p/src/pkg.py")));
assert!(package.contains(&PathBuf::from("/p/src/pkg/__init__.py")));
assert!(counterpart_candidates(Path::new("/p/a.txt"), typings, None, &search).is_empty());
}
#[test]
fn stub_path_follows_the_pyright_settings() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("typings"));
std::fs::write(dir.path().join("pyproject.toml"), "[tool.basedpyright]\nstubPath = \"stubs\"\n").unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("stubs"));
std::fs::write(dir.path().join("pyrightconfig.json"), r#"{"stubPath": "types"}"#).unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("types"));
}
#[test]
fn declarations_match_by_qualified_name() {
let py = "def f(a):\n def inner(): pass\n return a\n\nclass C:\n def __init__(self): pass\n def m(self): pass\n def extra(self): pass\n\ndef g(): pass\nX = 1\n";
let pyi = "from typing import overload\n@overload\ndef f(a: int) -> int: ...\n@overload\ndef f(a: str) -> str: ...\nclass C:\n def __init__(self) -> None: ...\n def m(self) -> None: ...\ndef inner() -> None: ...\nX: int\n";
let links = match_declarations(&outline(py), &outline(pyi));
let names: Vec<(&str, u32, u32)> =
links.iter().map(|l| (l.name.as_str(), l.range.start.line, l.target.start.line)).collect();
assert_eq!(names, [("f", 0, 2), ("C", 4, 5), ("C.__init__", 5, 6), ("C.m", 6, 7)]);
}
}
+9 -23
View File
@@ -488,17 +488,14 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
if !executable.is_file() {
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
}
config.command = ide_core::ipc_path::to_ipc(&executable);
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
&& !Path::new(&config.command).is_file()
&& Path::new(&config.command).components().count() > 1
{
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
}
if config.kind == "tomcat" {
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
@@ -521,21 +518,10 @@ async fn start_inner(
})
.await?;
}
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
if is_python {
let near = ide_run::scope::owner(&project.root, &config);
python_paths = super::python::with_user_paths(
python_paths,
&host.config_dir,
&project,
Some(&config.command),
Some(&near),
);
}
let encoding = settings.console.encoding;
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths,
python_paths: if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) },
ruby_reporter: ruby_reporter_dir(host, &config),
};
project.require_trust()?;
+27 -151
View File
@@ -120,49 +120,6 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) ->
.map_err(join_err)?
}
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
#[command(trust = outside_restricted)]
pub async fn sdk_python_sys_path(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<ide_core::IpcPath>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let paths = paths.ok_or_else(|| {
IdeError::invalid(format!(
"Cannot read sys.path of {}: the interpreter failed or did not answer in time",
python.display()
))
})?;
Ok(paths.iter().map(|p| p.as_path().into()).collect())
})
.await
.map_err(join_err);
host.end_request(request);
result?
}
/// For each folder added to an interpreter's paths, why it stays off the import path
/// (`None`: it is used). The folders may not be saved yet.
#[command(trust = outside_restricted)]
pub async fn sdk_python_user_path_problems(
host: &Host,
window: &str,
paths: Vec<String>,
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
host.require_trust_if_project(window)?;
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
.await
.map_err(join_err)
}
/// The interpreter of the workspace member `near` belongs to, else the project's.
pub(crate) fn effective_python(
config_dir: &std::path::Path,
@@ -379,21 +336,7 @@ pub async fn sdk_locate_tools(
.map_err(join_err)
}
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
#[command(trust = outside_restricted)]
pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<String>> {
host.require_trust_if_project(window)?;
let root = host.project(window)?.root.clone();
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
host.end_request(request);
result?
}
/// Creates a Python environment and streams its output through `on_output`.
/// With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
#[allow(clippy::too_many_arguments)]
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
#[command(trust = outside_restricted)]
pub async fn sdk_python_create_venv(
host: &Host,
@@ -401,14 +344,13 @@ pub async fn sdk_python_create_venv(
tool: ide_sdk::python::VenvTool,
base: PathBuf,
location: PathBuf,
install_packages: bool,
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
let _ = on_output.send(line);
})
})
@@ -423,34 +365,12 @@ pub async fn sdk_python_packages(
host: &Host,
window: &str,
python: PathBuf,
outdated: bool,
request: RequestId,
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel))
.await
.map_err(join_err);
host.end_request(request);
result?
}
/// A package index other than PyPI that installing from `python` uses; `None` for PyPI.
#[command(trust = outside_restricted)]
pub async fn sdk_python_package_index(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Option<String>> {
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)
})
.await
.map_err(join_err);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
host.end_request(request);
result?
}
@@ -503,6 +423,7 @@ mod tests {
use super::*;
use crate::HostConfig;
use std::path::Path;
use std::sync::Arc;
fn fake_venv(root: &Path, name: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
@@ -515,74 +436,23 @@ mod tests {
python
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_launch_takes_the_user_paths_of_the_interpreter_it_uses() {
use crate::ops::python::{debug_python, with_user_paths};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (root, bare, own) = (base.join("project"), base.join("bare"), base.join("own"));
let (for_main, for_own) = (base.join("for-main"), base.join("for-own"));
for dir in [&root, &bare, &own, &for_main, &for_own] {
std::fs::create_dir(dir).unwrap();
}
let (main_python, own_python) = (fake_venv(&root, ".venv"), fake_venv(&own, ".venv"));
ide_workspace::workspace::Workspace::attach(&root, "ws", vec![root.clone(), bare.clone(), own.clone()])
.unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
let text = |p: &Path| p.to_string_lossy().into_owned();
project
.settings
.set(
ide_workspace::SettingsScope::Global,
"languages.python.interpreterPaths",
serde_json::json!({ text(&main_python): [text(&for_main)], text(&own_python): [text(&for_own)] }),
)
.unwrap();
let paths = |command: Option<&str>, near: &Path| {
with_user_paths(Vec::new(), &host.config_dir, &project, command, Some(near))
};
// A member without a Python of its own runs on the primary project's interpreter;
// a member with its own virtualenv on that one.
assert_eq!(paths(None, &root), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &bare), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &own), std::slice::from_ref(&for_own));
// The interpreter a launch names wins over where it runs; a manager's command does not name one.
assert_eq!(paths(Some(&text(&own_python)), &bare), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("uv"), &own), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("python3"), &bare), std::slice::from_ref(&for_main));
// What is already on the path is neither repeated nor dropped.
let kept = with_user_paths(vec![root.clone(), for_main.clone()], &host.config_dir, &project, None, Some(&root));
assert_eq!(kept, [root.clone(), for_main]);
// Debug resolves a relative command against its working directory before sending it.
let debug_interpreter = bare.join("..").join(own_python.strip_prefix(&base).unwrap());
let mut launch = ide_dap::LaunchConfig {
name: "Python".into(),
adapter: "debugpy".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(bare.as_path().into()),
env: Default::default(),
extra_json: Some(serde_json::json!({ "python": text(&debug_interpreter) }).to_string()),
};
assert_eq!(debug_python(&launch), Some(text(&debug_interpreter)));
assert_eq!(paths(debug_python(&launch).as_deref(), &bare), [for_own]);
launch.extra_json = Some(serde_json::json!({ "python": ["uv", "run", "python"] }).to_string());
assert_eq!(debug_python(&launch), None);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_hand_picked_venv_is_resolved_like_a_detected_interpreter() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
@@ -636,7 +506,17 @@ mod tests {
]);
std::fs::write(config.join("recent.json"), serde_json::to_vec(&recent).unwrap()).unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let host = Host::new(HostConfig {
config_dir: config,
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
@@ -665,12 +545,8 @@ ide_command::domain!(
sdk_project_libraries,
sdk_python_create_venv,
sdk_python_effective,
sdk_python_hatch_envs,
sdk_python_interpreter,
sdk_python_packages,
sdk_python_package_index,
sdk_python_pip,
sdk_python_project_interpreters,
sdk_python_sys_path,
sdk_python_user_path_problems,
);
+5 -110
View File
@@ -20,18 +20,13 @@ fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
.iter()
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.map(|p| resolve_dictionary(p, root))
.map(|p| match p.strip_prefix("~/") {
Some(rest) => dirs::home_dir().unwrap_or_default().join(rest),
None => root.join(p),
})
.collect()
}
/// One `spelling.customDictionaries` entry resolved: `~/…` from home, relative from the project root.
fn resolve_dictionary(text: &str, root: &Path) -> PathBuf {
match text.strip_prefix("~/") {
Some(rest) => dirs::home_dir().unwrap_or_default().join(rest),
None => root.join(text),
}
}
fn speller(project: &Project) -> Speller {
let s = project.settings.effective().spelling;
let words = s.ide_words.iter().chain(&s.project_words);
@@ -121,104 +116,4 @@ pub async fn spell_suggest(host: &Host, window: &str, word: String) -> IdeResult
.await
}
/// Appends `word` to the custom dictionary `dictionary` (a
/// `spelling.customDictionaries` entry: `~/…` from home, relative from the
/// project root) and reports which file was written, creating it when missing.
/// A Hunspell `.dic` with a `.aff` beside it keeps its word count line current;
/// the speller picks the change up through its own mtime cache.
#[command(trust = always)]
pub async fn spell_save_to_dictionary(
host: &Host,
window: &str,
dictionary: String,
word: String,
) -> IdeResult<String> {
let project = host.project(window)?;
blocking(move || {
let entry = dictionary.trim();
if entry.is_empty()
|| !project.settings.read_effective(|s| s.spelling.custom_dictionaries.iter().any(|p| p.trim() == entry))
{
return Err(IdeError::invalid("Select a configured custom dictionary"));
}
let w = word.trim();
// One word per line: no whitespace, no line breaks; digits and hyphens
// may appear, but at least one letter (a number list checks nothing).
if w.starts_with('#')
|| w.contains('/')
|| w.chars().any(|c| c.is_whitespace() || c.is_control())
|| !w.chars().any(|c| c.is_alphabetic())
{
return Err(IdeError::invalid(format!("'{word}' is not a word a dictionary can list")));
}
let path = resolve_dictionary(entry, &project.root);
// Serialize the read/modify/write across projects that share a dictionary.
static SAVES: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
let _save = SAVES.lock();
let mut text = match std::fs::metadata(&path) {
Ok(m) if !m.is_file() || m.permissions().readonly() => {
return Err(IdeError::invalid(format!("{} is not a writable dictionary file", path.display())));
}
Ok(_) => std::fs::read_to_string(&path)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.into()),
};
let hunspell = ide_spell::affix_file(&path).is_some();
let already_listed = if hunspell {
text.lines().any(|line| line.trim() == w)
} else {
ide_spell::parse_word_list(&text).contains(&w.to_lowercase())
};
if already_listed {
return Ok(String::new());
}
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
if hunspell {
let body = text.strip_prefix('\u{feff}').unwrap_or(&text);
let start = text.len() - body.len()
+ body
.split_inclusive('\n')
.take_while(|line| line.trim_start().starts_with('#'))
.map(str::len)
.sum::<usize>();
let header = text[start..].lines().next().unwrap_or_default();
if let Some(count) = header.trim().parse::<usize>().ok().and_then(|n| n.checked_add(1)) {
text.replace_range(start..start + header.len(), &count.to_string());
} else if text.is_empty() {
text.push_str("1\n");
}
}
if !text.is_empty() && !text.ends_with('\n') {
text.push_str(newline);
}
text.push_str(w);
text.push_str(newline);
// A dictionary file may name folders that do not exist yet (a fresh
// project layout): create them, then write.
if let Some(dir) = path.parent()
&& !dir.is_dir()
{
std::fs::create_dir_all(dir)?;
}
ide_vfs::write_atomic_strict(&path, text.as_bytes())?;
Ok(path.to_string_lossy().into_owned())
})
.await
}
ide_command::domain!(spell: spell_check, spell_suggest, spell_save_to_dictionary);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_home_dictionaries() {
if let Some(home) = dirs::home_dir() {
assert_eq!(
resolve_dictionary("~/words/personal.txt", Path::new("project")),
home.join("words/personal.txt")
);
}
}
}
ide_command::domain!(spell: spell_check, spell_suggest);
+11 -2
View File
@@ -272,8 +272,17 @@ impl Fixture {
std::fs::create_dir_all(root.join("src")).unwrap();
let source = root.join("src/Chains.java");
std::fs::write(&source, SOURCE).unwrap();
let host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
let host = Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project(WINDOW, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
Self { host, source, _temp: temp }
+17 -7
View File
@@ -1,7 +1,7 @@
use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_core::{IdeResult, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
@@ -9,7 +9,7 @@ mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
#[command(trust = always)]
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, mime: String) -> IdeResult<String> {
pub async fn term_store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
if data.len() > MAX_IMAGE_BYTES {
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
}
@@ -183,18 +183,28 @@ pub fn term_available_shells() -> Vec<String> {
mod tests {
use super::*;
use crate::HostConfig;
use ide_core::error::ErrorKind;
use ide_core::{NullSink, error::ErrorKind};
use std::sync::Arc;
#[tokio::test]
async fn image_size_limit_is_checked_before_storage() {
let root = tempfile::tempdir().unwrap();
let host = Host::new(HostConfig::for_test(root.path()));
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: root.path().join("data"),
local_data_dir: root.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let id = TerminalId::next();
let error =
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "image/png".into()).await.unwrap_err();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
+11 -1
View File
@@ -542,7 +542,17 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir(&root).unwrap();
let backend = crate::Host::new(crate::HostConfig::for_test(tmp.path()));
let backend = crate::Host::new(crate::HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("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,
});
backend.open_project("main", &root).unwrap();
let active = backend.project("main").unwrap().files_events_active.clone();
let plugins =
@@ -20,7 +20,6 @@ pub(crate) fn merge(server: Vec<InlayHint>, plugin: Vec<PluginInlayHint>, range:
padding_right: h.padding_right,
tooltip: h.tooltip,
parts: Vec::new(),
text_edits: Vec::new(),
}));
out.sort_by_key(|h| (h.position.line, h.position.col));
out
@@ -51,7 +50,6 @@ mod tests {
padding_right: true,
tooltip: None,
parts: Vec::new(),
text_edits: Vec::new(),
}
}
+11 -1
View File
@@ -130,7 +130,17 @@ mod tests {
#[tokio::test]
async fn a_tool_window_call_carries_the_active_editor() {
let tmp = tempfile::tempdir().unwrap();
let host = Host::new(HostConfig::for_test(tmp.path()));
let host = Host::new(HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let range = ide_core::Range::new(ide_core::Pos::new(1, 0), ide_core::Pos::new(1, 4));
let active = PluginEditor { path: "/p/a.rs".into(), language: "rust".into(), selections: vec![range] };
let inv = view_invocation(&host, "main", None, Some(active)).unwrap();
+6 -6
View File
@@ -200,12 +200,7 @@ impl Host {
// resolve imports into them. A container target already supplies its own
// `extraPaths` (the site-packages snapshot); don't mix local sources into it.
if !container_python {
let mut paths = python_dependency_roots(&effective, root);
// The folders added to the paths of the interpreter this server analyses with.
if let Some(python) = ide_sdk::apply::python_server_interpreter(root, server_root, &effective) {
paths.extend(ide_sdk::apply::interpreter_user_paths(&python, &effective));
}
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
ide_sdk::apply::configure_python_extra_paths(cfg, &python_dependency_roots(&effective, root));
}
if cfg.name == "jdtls" {
// A workspace member keeps its build model under its own key (Build Project).
@@ -1204,6 +1199,11 @@ impl Project {
self.with_log_repo_of(path, |r| f(r as &dyn Backend))
}
/// `with_repo` through the backend-agnostic Changes-view surface.
pub fn with_backend<T>(&self, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
self.with_backend_at(None, f)
}
/// `with_repo_recorded` through the backend-agnostic Changes-view surface.
pub fn with_backend_recorded<T>(
&self,
+11 -1
View File
@@ -87,7 +87,17 @@ mod tests {
#[tokio::test]
async fn without_a_credential_store_the_password_lasts_the_session() {
let tmp = tempfile::tempdir().unwrap();
let mut host = Host::new(crate::HostConfig::for_test(tmp.path()));
let mut host = Host::new(crate::HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let path = tmp.path().join("data/proxy-password.json");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, r#"{"httpProxy": "old"}"#).unwrap();
+1 -2
View File
@@ -27,8 +27,7 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
pub const PROTOCOL_VERSION: u32 = 3;
pub const PROTOCOL_VERSION: u32 = 2;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+12 -4
View File
@@ -1,7 +1,6 @@
//! The mode new agent tasks start in.
mod common;
use ide_core::NullSink;
use ide_host::{Host, HostConfig};
use serde_json::json;
use std::path::Path;
@@ -42,8 +41,17 @@ async fn new_tasks_start_asking_for_approval_when_the_user_chose_so() {
std::fs::write(config.join("settings.toml"), "[agents]\nnewTaskApprovals = \"ask\"\n").unwrap();
// A project's own settings don't choose this.
std::fs::write(root.join(".openidea/settings.toml"), "[agents]\nnewTaskApprovals = \"bypass\"\n").unwrap();
let host =
Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) }));
let host = Arc::new(Host::new(HostConfig {
config_dir: config.clone(),
data_dir: data,
local_data_dir: tmp.path().join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
assert_eq!(codex_mode(&host).await.as_deref(), Some("ask"));
+13 -4
View File
@@ -1,8 +1,7 @@
//! Values of agents' environment variables live in the credential store; agent files keep only their names.
mod common;
use ide_host::Host;
use ide_core::NullSink;
use ide_host::{Host, HostConfig};
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -11,7 +10,17 @@ use std::sync::Arc;
const VALUE: &str = "agent-env-value-5b2d81";
fn host(dir: &Path) -> Arc<Host> {
Arc::new(Host::new(common::host_config(dir)))
Arc::new(Host::new(HostConfig {
config_dir: dir.join("config"),
data_dir: dir.join("data"),
local_data_dir: dir.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
fn open(host: &Host, tmp: &tempfile::TempDir) {
+13 -4
View File
@@ -1,21 +1,30 @@
//! External MCP servers in Settings › Agents, as the host stores and lists them.
mod common;
use ide_agent::{McpScope, McpServer, McpServerInput};
use ide_core::NullSink;
use ide_core::settings::McpTransport;
use ide_host::Host;
use ide_host::ops::agent::{
agent_mcp_import as mcp_import, agent_mcp_list as mcp_list, agent_mcp_save as mcp_save,
agent_mcp_set_enabled as mcp_set_enabled,
};
use ide_host::{Host, HostConfig};
use std::path::{Path, PathBuf};
use std::sync::Arc;
fn open(base: &Path) -> (Arc<Host>, PathBuf) {
let root = dunce::canonicalize(base).unwrap().join("project");
std::fs::create_dir_all(root.join(".openidea")).unwrap();
let host = Arc::new(Host::new(common::host_config(base)));
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
(host, root)
+17 -11
View File
@@ -1,9 +1,8 @@
//! Separate project windows share discovery and its backend-enforced cooldown.
#![cfg(unix)]
mod common;
use ide_agent::AgentEvent;
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
use std::time::Duration;
@@ -44,21 +43,28 @@ done
),
)
.unwrap();
let host = Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) });
let host = Host::new(HostConfig {
config_dir: config,
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("first", &root).unwrap();
host.open_project("second", &root).unwrap();
let (send, mut events) = tokio::sync::mpsc::unbounded_channel();
for window in ["first", "second"] {
let send = send.clone();
host.project(window).unwrap().agents.subscribe_as(
"",
Arc::new(move |event| {
if let AgentEvent::ModelCatalog { catalog } = event {
let _ = send.send((window, catalog));
}
}),
);
host.project(window).unwrap().agents.subscribe(Arc::new(move |event| {
if let AgentEvent::ModelCatalog { catalog } = event {
let _ = send.send((window, catalog));
}
}));
}
for _ in 0..20 {
for window in ["first", "second"] {
+12 -4
View File
@@ -1,7 +1,5 @@
//! Each project of a workspace keeps its own excluded folders: they apply below that project only.
mod common;
use ide_core::RequestId;
use ide_core::{NullSink, RequestId};
use ide_host::{Host, HostConfig, ops};
use ide_workspace::settings::SettingsScope;
use std::path::{Path, PathBuf};
@@ -9,7 +7,17 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
fn host(base: &Path) -> Host {
Host::new(HostConfig { local_data_dir: base.join("local"), ..common::host_config(base) })
Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
})
}
/// Files containing `needle` that Find in Files reports, by path.
-62
View File
@@ -1,62 +0,0 @@
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
mod common;
use ide_core::IpcBytes;
use ide_host::Host;
use ide_host::rpc::{self, Dispatcher, Invoke};
use ide_jsonrpc::{Handler, Peer};
use serde_json::{Value, json};
use std::sync::{Arc, OnceLock};
struct Client;
impl Handler for Client {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
async fn connect(base: &std::path::Path) -> Peer {
let host = Arc::new(Host::new(common::host_config(base)));
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host, Dispatcher::standard(), Arc::new(OnceLock::new()), sr, sw));
let (cr, cw) = tokio::io::split(client_io);
Peer::connect(cr, cw, Arc::new(Client))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_bytes_cross_the_protocol_as_base64() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let bytes: Vec<u8> = (0..=255).cycle().take(3 * 1024 * 1024 + 1).collect();
let path = tmp.path().join("image.bin");
let args = json!({ "path": path, "data": IpcBytes(bytes.clone()) });
assert!(args["data"].is_string());
// Measure the envelope separately so the assertion is independent of the temp directory.
let envelope = serde_json::to_vec(&json!({ "path": path, "data": "" })).unwrap();
let body = serde_json::to_vec(&args).unwrap();
assert_eq!(body.len(), envelope.len() + bytes.len().div_ceil(3) * 4);
let call = Invoke { window: "main".into(), cmd: "fs_create_file_bytes".into(), args };
peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_array_of_numbers_is_not_accepted_as_bytes() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let path = tmp.path().join("old.bin");
let call = Invoke {
window: "main".into(),
cmd: "fs_create_file_bytes".into(),
args: json!({ "path": path, "data": [1, 2, 3] }),
};
let error = peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap_err();
assert!(error.message.contains("argument data"), "{error:?}");
assert!(!path.exists());
}
+24 -5
View File
@@ -2,9 +2,8 @@
//! and leaves the other windows' processes alone.
#![cfg(unix)]
mod common;
use ide_host::{Host, ops};
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -28,7 +27,17 @@ fn closing_a_project_closes_its_terminals_and_keeps_other_windows() {
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
runtime.block_on(async {
let host = Arc::new(Host::new(common::host_config(tmp.path())));
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("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project_shell = ops::term::term_spawn(&host, "main", options(&root), ops::Channel::new(|_| {}))
@@ -58,7 +67,17 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(1).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
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("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: runtime.handle().clone(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
-23
View File
@@ -1,23 +0,0 @@
//! Shared by the integration tests (each declares `mod common;`).
use ide_host::HostConfig;
use std::path::Path;
use std::sync::Arc;
/// A host under `base`: `config`, `data` and `data` again for the machine-local directory,
/// built-in languages, no grammars, a sink that drops events, the window as its own owner, the
/// current tokio runtime and no project environment. Override fields with
/// `HostConfig { sink_for: .., ..common::host_config(base) }`. Call it inside a runtime.
pub fn host_config(base: &Path) -> HostConfig {
HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}
}
@@ -5,8 +5,6 @@
//! this machine's Python must not have Django installed.
#![cfg(unix)]
mod common;
use ide_core::IdeEvent;
use ide_host::{Host, HostConfig, ops};
use ide_run::{OutputChunk, RunConfig};
@@ -20,6 +18,11 @@ type Events = Arc<Mutex<Vec<IdeEvent>>>;
fn host(base: &Path, events: &Events) -> Arc<Host> {
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new({
let events = events.clone();
move |_| {
@@ -27,7 +30,9 @@ fn host(base: &Path, events: &Events) -> Arc<Host> {
Arc::new(move |e: IdeEvent| events.lock().unwrap().push(e))
}
}),
..common::host_config(base)
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
+13 -4
View File
@@ -1,6 +1,6 @@
mod common;
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
@@ -11,8 +11,17 @@ async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("notes.txt"), "hello\n").unwrap();
let host =
Host::new(HostConfig { data_dir: data.clone(), local_data_dir: local.clone(), ..common::host_config(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: data.clone(),
local_data_dir: local.clone(),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert_eq!(std::path::PathBuf::from(ops::tools::jdk_download_location(&host).unwrap()), local.join("tools/jdks"));
let light = host.open_light("main", &root.join("notes.txt")).unwrap();
assert!(light.cache_dir.starts_with(&local));
+13 -4
View File
@@ -1,14 +1,23 @@
mod common;
use ide_host::Host;
use ide_core::NullSink;
use ide_host::ops::db;
use ide_host::{Host, HostConfig};
use std::sync::Arc;
#[tokio::test]
async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
+13 -5
View File
@@ -2,11 +2,9 @@
//! that sends no real window (the desktop shell once passed `""`) never reaches the debugger,
//! and a project in Restricted Mode never reads the debuggee's memory.
mod common;
use ide_core::IdeError;
use ide_host::Host;
use ide_core::{IdeError, NullSink};
use ide_host::rpc::{self, Dispatcher, Invoke};
use ide_host::{Host, HostConfig};
use ide_jsonrpc::{Handler, Peer};
use serde_json::{Value, json};
use std::sync::{Arc, OnceLock};
@@ -41,7 +39,17 @@ fn host(trusted: bool) -> (Arc<Host>, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir(&root).unwrap();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
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("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, trusted, false).unwrap();
host.open_project("main", &root).unwrap();
(host, tmp)
+13 -5
View File
@@ -1,8 +1,6 @@
mod common;
use ide_core::RequestId;
use ide_core::{NullSink, RequestId};
use ide_host::{
Host,
Host, HostConfig,
ops::{Channel, fs::fs_synchronize_directories},
};
use ide_vfs::{DirectorySyncAction as Action, DirectorySyncOperation, DirectorySyncProgress};
@@ -20,7 +18,17 @@ fn op(path: &str, action: Action, overwrite: bool) -> DirectorySyncOperation {
}
fn host(base: &Path) -> Host {
Host::new(common::host_config(base))
Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
})
}
#[tokio::test(flavor = "multi_thread")]
+13 -4
View File
@@ -2,9 +2,8 @@
//! (`OPENIDEA_DOCKER`) that prints what it was given.
#![cfg(unix)]
mod common;
use ide_host::{Host, ops};
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use ide_run::{OutputChunk, RunConfig};
use parking_lot::Mutex;
use std::collections::BTreeMap;
@@ -14,7 +13,17 @@ use std::sync::Arc;
use std::time::Duration;
fn host(base: &Path) -> Arc<Host> {
Arc::new(Host::new(common::host_config(base)))
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
fn config(target: &str, root: &Path) -> RunConfig {
@@ -4,9 +4,8 @@
//! `docker` with the Compose plugin must be on `PATH`.
#![cfg(unix)]
mod common;
use ide_host::{Host, ops};
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use ide_run::{OutputChunk, RunConfig};
use parking_lot::Mutex;
use std::collections::BTreeMap;
@@ -16,7 +15,17 @@ use std::sync::Arc;
use std::time::Duration;
fn host(base: &Path) -> Arc<Host> {
Arc::new(Host::new(common::host_config(base)))
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
fn config(id: &str, target: &str, root: &Path, args: &[&str]) -> RunConfig {
+14 -5
View File
@@ -1,8 +1,7 @@
//! Explicit external logs allow history reads without adding a writable project root.
mod common;
use ide_host::{Host, ops::vcs};
use std::{path::Path, process::Command};
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops::vcs};
use std::{path::Path, process::Command, sync::Arc};
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git")
@@ -32,7 +31,17 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() {
git(&external, &["rm", "deleted.txt"]);
git(&external, &["commit", "-m", "delete"]);
let head = git(&external, &["rev-parse", "HEAD"]);
let host = Host::new(common::host_config(&base));
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
// A standalone editor needs no project, indexer, or writable VCS root.
vcs::vcs_open_external_log(&host, "standalone", external.clone()).await.unwrap();
let standalone = vcs::vcs_log(&host, "standalone", Some(external.clone()), Default::default()).await.unwrap();
+13 -3
View File
@@ -1,6 +1,6 @@
mod common;
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn links_are_validated_persisted_and_unlinked_without_removing_files() {
@@ -12,7 +12,17 @@ async fn links_are_validated_persisted_and_unlinked_without_removing_files() {
std::fs::write(dir.join("settings.gradle"), "rootProject.name = 'same-name'").unwrap();
}
let config = base.join("config");
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..common::host_config(&base) });
let host = Host::new(HostConfig {
config_dir: config.clone(),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project("main", &root).unwrap();
assert!(ops::build::gradle_link_projects(&host, "main", vec!["b".into()]).await.is_err());
host.set_project_trust(&root, true, false).await.unwrap();
+8 -3
View File
@@ -8,8 +8,6 @@
//! pinned versions and runs one language per job:
//! `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>`.
mod common;
use ide_core::{ChangeSet, DocId, IdeEvent, Pos, Range, RequestId, TextChange};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::{FormatOptions, GotoKind};
@@ -184,6 +182,11 @@ impl Smoke {
let events: Events = Arc::default();
let app = tmp.path().join("app");
let host = Arc::new(Host::new(HostConfig {
config_dir: app.join("config"),
data_dir: app.join("data"),
local_data_dir: app.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new({
let events = events.clone();
move |_| {
@@ -191,7 +194,9 @@ impl Smoke {
Arc::new(move |e: IdeEvent| events.lock().unwrap().push(e))
}
}),
..common::host_config(&app)
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project(WINDOW, &root).unwrap();
+13 -5
View File
@@ -1,14 +1,22 @@
//! LightEdit: a window editing loose files without a project.
mod common;
use ide_core::{ChangeSet, TextChange};
use ide_host::{Host, catalogue::TrustClass, ops};
use ide_core::{ChangeSet, NullSink, TextChange};
use ide_host::{Host, HostConfig, catalogue::TrustClass, ops};
use std::sync::Arc;
use std::time::Duration;
fn host(base: &std::path::Path) -> Arc<Host> {
Arc::new(Host::new(common::host_config(base)))
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+24 -4
View File
@@ -1,7 +1,7 @@
mod common;
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use ide_workspace::settings::SettingsScope;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
@@ -17,7 +17,17 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
std::fs::write(root.join("core/pom.xml"), "<project><artifactId>core</artifactId></project>").unwrap();
std::fs::write(sibling.join("pom.xml"), b_pom).unwrap();
let config = base.join("config");
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..common::host_config(&base) });
let host = Host::new(HostConfig {
config_dir: config.clone(),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
@@ -90,7 +100,17 @@ async fn reactor_module_beside_a_trusted_project_is_a_content_root_until_removed
std::fs::write(root.join("pom.xml"), reactor("<module>core</module><module>../service-a</module>")).unwrap();
std::fs::write(root.join("core/pom.xml"), "<project><artifactId>core</artifactId></project>").unwrap();
std::fs::write(service.join("pom.xml"), "<project><artifactId>service-a</artifactId></project>").unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..common::host_config(&base) });
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project("main", &root).unwrap();
let project = || host.project("main").unwrap();
assert!(project().content_roots().is_empty(), "Restricted Mode does not widen the index");
+10 -16
View File
@@ -1,5 +1,3 @@
mod common;
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
use ide_host::{Host, HostConfig};
@@ -27,12 +25,18 @@ impl Harness {
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
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"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = sink.clone();
Arc::new(move |e| events.lock().unwrap().push(e))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.open_project("main", &root).unwrap();
Self { host, root, tmp, events }
@@ -110,16 +114,7 @@ impl Harness {
let discovery = ide_mcp::discovery_path(self.tmp.path());
let registry = Arc::new(Registry::new(self.host.clone()));
let runtime = tokio::runtime::Handle::current();
(
ide_mcp::McpServer::start_with(
registry,
Some(discovery.clone()),
&runtime,
ide_mcp::ServerOptions::default(),
)
.unwrap(),
discovery,
)
(ide_mcp::McpServer::start(registry, Some(discovery.clone()), &runtime).unwrap(), discovery)
}
}
impl Drop for Harness {
@@ -270,11 +265,10 @@ async fn project_path_argument_routes_to_another_open_project() {
std::fs::write(second.join("unique.txt"), "second project").unwrap();
h.host.open_project("second", &second).unwrap();
let discovery = ide_mcp::discovery_path(h.tmp.path());
let _server = ide_mcp::McpServer::start_with(
let _server = ide_mcp::McpServer::start(
Arc::new(Registry::new(h.host.clone())),
Some(discovery.clone()),
&tokio::runtime::Handle::current(),
ide_mcp::ServerOptions::default(),
)
.unwrap();
let request = json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","arguments":{
+13 -4
View File
@@ -2,11 +2,10 @@
//! credential store; `settings.toml` keeps only their names. A project's own servers keep
//! their values in the project's file, where the project shares them.
mod common;
use ide_agent::{McpKeyValue, McpScope, McpServer, McpServerInput};
use ide_core::NullSink;
use ide_core::settings::McpTransport;
use ide_host::Host;
use ide_host::{Host, HostConfig};
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -14,7 +13,17 @@ use std::sync::Arc;
const VALUE: &str = "mcp-value-0f3c9a";
fn host(dir: &Path) -> Arc<Host> {
Arc::new(Host::new(common::host_config(dir)))
Arc::new(Host::new(HostConfig {
config_dir: dir.join("config"),
data_dir: dir.join("data"),
local_data_dir: dir.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
fn project(tmp: &tempfile::TempDir) -> PathBuf {
+12 -4
View File
@@ -3,9 +3,7 @@
//! written in its source, so the UI can compute inheritance gutter markers without a
//! language server's type-hierarchy provider.
mod common;
use ide_host::{Host, ops};
use ide_host::{Host, HostConfig, ops};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -59,7 +57,17 @@ async fn open() -> Opened {
std::fs::write(dep.join("dep.py"), "class DepBase:\n pass\n").unwrap();
let app = tmp.path().join("app");
let host = Arc::new(Host::new(common::host_config(&app)));
let host = Arc::new(Host::new(HostConfig {
config_dir: app.join("config"),
data_dir: app.join("data"),
local_data_dir: app.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
ops::project::open(&host, WINDOW, &root).await.unwrap();
+13 -4
View File
@@ -1,9 +1,8 @@
//! Opening the project a window is already opening reuses it: racing opens (a double
//! click, a launch path and a restore) must not start a second index and language servers.
mod common;
use ide_host::Host;
use ide_core::NullSink;
use ide_host::{Host, HostConfig};
use std::sync::{Arc, Barrier};
#[test]
@@ -14,7 +13,17 @@ fn racing_opens_of_one_window_share_one_project() {
std::fs::write(root.join("src/Main.java"), "class Main {}\n").unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
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("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: runtime.handle().clone(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
let start = Arc::new(Barrier::new(4));
+8 -4
View File
@@ -1,6 +1,4 @@
//! Database and MCP calls through a real sandboxed API 1.4 component.
mod common;
use ide_core::{CancellationToken, IdeEvent, event::McpUiRequest};
use ide_host::{
Host, HostConfig,
@@ -39,12 +37,18 @@ impl Harness {
let events = Arc::new(Mutex::new(vec![]));
let out = events.clone();
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"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |w| {
let (w, out) = (w.to_owned(), out.clone());
Arc::new(move |e| out.lock().unwrap().push((w.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
std::fs::write(root.join("db.sqlite"), "").unwrap();
host.open_project("main", &root).unwrap();
+19 -4
View File
@@ -1,6 +1,4 @@
//! Real Wasm provider dispatch and the document-edit path used locally and over RPC.
mod common;
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, TextChange};
use ide_host::plugins::{Consent, HostWorkspace, PluginEvent, PluginHost, set_editor_providers};
use ide_host::{Host, HostConfig, ops};
@@ -241,11 +239,18 @@ type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
fn runtime_host(base: &Path, events: Events) -> Arc<Host> {
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |window| {
let (events, window) = (events.clone(), window.to_owned());
Arc::new(move |event: IdeEvent| events.lock().push((window.clone(), event)))
}),
..common::host_config(base)
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}))
}
@@ -429,7 +434,17 @@ async fn typing_is_debounced_versioned_and_scoped_to_document_project_and_window
/// A host with a project open: `problems` and `decorations` need a workspace.
fn harness(root: &Path) -> Arc<Host> {
let host = Arc::new(Host::new(HostConfig { local_data_dir: root.join("local"), ..common::host_config(root) }));
let host = Arc::new(Host::new(HostConfig {
config_dir: root.join("config"),
data_dir: root.join("data"),
local_data_dir: root.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.open_project("main", root).unwrap();
host
}
@@ -1,6 +1,4 @@
//! The API 1.4 fixture exercises every kind through the real component runtime and editor ops.
mod common;
use ide_core::{CancellationToken, Pos, Range, RequestId};
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers};
use ide_host::{Host, HostConfig, ops};
@@ -80,8 +78,17 @@ async fn editor_ops_merge_the_fixture_format_selection_and_execute_owned_command
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir(&root).unwrap();
let host =
Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) }));
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"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.open_project("main", &root).unwrap();
let p = plugins(tmp.path());
p.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
+8 -4
View File
@@ -1,6 +1,4 @@
//! Indexed names use the same preview/apply/undo commands as language-server refactorings.
mod common;
use ide_core::{IdeEvent, Pos, RequestId, error::ErrorKind};
use ide_host::{
Host, HostConfig, ops,
@@ -23,12 +21,18 @@ async fn indexed_usages_rename_preview_staleness_and_grouped_undo() {
let events = Arc::new(Mutex::new(vec![]));
let captured = events.clone();
let host = Host::new(HostConfig {
config_dir: root.join("config"),
data_dir: root.join("data"),
local_data_dir: root.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = captured.clone();
Arc::new(move |e| events.lock().push(e))
}),
local_data_dir: root.join("local"),
..common::host_config(&root)
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_light("main", &first).unwrap();
let doc = project.documents.open(&first).unwrap();
@@ -1,8 +1,6 @@
//! `[[contributes.serverCommands]]` (plugin API 1.9): a command a language server hands to the
//! client runs the plugin command that claims it. The fixture's command sends its argument
//! back to the server (`mock/ran`), through the real component runtime and `language-servers`.
mod common;
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers};
use ide_host::{Host, HostConfig, ops};
use ide_jsonrpc::{Handler, Peer};
@@ -90,8 +88,17 @@ async fn a_command_the_server_leaves_to_the_client_runs_the_plugin_that_claims_i
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir(&root).unwrap();
let host =
Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) }));
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"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
// Language servers start only in a trusted project.
host.set_project_trust(&root, true, false).await.unwrap();
host.open_project("main", &root).unwrap();
+8 -3
View File
@@ -1,5 +1,3 @@
mod common;
use ide_core::{CancellationToken, Diagnostic, Pos, Range, Severity};
use ide_host::plugins::{HostWorkspace, PluginWorkspace};
use ide_host::{Host, HostConfig};
@@ -18,8 +16,15 @@ impl Harness {
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).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"),
..common::host_config(tmp.path())
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.open_project("main", &root).unwrap();
host.open_project("second", &root).unwrap();
+8 -3
View File
@@ -5,8 +5,6 @@
//! `misbehave`) so tests need no wasm toolchain. Rebuild them with
//! `plugins/build.sh <dir>` after changing their source or `wit/`.
mod common;
use ide_core::error::ErrorKind;
use ide_core::ipc_path::to_ipc;
use ide_host::plugins::*;
@@ -5705,8 +5703,15 @@ async fn web_ptys_are_capped_across_windows_and_end_with_the_plugin() {
f.install(&sample("web-pty"));
let root = tempfile::tempdir().unwrap();
let host = Arc::new(Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: root.path().join("data"),
local_data_dir: root.path().join("local"),
..common::host_config(root.path())
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let spawn = |window: &str| {
f.host.spawn_web_pty(
+12 -4
View File
@@ -7,9 +7,7 @@
//! java, kotlin and python jobs):
//! `cargo test -p ide-host --test project_smoke -- --ignored`.
mod common;
use ide_host::{Host, ops};
use ide_host::{Host, HostConfig, ops};
use ide_index::SymbolFilter;
use ide_workspace::roots::RootKind;
use std::path::{Path, PathBuf};
@@ -55,7 +53,17 @@ async fn open(fixture: &str) -> Opened {
let root = dunce::canonicalize(tmp.path()).unwrap().join(fixture);
copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(fixture), &root);
let app = tmp.path().join("app");
let host = Arc::new(Host::new(common::host_config(&app)));
let host = Arc::new(Host::new(HostConfig {
config_dir: app.join("config"),
data_dir: app.join("data"),
local_data_dir: app.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
ops::project::open(&host, WINDOW, &root).await.unwrap();
Opened { host, root, _tmp: tmp }
Loaded 100 of 522 files, more files were not shown because too many files have changed in this diff. Show more