Compare commits

..
Author SHA1 Message Date
l0ng-ai 07653129fc fix(vcs): keep the log mounted while another Git tab is shown
Switching from Console or Worktrees back to Log rebuilt the commit list, graph,
branch tree and details, and reloaded the log, refs and branches. The last log
tab shown now stays mounted, hidden with content-visibility, so switching back
to it is a plain show.
2026-11-23 19:23:41 +08:00
289 changed files with 1456 additions and 10494 deletions

No files matched your search

Generated
+2 -5
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.3"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
dependencies = [
"time",
"version_check",
@@ -4253,7 +4253,6 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
@@ -4847,7 +4846,6 @@ dependencies = [
name = "ide-sdk"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
@@ -4859,7 +4857,6 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
+1 -4
View File
@@ -4234,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()),
-3
View File
@@ -536,9 +536,6 @@ pub enum AgentEntry {
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Images returned by the tool, kept separately from its truncated text.
#[serde(default)]
images: Vec<AgentImage>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
-30
View File
@@ -1007,16 +1007,11 @@ impl Session {
let mut updates = Vec::new();
let mut finished = None;
let mut read_title = false;
let mut refresh_usage = false;
{
let mut st = self.st.lock();
let st = &mut *st;
match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) {
Some("compact_boundary") => {
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
updates.extend(st.tr.on_message(&msg));
}
Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands"));
}
@@ -1120,31 +1115,6 @@ impl Session {
if read_title {
self.read_title();
}
if refresh_usage {
self.refresh_usage();
}
}
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
/// counts it (`get_context_usage`); until then the meter would show the count from before.
fn refresh_usage(self: &Arc<Self>) {
let me = self.clone();
tokio::spawn(async move {
let Some(proc) = me.st.lock().proc.clone() else { return };
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
Ok(usage) => usage,
Err(e) => {
tracing::debug!("reading claude context usage after compaction: {e}");
return;
}
};
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
let update = me.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = me.shim() {
shim.notify(vec![update]);
}
});
}
/// Sends the session's title once it has one: the one in its transcript, or else one
@@ -531,38 +531,6 @@ async fn sessions_without_a_title_get_one_generated() {
assert_eq!(request["request"]["persist"], true);
}
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
/// driver asks Claude Code, and the meter shows that instead of the count from before.
#[tokio::test(flavor = "multi_thread")]
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "get_context_usage"}})),
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
]);
let cli = replay_cli(processes);
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let session = h.new_session().await;
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut usage = Vec::new();
for _ in 0..100 {
usage = h.updates(&session, "usage_update");
if usage.last().is_some_and(|u| u["used"] == 4200) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() {
let r = replay("multi_turn").await;
@@ -1130,24 +1098,6 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
}
#[test]
fn a_compaction_replaces_the_context_usage() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
t.on_message(&assistant);
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
assert_eq!(t.on_result(&result)[0].update["used"], 950);
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
// The `/compact` turn's result reports what compaction left, not the count from before.
assert_eq!(t.on_result(&result)[0].update["used"], 120);
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
assert!(t.on_result(&result).is_empty());
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
@@ -144,22 +144,6 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t));
}
}
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) != Some("image") {
continue;
}
let Some(source) = block.get("source") else { continue };
if source.get("type").and_then(Value::as_str) != Some("base64") {
continue;
}
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
if !data.is_empty() && mime.starts_with("image/") {
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
}
}
}
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() {
out["content"] = Value::Array(content);
@@ -246,43 +230,6 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
}
#[test]
fn image_tool_results_keep_text_and_inline_images() {
let result = result_fields(
"Read",
&json!({"file_path": "/w/preview.png"}),
&json!({"content": [
{"type": "text", "text": "Preview ready"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
None,
);
assert_eq!(result["status"], "completed");
assert_eq!(
result["content"],
json!([
text("Preview ready"),
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
])
);
}
#[test]
fn failed_shell_tool_images_keep_fallback_error_text() {
let result = result_fields(
"Bash",
&json!({}),
&json!({"is_error": true, "content": [
{"type": "text", "text": "Preview command failed"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
Some(&json!({"stdout": "", "stderr": ""})),
);
assert_eq!(result["status"], "failed");
assert_eq!(result["content"][0], text("Preview command failed"));
assert_eq!(result["content"][1]["content"]["type"], "image");
}
#[test]
fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"});
@@ -458,13 +458,6 @@ impl Translator {
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
self.finish_child(&tool_use, stop, last.or(summary))
}
// Compaction replaced the conversation with its summary: the context now holds
// `post_tokens`. Without it the stale count must not come back with the result;
// the driver asks Claude Code instead (`Session::refresh_usage`).
Some("compact_boundary") => {
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
self.usage_update().into_iter().collect()
}
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => {
@@ -568,16 +561,6 @@ impl Translator {
self.usage_update().into_iter().collect()
}
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
}
Update { session: self.root.clone(), update }
}
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
-2
View File
@@ -1731,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());
}
+3 -42
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -84,7 +84,6 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
images: Vec::new(),
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
@@ -151,7 +150,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -174,20 +173,10 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if let Some(t) = content_text(item.get("content")) {
if !text.is_empty() {
text.push('\n');
}
@@ -214,9 +203,6 @@ impl Timeline {
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -453,31 +439,6 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
old.as_object_mut().unwrap().remove("images");
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
]});
t.apply(&update);
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+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
+8 -56
View File
@@ -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()
+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
-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,
}
-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)");
}
}
-2
View File
@@ -12,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;
@@ -38,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;
-4
View File
@@ -1396,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 {
@@ -1410,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 -2
View File
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
mut config: RunConfig,
config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,7 +544,6 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+61 -148
View File
@@ -1,6 +1,6 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
pub(super) mod workspace;
mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use crate::ops::Channel;
@@ -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};
@@ -184,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
@@ -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
@@ -1034,18 +952,16 @@ pub async fn build_run(
items: Vec::new(),
});
}
let mut launch_caches = Vec::new();
let plan = if let Some(id) = cmake {
launch_caches.push(cache.clone());
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
cmake_plan(&root, kind, &configs, &id)?
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = workspace::cache_at(&root, &cache, member);
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -1069,7 +985,6 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
launch_caches.push(cache.clone());
match compile::plan(
&root,
&model,
@@ -1092,9 +1007,7 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
+6 -23
View File
@@ -1,33 +1,12 @@
use super::*;
use std::path::PathBuf;
pub(in crate::ops) struct Scope {
pub(super) struct Scope {
pub root: PathBuf,
pub cache: PathBuf,
pub settings: Settings,
}
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let root = workspace
.as_ref()
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
.unwrap_or(&project.root);
Ok(Scope {
cache: cache_at(&project.root, &project.build_cache_dir(), root),
settings: if root == &project.root {
project.settings.effective()
} else {
project.settings.for_project(root).effective()
},
root: root.clone(),
})
}
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
}
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
}
@@ -40,7 +19,11 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: cache_at(window_root, cache, &root),
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
+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));
+2 -12
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)?;
@@ -228,15 +228,6 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -392,7 +383,6 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+62 -57
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::{load, with_profiles, workspace};
use super::build::load;
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,44 +46,37 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
let module = project.root.join(module);
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
launches.snapshots.lock().initialize();
let root = &scope.root;
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
project.java_launch_snapshots.lock().initialize();
let model = load(&project.root, &project.build_cache_dir(), &settings);
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
let prefer_maven = settings.languages.java.maven.delegate_build;
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(root, &scope.cache, &module),
cache::has_record(&project.root, &project.build_cache_dir(), &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, is_maven)
(model, external, delegated, prefer_maven, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -108,7 +101,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -117,8 +110,7 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
// The modules of the launches sharing this build also share its classpath probe.
@@ -126,8 +118,8 @@ pub(crate) async fn resolve_launch(
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = launches.snapshots.lock().build(
root,
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -140,7 +132,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -157,15 +149,24 @@ pub(crate) async fn resolve_launch(
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
Ok(_) => {}
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
@@ -176,7 +177,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -193,36 +194,28 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let settings = project.settings.effective();
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let model = load(&root, &cache, &settings);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -256,9 +249,9 @@ async fn resolve_launch_without_jdtls(
let build_ms = started.elapsed().as_millis();
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let project = project.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
Some(server) => {
info.project_root = server.classpath.project_root;
@@ -267,14 +260,26 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
if !is_maven_module(root, &model, &module) {
let is_maven = model
.maven
.as_ref()
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
if !is_maven {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let classpath = compile::module_classpath(
&project.root,
&model,
&module,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -282,8 +287,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -440,10 +445,10 @@ fn apply_library_classpath(
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
async fn build_members(
project: &std::sync::Arc<crate::Project>,
scope: &std::sync::Arc<workspace::Scope>,
model: &std::sync::Arc<BuildModel>,
module: &Path,
test: bool,
prefer_maven: bool,
waiting: &cache::WaitingGuard,
cancel: &CancellationToken,
) -> IdeResult<Vec<cache::Member>> {
@@ -451,11 +456,10 @@ async fn build_members(
if others.is_empty() {
return Ok(Vec::new());
}
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let joining = {
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -496,7 +500,8 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven = is_maven_module(root, model, &o.module);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
+8 -291
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())
}
}
@@ -151,30 +64,6 @@ pub(super) struct Member {
pub rebuild_on_jdt_errors: bool,
}
/// Launches share a build only within the same workspace project's cache.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
pub(in crate::ops) struct Launches {
pub waiting: Waiting,
pub snapshots: Mutex<Session>,
}
impl Sessions {
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
self.0
.lock()
.entry(cache.to_owned())
.or_insert_with(|| {
Arc::new(Launches {
waiting: Waiting::default(),
snapshots: Mutex::new(Session::new(cache.to_owned())),
})
})
.clone()
}
}
/// Java launches from their start until their build: one launch's Maven run also builds
/// the modules of launches still waiting (configurations started together, #3971).
#[derive(Default)]
@@ -367,23 +256,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 +293,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 +303,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 +698,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 +711,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 +732,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 +869,6 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -1086,132 +929,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();
+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());
+10 -27
View File
@@ -242,10 +242,7 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
if jvm && member.is_some() && config.cwd.is_none() {
config.cwd = Some(owner.into());
} else if config.extras.module.is_none() && !jvm {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
@@ -488,17 +485,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 +515,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()?;
+2 -121
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,9 +336,7 @@ pub async fn sdk_locate_tools(
.map_err(join_err)
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
/// `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
#[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,
@@ -389,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);
})
})
@@ -482,77 +436,6 @@ 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 {
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();
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();
@@ -666,6 +549,4 @@ ide_command::domain!(
sdk_python_packages,
sdk_python_pip,
sdk_python_project_interpreters,
sdk_python_sys_path,
sdk_python_user_path_problems,
);
+4 -5
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)"));
}
@@ -201,11 +201,10 @@ mod tests {
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());
}
@@ -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(),
}
}
+13 -10
View File
@@ -51,8 +51,10 @@ pub struct Project {
pub(crate) member_excludes: MemberExcludes,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Pending launches and retained snapshots, scoped to each workspace project.
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Superseded launch snapshots retained until this project session ends.
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
/// Java launches waiting for their build, which can share one Maven run.
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Database tool window: data sources and their connections.
@@ -200,12 +202,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).
@@ -644,7 +641,10 @@ impl Host {
detected_roots,
member_excludes,
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
@@ -891,7 +891,10 @@ impl Host {
detected_roots: Arc::default(),
member_excludes: Arc::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
+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")]
-70
View File
@@ -1,70 +0,0 @@
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
use ide_core::{IpcBytes, 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};
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(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: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
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());
}
-7
View File
@@ -74,13 +74,6 @@ async fn serves_projects_files_documents_search_and_runs() {
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
let scratch_path = base.join("data/scratches");
assert!(!scratch_path.exists());
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
assert!(scratch_path.is_dir());
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
+4 -8
View File
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1].into(), "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
assert!(!data_dir.join("terminal-images").exists());
let terminal = host
.terminals
@@ -41,15 +41,11 @@ async fn storage_requires_a_registered_terminal() {
)
.unwrap();
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3].into(), mime.into()).await.unwrap();
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
}
assert!(
ops::term::term_store_image(&host, terminal.id, vec![1].into(), "application/octet-stream".into())
.await
.is_err()
);
assert!(ops::term::term_store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::term_store_image(&host, terminal.id, vec![4].into(), "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
}
-101
View File
@@ -6,107 +6,6 @@ use std::{
time::Duration,
};
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn java_launch_builds_the_owning_workspace_reactor() {
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::{fs, os::unix::fs::PermissionsExt};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let config_dir = base.join("config");
let primary = base.join("primary");
let sibling = base.join("spring");
let nested = primary.join("nested");
let roots = [&primary, &sibling, &nested];
for (i, root) in roots.into_iter().enumerate() {
fs::create_dir_all(root.join("app")).unwrap();
fs::write(
root.join("pom.xml"),
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
)
.unwrap();
let wrapper = root.join("mvnw");
fs::write(
&wrapper,
r#"#!/bin/sh
set -eu
printf '%s\n' "$*" >> calls
mkdir -p app/target/classes
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
scope=runtime
for arg in "$@"; do
case "$arg" in
-Dmdep.includeScope=*) scope="${arg#*=}";;
esac
done
for arg in "$@"; do
case "$arg" in
-Dmdep.outputFile=*)
touch "app/$scope.jar"
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
esac
done
"#,
)
.unwrap();
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
SettingsStore::load(&config_dir, Some(root))
.set(
SettingsScope::Project,
"languages.java.maven.activeProfiles",
serde_json::json!(format!("member-{i}")),
)
.unwrap();
}
// Exercise the build-tool classpath fallback without starting an installed server.
let global = SettingsStore::load(&config_dir, None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(HostConfig {
config_dir,
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,
});
for root in roots {
host.trust.decide(root, true, false).unwrap();
}
host.open_project("main", &primary).unwrap();
for root in [&sibling, &nested] {
ops::project::attach_workspace(&host, "main", root).unwrap();
}
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
let temp = tempfile::tempdir().unwrap();
-19
View File
@@ -968,7 +968,6 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
_ => InlayKind::Other,
};
let tooltip = h.tooltip.map(tooltip_text);
let text_edits = conv.text_edits(path, h.text_edits.unwrap_or_default());
InlayHint {
position: conv.pos(path, h.position),
label,
@@ -977,7 +976,6 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
padding_right: h.padding_right.unwrap_or(false),
tooltip,
parts,
text_edits,
}
}
@@ -1591,23 +1589,6 @@ mod tests {
assert!(h.padding_left && !h.padding_right);
assert_eq!(h.parts.len(), 2);
assert!(h.parts.iter().all(|p| p.location.is_none()));
assert!(h.text_edits.is_empty());
}
#[test]
fn inlay_text_edits_carry_over() {
let conv = Conv::utf16();
let h: lsp::InlayHint = serde_json::from_value(json!({
"position": {"line": 2, "character": 5}, "label": ": Any", "kind": 1,
"textEdits": [
{"range": {"start": {"line": 2, "character": 5}, "end": {"line": 2, "character": 5}}, "newText": ": Any"},
{"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}, "newText": "from typing import Any\n"}
]
}))
.unwrap();
let h = inlay_hint(&conv, Path::new("/a"), h);
let edits: Vec<_> = h.text_edits.iter().map(|e| (e.range.start, e.new_text.as_str())).collect();
assert_eq!(edits, [(p(2, 5), ": Any"), (p(0, 0), "from typing import Any\n")]);
}
#[cfg(unix)]
+35 -62
View File
@@ -8,12 +8,10 @@
use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::ErrorKind;
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use specta::Type;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -648,8 +646,10 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Open editors may have cached empty tokens or inheritance results during the import.
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,9 +666,10 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
@@ -852,65 +853,37 @@ impl LspManager {
}
}
fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> {
/// Tells jdtls the build files of `uris` changed (`java/projectConfigurationsUpdate`),
/// so it re-imports their projects (e.g. after `~/.m2` gained an artifact it could
/// not resolve). Best-effort: skipped while jdtls is not already running.
pub async fn java_update_project_configs(&self, path: &Path, uris: Vec<String>) -> IdeResult<()> {
if uris.is_empty() {
return Ok(());
}
let java = LanguageId::new("java");
let mut targets = HashMap::new();
for file in files {
if let Some(server) = self.servers_for(&java, file).into_iter().find(|s| s.name == SERVER)
&& let Some(run) = server.running()
{
let (_, paths) = targets.entry(server.id).or_insert_with(|| (run, Vec::new()));
paths.push(file.as_path());
}
}
targets.into_values().collect()
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
return Ok(());
};
let Some(run) = server.running() else { return Ok(()) };
let identifiers: Vec<Value> = uris.iter().map(|u| json!({ "uri": u })).collect();
run.peer
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
.map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e))
}
/// Re-imports projects even when their build files did not change. Wait for
/// the Maven configuration job when a source refresh depends on its binaries.
pub async fn java_update_project_configs(
&self,
files: &[PathBuf],
wait: Option<&CancellationToken>,
) -> IdeResult<()> {
const UPDATE: &str = "openidea.java.updateProjectConfigurations";
let mut result = Ok(());
for (run, paths) in self.running_java_projects(files) {
let uris: Vec<_> = paths.iter().map(|path| crate::path_to_uri_string(path)).collect();
let supports_wait = run.caps.read().commands().iter().any(|command| command == UPDATE);
let updated = match wait.filter(|_| supports_wait) {
Some(cancel) => self
.jdtls_request(
paths[0],
"workspace/executeCommand",
json!({ "command": UPDATE, "arguments": uris }),
BUILD_TIMEOUT,
cancel,
)
.await
.map(|_| ()),
None => {
let identifiers: Vec<_> = uris.into_iter().map(|uri| json!({ "uri": uri })).collect();
run.peer
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
.map_err(|e| crate::rpc_err(SERVER, "java/projectConfigurationsUpdate", e))
}
};
result = result.and(updated);
/// Asks jdtls to re-read library archives replaced in place (`openidea.java.refreshArchives`):
/// a SNAPSHOT installed again keeps its path, and JDT would keep showing the classes it read
/// from the old archive. Best-effort: skipped while jdtls is not already running.
pub async fn java_refresh_archives(&self, path: &Path, archives: &[PathBuf]) -> IdeResult<()> {
let java = LanguageId::new("java");
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
return Ok(());
};
if server.running().is_none() {
return Ok(());
}
result
}
/// Asks jdtls to re-read library archives replaced in place.
pub async fn java_refresh_archives(&self, files: &[PathBuf], archives: &HashSet<PathBuf>) -> IdeResult<()> {
let mut archives: Vec<_> = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
archives.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
let mut result = Ok(());
for (_, paths) in self.running_java_projects(files) {
let refreshed = self.jdtls_command(paths[0], "openidea.java.refreshArchives", archives.clone()).await;
result = result.and(refreshed.map(|_| ()));
}
result
let archives = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
self.jdtls_command(path, "openidea.java.refreshArchives", archives).await.map(|_| ())
}
/// Pause autobuild before resolving the launch classpath. That query takes the
+1 -11
View File
@@ -280,7 +280,7 @@ pub struct LspManager {
virtual_docs: Mutex<HashMap<String, VirtualDocument>>,
/// Modification time of the archive behind a cached library class, so a jar
/// replaced in place (a SNAPSHOT installed again) is read again.
virtual_stamps: Mutex<HashMap<String, virtual_doc::ArchiveStamp>>,
virtual_stamps: Mutex<HashMap<String, std::time::SystemTime>>,
injections: injections::State,
/// Open notebooks by path. Locked before `docs` when both are.
notebooks: Mutex<HashMap<PathBuf, notebook::NotebookState>>,
@@ -3631,16 +3631,6 @@ impl LspManager {
archives
}
/// Drop cached text after JDT LS reopens the archives. A request could have
/// read the old attachment while the binary already had its new timestamp.
pub fn invalidate_library_archives(&self, archives: &std::collections::HashSet<PathBuf>) {
if !archives.is_empty() {
self.virtual_docs
.lock()
.retain(|uri, _| !virtual_doc::archive(uri).is_some_and(|archive| archives.contains(&archive)));
}
}
/// Contents of a virtual document, from the server that owns `uri`:
/// `workspace/textDocumentContent` (LSP 3.18) when the server serves the
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry
-2
View File
@@ -261,8 +261,6 @@ pub struct InlayHint {
/// The label's parts when the server split it (empty for a plain label);
/// their values concatenate to `label`.
pub parts: Vec<InlayLabelPart>,
/// The edits that turn the hint into code (an annotation and any import it needs).
pub text_edits: Vec<TextEdit>,
}
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
+5 -23
View File
@@ -192,22 +192,9 @@ pub(crate) fn archive(uri: &str) -> Option<std::path::PathBuf> {
}
}
/// Timestamps for a library document's archive and its replaceable SNAPSHOT attachment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ArchiveStamp {
archive: std::time::SystemTime,
sources: Option<std::time::SystemTime>,
}
pub(crate) fn archive_modified(uri: &str) -> Option<ArchiveStamp> {
let modified = |path: &std::path::Path| std::fs::metadata(path).and_then(|m| m.modified()).ok();
let archive = archive(uri)?;
let sources = archive
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.strip_suffix("-SNAPSHOT.jar"))
.and_then(|name| modified(&archive.with_file_name(format!("{name}-SNAPSHOT-sources.jar"))));
Some(ArchiveStamp { archive: modified(&archive)?, sources })
/// Modification time of the archive a `jar:` or `jdt:` library class comes from.
pub(crate) fn archive_modified(uri: &str) -> Option<std::time::SystemTime> {
std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok()
}
/// Whether `uri` is jdtls' class `package.name`, in any archive.
@@ -446,14 +433,9 @@ mod tests {
let uri = format!("jar:file://{}!/p/C.class", jar.display());
assert_eq!(archive(&uri), Some(jar.clone()));
let before = archive_modified(&uri).unwrap();
std::fs::write(dir.path().join("lib-1.0-SNAPSHOT-sources.jar"), b"PK").unwrap();
let with_sources = archive_modified(&uri).unwrap();
assert_eq!(before.archive, with_sources.archive);
assert_ne!(with_sources, before);
let file = std::fs::File::options().write(true).open(&jar).unwrap();
file.set_modified(before.archive + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(archive_modified(&uri), Some(with_sources));
file.set_modified(before + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(archive_modified(&uri), Some(before));
std::fs::remove_file(&jar).unwrap();
assert_eq!(archive_modified(&uri), None);
}
+7 -9
View File
@@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
async fn a_project_update_refreshes_java_semantic_tokens() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
@@ -3175,22 +3175,20 @@ async fn a_project_update_refreshes_java_tokens_and_inheritance() {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(refreshes().is_empty());
assert_eq!(refreshes(), 0);
// A later import may add tokens and implementation targets to open editors.
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
-2
View File
@@ -1587,13 +1587,11 @@ mod tests {
}
/// A pipe stand-in that counts the bytes taken from it.
#[cfg(unix)]
struct Counted<R> {
inner: R,
taken: Arc<AtomicUsize>,
}
#[cfg(unix)]
impl<R: Read> Read for Counted<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
-2
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dirs.workspace = true
dunce.workspace = true
ignore.workspace = true
@@ -17,7 +16,6 @@ ide-vfs.workspace = true
quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
specta.workspace = true
tempfile.workspace = true
toml.workspace = true
+9 -157
View File
@@ -66,10 +66,9 @@ pub fn ruff_configuration(root: &Path, configured: &str) -> IdeResult<Option<Pat
/// The project interpreter: the configured one, else a project virtualenv
/// (`.venv`, `venv`, …) or pixi environment (`.pixi/envs/<env>`) in the project
/// root, else the project's Pipenv environment, else the Python the project pins
/// for mise / asdf. A configured interpreter whose executable is gone (uninstalled,
/// moved) is skipped like PyCharm's "Invalid" SDKs, so runs fall back instead of
/// failing on a dead path.
/// root, else the Python the project pins for mise / asdf. A configured
/// interpreter whose executable is gone (uninstalled, moved) is skipped like
/// PyCharm's "Invalid" SDKs, so runs fall back instead of failing on a dead path.
/// `None` when the project interpreter is a run target's (see [`crate::container_python`]).
pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
if s.languages.python.run_target().is_some() {
@@ -81,72 +80,6 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_python(root))
}
/// An absolute or `~/` path from the settings; `None` for anything else.
pub fn absolute_setting_path(s: &str) -> Option<PathBuf> {
setting_path(Path::new(""), s).filter(|p| p.is_absolute())
}
/// Why a folder added to an interpreter's paths stays off the import path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum UserPathProblem {
/// Not an existing folder.
Missing,
/// Not absolute or `~/`, or it holds the separator of `PYTHONPATH`.
Invalid,
}
/// A folder added to an interpreter's paths (All Interpreters › Show Paths), as it goes on the
/// import path.
pub fn user_path(s: &str) -> Result<PathBuf, UserPathProblem> {
let path = absolute_setting_path(s).ok_or(UserPathProblem::Invalid)?;
// `PYTHONPATH` cannot hold a path with its separator in it: joining would fail every launch.
if std::env::join_paths([&path]).is_err() {
return Err(UserPathProblem::Invalid);
}
if !path.is_dir() {
return Err(UserPathProblem::Missing);
}
Ok(path)
}
/// Whether the settings key `key` names the interpreter `python`. Paths are compared as
/// written, not through symlinks: a virtualenv's `python` links to its base interpreter, and
/// the two are different interpreters.
fn names_interpreter(key: &str, python: &Path) -> bool {
let Some(key) = absolute_setting_path(key) else { return false };
if cfg!(windows) {
let fold = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase();
fold(&key) == fold(python)
} else {
key == python
}
}
/// The folders the user added to `python`'s paths that can be imported from.
pub fn interpreter_user_paths(python: &Path, s: &Settings) -> Vec<PathBuf> {
let mut out = Vec::new();
for (interpreter, paths) in &s.languages.python.interpreter_paths {
if !names_interpreter(interpreter, python) {
continue;
}
for path in paths.iter().filter_map(|p| user_path(p).ok()) {
if !out.contains(&path) {
out.push(path);
}
}
}
out
}
/// The interpreter a Python language server started for `server_root` analyses with: that
/// folder's own virtualenv unless an interpreter is configured, else the project interpreter.
pub fn python_server_interpreter(root: &Path, server_root: &Path, s: &Settings) -> Option<PathBuf> {
project_venv_python(server_root)
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
.or_else(|| python_interpreter(root, s))
}
/// An explicit project interpreter wins; otherwise use the closest virtualenv to the file.
pub fn python_interpreter_near(root: &Path, near: Option<&Path>, s: &Settings) -> Option<PathBuf> {
if s.languages.python.run_target().is_some() {
@@ -1227,7 +1160,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
let name = name.as_str();
if PYTHON_SERVERS.contains(&name) {
let python = python_server_interpreter(root, server_root, s);
let python = project_venv_python(server_root)
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
.or_else(|| python_interpreter(root, s));
if let Some(python) = python {
let p = python.to_string_lossy().into_owned();
match name {
@@ -1753,8 +1688,7 @@ fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &
}
}
/// Whether `cmd` is a Python executable by its name (`python`, `python3.12`, `python.exe`).
pub fn is_python_command(cmd: &str) -> bool {
fn is_python_command(cmd: &str) -> bool {
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = name.strip_suffix(".exe").unwrap_or(&name);
name == "python"
@@ -1967,17 +1901,10 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
"python" | "pytest" | "django-test" => {
let command = Path::new(&c.command);
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
let python = if own {
let cwd = root.join(c.cwd.as_deref().unwrap_or(Path::new("")));
Some(ide_core::project_roots::resolve(&cwd, command))
} else {
toolchain("python", &owner)
};
let python = toolchain("python", &owner);
// The member's explicit interpreter, else the inherited one, else the
// member's own venv / pin.
if !own && let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
if let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
let runner = PY_RUNNERS.contains(&c.command.as_str());
if (c.kind == "python" || c.kind == "django-test") && (runner || is_python_command(&c.command)) {
if runner && c.args.first().map(String::as_str) == Some("run") {
@@ -2322,81 +2249,6 @@ fn conda_activation(python: &Path, name: &str, conda_exe: Option<PathBuf>, on_pa
}
}
#[cfg(test)]
mod python_user_path_tests {
use super::*;
fn venv(dir: &Path) -> PathBuf {
let python = dir.join(".venv").join(crate::bin_dir()).join(crate::exe("python"));
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
std::fs::write(&python, "").unwrap();
std::fs::write(dir.join(".venv/pyvenv.cfg"), "").unwrap();
python
}
fn text(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn user_paths_follow_the_interpreter_and_skip_what_cannot_be_imported() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let (lib, other) = (root.join("shared"), root.join("other"));
std::fs::create_dir_all(&lib).unwrap();
std::fs::create_dir_all(&other).unwrap();
let python = venv(&root);
let other_python = root.join("other-python");
let mut s = Settings::default();
s.languages.python.interpreter_paths = [
// Gone, duplicated, relative and a file: none of them reach the import path.
(text(&python), vec![text(&lib), text(&root.join("gone")), text(&lib), "relative".into(), text(&python)]),
(text(&other_python), vec![text(&other)]),
]
.into();
assert_eq!(interpreter_user_paths(&python, &s), std::slice::from_ref(&lib));
assert_eq!(interpreter_user_paths(&other_python, &s), [other]);
assert!(interpreter_user_paths(&root.join("unknown-python"), &s).is_empty());
}
#[test]
fn a_folder_that_stays_off_the_import_path_says_why() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
assert_eq!(user_path(&text(&root)), Ok(root.clone()));
assert_eq!(user_path(&text(&root.join("gone"))), Err(UserPathProblem::Missing));
assert_eq!(user_path("relative/dir"), Err(UserPathProblem::Invalid));
assert_eq!(user_path(" "), Err(UserPathProblem::Invalid));
// One entry with the separator in it would make `PYTHONPATH` impossible to build.
#[cfg(unix)]
{
let odd = root.join("libs:v2");
std::fs::create_dir(&odd).unwrap();
assert_eq!(user_path(&text(&odd)), Err(UserPathProblem::Invalid));
let mut s = Settings::default();
s.languages.python.interpreter_paths = [("/bin/python".into(), vec![text(&odd), text(&root)])].into();
assert_eq!(interpreter_user_paths(Path::new("/bin/python"), &s), [root]);
}
}
#[test]
fn a_language_server_takes_the_interpreter_of_its_own_folder() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let sub = root.join("services/api");
let (python, sub_python) = (venv(&root), venv(&sub));
let mut s = Settings::default();
assert_eq!(python_server_interpreter(&root, &root, &s), Some(python.clone()));
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(sub_python));
// A configured interpreter is the one every server of the project uses.
s.languages.python.interpreter = text(&python);
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(python));
s.languages.python.interpreter = "target:docker".into();
assert_eq!(python_server_interpreter(&root, &root, &s), None);
}
}
#[cfg(test)]
mod java_compiler_tests {
use super::*;
+9 -254
View File
@@ -2,10 +2,10 @@
use crate::exec::{executables_in, query, search_path, which};
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
use ide_core::process::{host_var_os, host_var_os_in};
use ide_core::process::host_var_os;
use ide_core::version_managers::{self, Tool};
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -55,7 +55,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };
let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };
let at = sdks.iter().take_while(|s| matches!(s.source.as_str(), "venv" | "pipenv")).count().min(i);
let at = sdks.iter().take_while(|s| s.source == "venv").count().min(i);
let sdk = sdks.remove(i);
sdks.insert(at, sdk);
}
@@ -81,8 +81,7 @@ fn dedupe_by_real_path(paths: Vec<(PathBuf, &'static str)>) -> Vec<(PathBuf, &'s
/// Project-local virtualenv directories checked by auto-detection, in order.
pub(crate) const PROJECT_VENVS: [&str; 4] = [".venv", "venv", "env", ".env"];
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment, else the
/// interpreter of the project's Pipenv environment.
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment.
pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
PROJECT_VENVS
.iter()
@@ -95,101 +94,6 @@ pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
[env.join(exe("python")), env.join("bin").join(exe("python"))].into_iter().find(|p| p.is_file())
})
})
.or_else(|| pipenv_env_python(root))
}
/// Pipenv's active workon home first, followed by the other conventional location.
fn workon_homes(home: &Path, env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
let data = var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
let mut defaults = [home.join(".virtualenvs"), data.join("virtualenvs")];
if !cfg!(windows) {
defaults.swap(0, 1);
}
var("WORKON_HOME").into_iter().chain(defaults).collect()
}
/// How many folders pipenv searches for a `Pipfile`, the project's own and those above it
/// (`PIPENV_MAX_DEPTH`, 10 by default).
const PIPFILE_MAX_DEPTH: usize = 10;
/// The folder of the `Pipfile` pipenv uses for a project opened at `root`: the nearest one in
/// `root` or the folders above it, searched as pipenv does.
pub(crate) fn pipfile_dir(root: &Path) -> Option<PathBuf> {
root.ancestors().take(PIPFILE_MAX_DEPTH).find(|dir| dir.join("Pipfile").is_file()).map(Path::to_path_buf)
}
/// The folder name pipenv gives the environment of the project whose `Pipfile` is in `dir`
/// (`venv_locator._get_virtualenv_hash`): the folder's name with shell-special characters
/// replaced and cut to 42 characters, `-`, and the URL-safe base64 of the first 6 bytes of
/// the SHA-256 of the `Pipfile` path.
pub(crate) fn pipenv_env_name(dir: &Path) -> String {
use base64::Engine;
use sha2::Digest;
let name: String = (dir.file_name().unwrap_or_default().to_string_lossy().chars())
.map(|c| if " &$`!*@\"()[]\\\r\n\t".contains(c) { '_' } else { c })
.take(42)
.collect();
let digest = sha2::Sha256::digest(dir.join("Pipfile").to_string_lossy().as_bytes());
format!("{name}-{}", base64::engine::general_purpose::URL_SAFE.encode(&digest[..6]))
}
/// The project a Pipenv virtualenv belongs to. Pipenv records the project folder in
/// `<venv>/.project`; virtualenvwrapper does too, so the environment must also carry the
/// name pipenv derives from that project's `Pipfile`, or be the project's own `.venv`.
fn pipenv_project(venv: &Path) -> Option<PathBuf> {
let project = PathBuf::from(std::fs::read_to_string(venv.join(".project")).ok()?.trim());
let named = venv.file_name().is_some_and(|name| *name.to_string_lossy() == pipenv_env_name(&project));
(project.is_absolute() && project.join("Pipfile").is_file() && (named || venv == project.join(".venv")))
.then_some(project)
}
/// The interpreter of the Pipenv environment `pipenv --venv` names for the project at `root`,
/// found without starting pipenv, which takes about a second.
fn pipenv_env_python(root: &Path) -> Option<PathBuf> {
let dir = pipfile_dir(root)?;
let var = |key: &str| host_var_os_in(&dir, key);
let homes = home_dir().map(|home| workon_homes(&home, var)).unwrap_or_default();
pipenv_env_in(&dir, &homes, var("PIPENV_CUSTOM_VENV_NAME").as_deref())
}
/// A project-local environment, an explicitly selected path or name, or Pipenv's hashed name.
fn pipenv_env_in(dir: &Path, homes: &[PathBuf], custom_name: Option<&OsStr>) -> Option<PathBuf> {
let dot_venv = dir.join(".venv");
let python_in = |env: &Path| {
let python = env.join(bin_dir()).join(exe("python"));
(env.join("pyvenv.cfg").is_file() && python.is_file()).then_some(python)
};
if dot_venv.is_file() {
let pointer = std::fs::read_to_string(&dot_venv).ok()?;
let pointer = pointer.trim();
if !pointer.is_empty() {
let path = Path::new(pointer);
let components = path.components().filter(|part| *part != std::path::Component::CurDir);
let home = if components.count() > 1 || pointer.ends_with(std::path::is_separator) {
dir.join(path)
} else {
homes.first()?.join(path)
};
return python_in(&dunce::canonicalize(home).ok()?);
}
}
if let Some(python) = python_in(&dot_venv) {
return Some(python);
}
if let Some(name) = custom_name.filter(|name| !name.is_empty()) {
let path = Path::new(name);
return if path.is_absolute() { python_in(path) } else { python_in(&homes.first()?.join(path)) };
}
// Pipenv hashes the path it was started in, which may or may not have its symlinks resolved.
let mut names: Vec<String> = [Some(dir.to_path_buf()), dunce::canonicalize(dir).ok()]
.into_iter()
.flatten()
.map(|d| pipenv_env_name(&d))
.collect();
names.dedup();
homes.iter().flat_map(|home| names.iter().map(move |name| home.join(name))).find_map(|home| python_in(&home))
}
/// `/usr/bin/python3` on macOS is a stub that opens an installer dialog when
@@ -319,22 +223,15 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
found.push((python, "pixi"));
}
}
if let Some(python) = pipenv_env_python(root) {
// The selected Pipenv environment may already be a project-local virtualenv.
if let Some((_, source)) = found.iter_mut().find(|(path, _)| *path == python) {
*source = "pipenv";
} else {
found.push((python, "pipenv"));
}
}
}
if let Ok(venv) = std::env::var("VIRTUAL_ENV") {
found.push((Path::new(&venv).join(bin_dir()).join(exe("python")), "venv"));
}
if let Some(home) = home_dir() {
// Virtualenvs managed by virtualenvwrapper / pipenv / poetry.
let env_dirs = [".virtualenvs", ".local/share/virtualenvs"].map(|d| home.join(d));
let var = |key: &str| host_var_os(key);
for dir in workon_homes(&home, var).into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
for dir in env_dirs.into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
for env in subdirs(&dir) {
found.push((env.join(bin_dir()).join(exe("python")), "venv"));
}
@@ -436,11 +333,7 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
seen_real.insert(p.canonicalize().unwrap_or_else(|_| p.clone()))
}
})
.map(
|(p, source)| {
if venv_of(&p).is_some() && !matches!(source, "conda" | "pipenv") { (p, "venv") } else { (p, source) }
},
)
.map(|(p, source)| if venv_of(&p).is_some() && source != "conda" { (p, "venv") } else { (p, source) })
.collect();
par_map(&candidates, |(path, source)| python_sdk(path, source, root))
}
@@ -464,18 +357,7 @@ pub fn python_interpreter_sdk(path: &Path, root: Option<&Path>) -> Option<Sdk> {
{
return None;
}
let source = if let Some(home) = venv_of(&path) {
let pipenv_home = root.and_then(pipenv_env_python).and_then(|p| venv_of(&p));
if pipenv_home.is_some_and(|p| dunce::canonicalize(p).is_ok_and(|p| dunce::canonicalize(&home).ok() == Some(p)))
{
"pipenv"
} else {
"venv"
}
} else {
"system"
};
Some(python_sdk_with_version(&path, source, root, version))
Some(python_sdk_with_version(&path, if venv_of(&path).is_some() { "venv" } else { "system" }, root, version))
}
pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Option<Sdk> {
@@ -488,17 +370,7 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, version: String) -> Sdk {
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
let venv = venv_of(path);
let pipenv = if source == "pipenv" {
root.and_then(pipfile_dir)
} else {
venv.as_deref().filter(|_| source == "venv").and_then(pipenv_project)
};
let source = if pipenv.is_some() { "pipenv" } else { source };
let label = match (&venv, source) {
(_, "pipenv") => {
let project = pipenv.as_deref().and_then(Path::file_name).unwrap_or_default().to_string_lossy();
format!("Python {short} (Pipenv: {project})")
}
(Some(home), _) => {
let dir = home.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// `.venv` inside a project reads better as the folder that holds it (the project,
@@ -561,7 +433,7 @@ fn pixi_env_name(python: &Path) -> Option<String> {
pixi_env_home(python)?.file_name().map(|n| n.to_string_lossy().into_owned())
}
pub(crate) fn pyvenv_version(python: &Path) -> Option<String> {
fn pyvenv_version(python: &Path) -> Option<String> {
let cfg = std::fs::read_to_string(venv_of(python)?.join("pyvenv.cfg")).ok()?;
cfg.lines().find_map(|l| {
let (k, v) = l.split_once('=')?;
@@ -1247,106 +1119,6 @@ mod pixi_tests {
}
}
#[cfg(test)]
mod pipenv_tests {
use super::*;
fn venv(home: &Path, project: &Path) -> PathBuf {
let python = home.join(bin_dir()).join(exe("python"));
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
std::fs::write(&python, "").unwrap();
std::fs::write(home.join("pyvenv.cfg"), "version = 3.12.1\n").unwrap();
std::fs::write(home.join(".project"), project.to_string_lossy().as_bytes()).unwrap();
python
}
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
}
#[test]
fn the_environment_named_for_the_pipfile_is_the_projects() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let (shop, blog) = (tmp.join("shop"), tmp.join("blog"));
for project in [&shop, &blog] {
std::fs::create_dir_all(project.join("src/pkg")).unwrap();
std::fs::write(project.join("Pipfile"), "").unwrap();
}
let homes = [tmp.join("missing"), tmp.join(".virtualenvs"), tmp.join("workon")];
// virtualenvwrapper's `mkproject` writes `.project` too: its environment is not pipenv's,
// though it comes first and its project has a Pipfile.
let wrapper = venv(&homes[1].join("shop"), &shop);
let shop_python = venv(&homes[2].join(pipenv_env_name(&shop)), &shop);
let blog_python = venv(&homes[2].join(pipenv_env_name(&blog)), &blog);
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(shop_python.clone()));
assert_eq!(pipenv_env_in(&blog, &homes, None), Some(blog_python));
// Opened in a sub-folder, the project is the one pipenv finds above it.
assert_eq!(pipfile_dir(&shop.join("src/pkg")), Some(shop.clone()));
assert_eq!(pipfile_dir(&tmp), None);
let sdk = python_sdk(&shop_python, "venv", Some(&blog)).unwrap();
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
assert_eq!(
sdk.home.as_deref().map(|h| h.to_path_buf()),
shop_python.parent().unwrap().parent().map(Into::into)
);
let sdk = python_sdk(&wrapper, "venv", None).unwrap();
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (shop)", "venv"));
}
#[test]
fn a_pipenv_environment_inside_the_project_is_named_as_pipenvs() {
let tmp = tempfile::tempdir().unwrap();
let shop = tmp.path().join("shop");
std::fs::create_dir_all(&shop).unwrap();
std::fs::write(shop.join("Pipfile"), "").unwrap();
let python = venv(&shop.join(".venv"), &shop);
assert_eq!(project_venv_python(&shop), Some(python.clone()));
assert_eq!(pipenv_env_in(&shop, &[], None), Some(python.clone()));
assert_eq!(python_sdk(&python, "venv", Some(&shop)).unwrap().name, "Python 3.12 (Pipenv: shop)");
}
#[test]
fn pipenv_uses_the_explicit_environment_without_a_project_marker() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let shop = tmp.join("shop");
let subdir = shop.join("src");
std::fs::create_dir_all(&subdir).unwrap();
std::fs::write(shop.join("Pipfile"), "").unwrap();
let homes = [tmp.join("workon")];
venv(&homes[0].join(pipenv_env_name(&shop)), &shop);
let named = homes[0].join("named");
let named_python = venv(&named, &shop);
std::fs::remove_file(named.join(".project")).unwrap();
let outside = tmp.join("outside");
let external_python = venv(&outside, &shop);
std::fs::remove_file(outside.join(".project")).unwrap();
let marker = shop.join(".venv");
let name = Some(OsStr::new("named"));
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(named_python.clone()));
assert_eq!(pipenv_env_in(&shop, &[], Some(outside.as_os_str())), Some(external_python.clone()));
for pointer in ["../outside".into(), outside.to_string_lossy()] {
std::fs::write(&marker, format!(" {pointer}\n")).unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(external_python.clone()));
assert_eq!(project_venv_python(&subdir), Some(external_python.clone()));
}
let sdk = detect(SdkKind::Python, Some(&subdir)).into_iter().next().unwrap();
assert_eq!(sdk.path.to_path_buf(), external_python);
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
std::fs::write(&marker, "named").unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(named_python));
std::fs::write(&marker, "missing").unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, name), None);
}
}
#[cfg(test)]
mod conda_tests {
use super::*;
@@ -1489,23 +1261,6 @@ mod env_manager_dir_tests {
);
}
#[test]
fn workon_homes_follow_pipenv_and_virtualenvwrapper() {
let home = Path::new("/home/me");
let order = |xdg: PathBuf| {
let wrapper = home.join(".virtualenvs");
if cfg!(windows) { [wrapper, xdg] } else { [xdg, wrapper] }
};
let defaults = order(home.join(".local/share/virtualenvs"));
assert_eq!(workon_homes(home, env(&[("WORKON_HOME", "")])), defaults);
assert_eq!(
workon_homes(home, env(&[("WORKON_HOME", "/envs"), ("XDG_DATA_HOME", "/xdg/data")])),
std::iter::once(PathBuf::from("/envs"))
.chain(order(PathBuf::from("/xdg/data/virtualenvs")))
.collect::<Vec<_>>()
);
}
#[test]
fn poetry_overrides_come_first_and_empty_ones_are_ignored() {
let home = Path::new("/home/me");
+1 -1
View File
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.18.0",
"1.17.0",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+3 -83
View File
@@ -384,33 +384,15 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
let structure = &s.project_structure;
let folders: Vec<PathBuf> = [root, project]
.into_iter()
.map(Path::to_path_buf)
.chain(structure.content_roots.iter().chain(&structure.dependencies).map(|p| PathBuf::from(p.trim())))
.collect();
let user = outside_folders(crate::apply::interpreter_user_paths(&python, s), &folders);
let key = std::iter::once(&python).chain(&user).map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n");
cached_cancellable(root, "python", key, &files, cancel, || {
let mut group = python_libraries(&python, Some(root));
if let Some(group) = &mut group {
group.roots.extend(library_roots(user));
}
group.into_iter().collect()
cached_cancellable(root, "python", python.display().to_string(), &files, cancel, || {
python_libraries(&python, Some(root)).into_iter().collect()
})
}
/// `paths` without the ones inside, or around, one of the project's `folders`: a library root
/// opens its files read-only, and the project's own code stays editable.
fn outside_folders(paths: Vec<PathBuf>, folders: &[PathBuf]) -> Vec<PathBuf> {
paths.into_iter().filter(|p| !folders.iter().any(|f| p.starts_with(f) || f.starts_with(p))).collect()
}
/// Standard library and site-packages folders of a Python interpreter.
pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGroup> {
// In a neutral directory: the working directory comes first on `sys.path` for `-c`.
@@ -420,16 +402,6 @@ pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGro
group(name, "python", library_roots(parse_python_paths(&out)))
}
/// `sys.path` of `python` started on its own; `None` when it cannot run or was cancelled.
pub fn python_sys_path(python: &Path, cancel: &CancellationToken) -> Option<Vec<PathBuf>> {
// In a neutral directory and without the IDE's own `PYTHONPATH`: neither belongs to the
// interpreter. `-c` puts `''` first for the working directory; a hook may add non-strings.
let dir = crate::python::neutral_dir()?;
let script = "import json,sys;print(json.dumps([p for p in sys.path if isinstance(p,str) and p]))";
let out = query_in_cancellable(python, &["-c", script], dir.path(), &[("PYTHONPATH", "")], QUERY_TIMEOUT, cancel)?;
Some(parse_python_paths(&out))
}
pub(crate) fn parse_python_paths(out: &str) -> Vec<PathBuf> {
let json = out.lines().rev().find(|l| l.trim_start().starts_with('[')).unwrap_or("[]");
serde_json::from_str::<Vec<Option<String>>>(json)
@@ -1118,58 +1090,6 @@ fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
}
}
#[cfg(test)]
mod python_tests {
use super::*;
#[test]
fn user_paths_inside_or_around_the_project_are_not_library_roots() {
let folders = [PathBuf::from("/work/app"), PathBuf::from("/work/attached")];
let paths = ["/work/app/stubs", "/work/app", "/work", "/work/attached/src", "/shared/lib", "/work/apple"];
assert_eq!(
outside_folders(paths.iter().map(PathBuf::from).collect(), &folders),
[PathBuf::from("/shared/lib"), PathBuf::from("/work/apple")]
);
}
#[test]
fn external_libraries_list_user_paths_outside_the_project_only() {
let Some(python) = crate::exec::which("python3") else { return };
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().canonicalize().unwrap();
let (root, attached, shared) = (base.join("app"), base.join("attached"), base.join("shared"));
for dir in [&root.join("stubs"), &attached.join("src"), &shared] {
std::fs::create_dir_all(dir).unwrap();
}
let text = |p: &Path| p.to_string_lossy().into_owned();
let mut s = Settings::default();
s.languages.python.interpreter = text(&python);
s.project_structure.dependencies = vec![text(&attached)];
s.languages.python.interpreter_paths =
[(text(&python), vec![text(&root.join("stubs")), text(&attached.join("src")), text(&base), text(&shared)])]
.into();
let groups = python_groups(&root, &root, &s, &CancellationToken::new());
let roots: Vec<&Path> = groups.iter().flat_map(|g| &g.roots).map(|r| Path::new(&*r.path)).collect();
assert!(roots.contains(&shared.as_path()), "{roots:?}");
// The project's own folders stay editable: a library root opens read-only.
for inside in [root.join("stubs"), attached.join("src"), base.clone()] {
assert!(!roots.contains(&inside.as_path()), "{roots:?}");
}
}
#[test]
fn sys_path_is_the_interpreters_own_and_can_be_cancelled() {
let Some(python) = crate::exec::which("python3") else { return };
let paths = python_sys_path(&python, &CancellationToken::new()).unwrap();
// Site hooks can add non-filesystem entries for editable packages.
assert!(paths.iter().any(|p| p.is_absolute()), "{paths:?}");
let cancelled = CancellationToken::new();
cancelled.cancel();
assert_eq!(python_sys_path(&python, &cancelled), None);
assert_eq!(python_sys_path(Path::new("/no/such/python"), &CancellationToken::new()), None);
}
}
#[cfg(test)]
mod go_cache_tests {
use super::*;
+2 -81
View File
@@ -28,22 +28,18 @@ pub enum VenvTool {
Poetry,
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH).
Conda,
/// `pipenv --python <base>` in the project (pipenv must be on PATH).
Pipenv,
}
/// Creates a virtualenv at `location` with `tool` and returns its interpreter.
/// `base` is the interpreter uv / venv build on, or the one poetry's / pipenv's env uses.
/// `install` also installs the packages the project declares, for the tool that reads them (pipenv).
/// `base` is the interpreter uv / venv build on, or the one poetry's env uses.
pub fn create_venv(
tool: VenvTool,
base: &Path,
location: &Path,
install: bool,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
create_venv_with(tool, base, location, install, which, cancel, on_line)
create_venv_with(tool, base, location, which, cancel, on_line)
}
/// [`create_venv`] with the tool lookup injectable (tests fake `uv` / `poetry`).
@@ -51,7 +47,6 @@ pub(crate) fn create_venv_with(
tool: VenvTool,
base: &Path,
location: &Path,
install: bool,
which: impl Fn(&str) -> Option<PathBuf>,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
@@ -91,7 +86,6 @@ pub(crate) fn create_venv_with(
}
VenvTool::Poetry => create_poetry_env(base, location, &which, cancel, on_line),
VenvTool::Conda => create_conda_env(base, location, &which, cancel, on_line),
VenvTool::Pipenv => create_pipenv_env(base, location, install, &which, cancel, on_line),
}
}
@@ -123,79 +117,6 @@ fn create_poetry_env(
.map(PathBuf::from)
.ok_or_else(|| IdeError::internal("poetry created no environment".to_owned()))?;
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "pipenv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// An environment that already exists is reused rather than rebuilt: the tools replace one
/// built on another Python without asking, losing its packages. If `base` is another Python
/// version than the environment's, nothing is changed and the error says how to go on.
fn reuse_existing_env(home: &Path, base: &Path, remove: &str) -> IdeResult<()> {
let short = |version: &str| version.split('.').take(2).collect::<Vec<_>>().join(".");
let existing = crate::discover::pyvenv_version(&home.join(bin_dir()).join(exe("python")));
let wanted = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
match (existing.as_deref().map(short), wanted.as_deref().map(short)) {
(Some(existing), Some(wanted)) if existing != wanted => Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!(
"{} already holds a Python {existing} environment, not Python {wanted} like the base interpreter. \
Select it under Existing environment, or remove it first with `{remove}`.",
home.display()
),
)),
_ => Ok(()),
}
}
/// Pipenv's environment for the project (`location` is a hint inside it, as for Poetry: pipenv
/// keeps its envs under `WORKON_HOME`). `pipenv --python <base>` creates it when `pipenv --venv`
/// finds none, writing a `Pipfile` (from `requirements.txt` if there is one) when the project
/// has none. `install` then runs `pipenv install --dev` for the packages of the `Pipfile`.
fn create_pipenv_env(
base: &Path,
location: &Path,
install: bool,
which: &dyn Fn(&str) -> Option<PathBuf>,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
let pipenv = which("pipenv")
.ok_or_else(|| IdeError::unavailable("Pipenv is not installed (install it from https://pipenv.pypa.io)"))?;
let project = location
.parent()
.filter(|p| p.is_dir())
.ok_or_else(|| IdeError::invalid("Pipenv environments need an open project directory"))?;
// No prompts or spinner, and the project's own environment even when the IDE was
// started from inside another virtualenv.
const ENV: [(&str, &str); 3] = [("PIPENV_YES", "1"), ("PIPENV_NOSPIN", "1"), ("PIPENV_IGNORE_VIRTUALENVS", "1")];
let env = ENV.map(|(k, v)| (k.to_owned(), v.to_owned()));
let venv = || {
query_in_cancellable(&pipenv, &["--venv"], project, &ENV, Duration::from_secs(30), cancel)
.map(PathBuf::from)
.filter(|home| home.join("pyvenv.cfg").is_file())
};
match venv() {
Some(home) => reuse_existing_env(&home, base, "pipenv --rm")?,
None => {
let args = ["--python".to_owned(), base.to_string_lossy().into_owned()];
stream(&pipenv, &args, Some(project), &env, cancel, on_line)?;
}
}
// Decided after creation: pipenv may just have written the `Pipfile`, or found one above the project.
let pipfile_dir = crate::discover::pipfile_dir(project);
if install && pipfile_dir.is_some() {
stream(&pipenv, &["install".to_owned(), "--dev".to_owned()], Some(project), &env, cancel, on_line)?;
}
let home = venv().ok_or_else(|| IdeError::internal("pipenv created no environment".to_owned()))?;
// Pipenv records the project only when it creates the environment: one it reuses after an
// interrupted creation has no `.project`, and detection would not know whose it is.
let record = home.join(".project");
if !record.exists() {
let owner = pipfile_dir.as_deref().unwrap_or(project);
let _ = std::fs::write(record, owner.to_string_lossy().as_bytes());
}
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "venv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
-101
View File
@@ -578,31 +578,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
assert_eq!(configs[6].args, ["manage.py", "test", "polls"]);
}
#[test]
fn saved_python_configs_keep_their_explicit_interpreter() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let default = fake_venv(root, ".venv");
let override_python = fake_venv(&root.join("member"), ".override");
let relative_python = override_python.strip_prefix(root.join("member")).unwrap();
let mut settings = Settings::default();
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
for command in [&override_python, relative_python] {
for kind in ["python", "pytest", "django-test"] {
let command = command.to_string_lossy();
let mut config = run(kind, &command, &["main.py"]);
config.detected = false;
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
}
}
#[test]
fn npm_config_runs_on_its_own_node_interpreter() {
if cfg!(windows) {
@@ -1510,7 +1485,6 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Uv,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1521,7 +1495,6 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Poetry,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1532,24 +1505,12 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Conda,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
)
.unwrap_err();
assert!(conda.message.contains("conda is not installed"), "{}", conda.message);
let pipenv = crate::python::create_venv_with(
crate::python::VenvTool::Pipenv,
&base,
&location,
true,
none,
&Default::default(),
&|_| {},
)
.unwrap_err();
assert!(pipenv.message.contains("Pipenv is not installed"), "{}", pipenv.message);
// An existing environment is refused before any tool runs.
std::fs::create_dir_all(&location).unwrap();
std::fs::write(location.join("pyvenv.cfg"), "home = /python").unwrap();
@@ -1557,7 +1518,6 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Uv,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1580,7 +1540,6 @@ fn an_existing_conda_environment_is_not_recreated() {
crate::python::VenvTool::Conda,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1631,7 +1590,6 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
crate::python::VenvTool::Conda,
&base,
Path::new("ds"),
false,
which,
&Default::default(),
&|_| {},
@@ -1643,65 +1601,6 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
assert!(again.message.contains("named ds already exists"), "{}", again.message);
}
#[test]
#[cfg(unix)]
fn pipenv_creates_the_projects_environment_and_never_replaces_one() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let project = tmp.join("shop");
let home = tmp.join("workon").join(crate::discover::pipenv_env_name(&project));
std::fs::create_dir_all(&project).unwrap();
let python = tmp.join("python");
std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap();
std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
// `--venv` fails until the environment exists; `--python` creates it outside the project,
// records the project in `.project` and writes a Pipfile.
let pipenv = tmp.join("pipenv");
std::fs::write(
&pipenv,
format!(
"#!/bin/sh\nhome='{home}'\nif [ \"$1\" = --venv ]; then [ -f \"$home/pyvenv.cfg\" ] || exit 1; echo \"$home\"; exit 0; fi\n\
[ \"$PIPENV_YES\" = 1 ] || exit 3\necho \"$@\" >> calls\n[ \"$1\" = --python ] || exit 0\n\
mkdir -p \"$home/bin\"\ncp '{python}' \"$home/bin/python\"\necho 'version = 3.12.1' > \"$home/pyvenv.cfg\"\n\
touch Pipfile\npwd -P > \"$home/.project\"\n",
home = home.display(),
python = python.display()
),
)
.unwrap();
std::fs::set_permissions(&pipenv, std::fs::Permissions::from_mode(0o755)).unwrap();
let which = |tool: &str| (tool == "pipenv").then(|| pipenv.clone());
let create = |install: bool| {
crate::python::create_venv_with(
crate::python::VenvTool::Pipenv,
&python,
&project.join(".venv"),
install,
which,
&Default::default(),
&|_| {},
)
};
let calls = || std::fs::read_to_string(project.join("calls")).unwrap_or_default();
// The project had no Pipfile: the one pipenv writes is installed from, as asked.
let sdk = create(true).unwrap();
assert_eq!(&*sdk.path, home.join("bin/python").as_path());
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
assert_eq!(calls(), format!("--python {}\ninstall --dev\n", python.display()));
// An existing environment is reused, never created again with `--python` (which replaces one
// of another version); one pipenv left without `.project` is still the project's.
std::fs::remove_file(home.join(".project")).unwrap();
assert_eq!(create(false).unwrap().source, "pipenv");
assert_eq!(calls().lines().count(), 2);
// On another Python than the base, nothing runs and the error says what to do.
std::fs::write(home.join("pyvenv.cfg"), "version = 3.11.4\n").unwrap();
let err = create(true).unwrap_err();
assert!(err.message.contains("Python 3.11 environment, not Python 3.12"), "{}", err.message);
assert!(err.message.contains("pipenv --rm"), "{}", err.message);
assert_eq!(calls().lines().count(), 2);
}
#[test]
fn neutral_dir_is_fresh_and_empty() {
let a = crate::python::neutral_dir().unwrap();
+1 -105
View File
@@ -13,8 +13,6 @@ use std::time::{Duration, Instant};
/// How long a cancelled git's process group (remote helpers, `ssh`, credential helpers) gets
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// Longest the wait for a captured child sleeps before it looks at cancellation again.
const POLL: Duration = Duration::from_millis(20);
/// A throwaway index file in the repository's Git directory.
pub(crate) struct TempIndex(PathBuf);
@@ -655,13 +653,9 @@ pub(crate) fn capture_command(
}
_ => None,
};
// When both readers finish, their senders disconnect the channel and wake the child wait.
let (closed_tx, closed) = mpsc::channel::<()>();
let capture = |mut pipe: Box<dyn Read + Send>| {
let overflow = overflow.clone();
let closed_tx = closed_tx.clone();
std::thread::spawn(move || {
let _closed_tx = closed_tx;
let mut bytes = Vec::new();
(&mut pipe).take(max.saturating_add(1) as u64).read_to_end(&mut bytes)?;
if bytes.len() > max {
@@ -673,9 +667,6 @@ pub(crate) fn capture_command(
};
let stdout = capture(Box::new(child.stdout.take().expect("piped stdout")));
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
drop(closed_tx);
let mut pipes_open = true;
let mut backoff = Duration::from_micros(100);
let status = loop {
if cancel.is_cancelled() || overflow.load(std::sync::atomic::Ordering::Acquire) {
terminate_tree(&mut child, KILL_GRACE);
@@ -693,15 +684,7 @@ pub(crate) fn capture_command(
if let Some(status) = child.try_wait()? {
break status;
}
if pipes_open {
// Cancellation and overflow are only noticed between wake-ups, so wait at most one
// `POLL` for them; the pipes closing ends the wait at once.
pipes_open = !matches!(closed.recv_timeout(POLL), Err(mpsc::RecvTimeoutError::Disconnected));
} else {
// Reap promptly after EOF, but back off if the child keeps running without its pipes.
std::thread::sleep(backoff);
backoff = (backoff * 2).min(POLL);
}
std::thread::sleep(Duration::from_millis(20));
};
if let Some(w) = writer {
let _ = w.join();
@@ -1262,90 +1245,3 @@ mod index_lock_tests {
assert!(!retryable_index_conflict(&["reset"], &out));
}
}
#[cfg(all(test, unix))]
mod capture_tests {
use super::*;
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
#[test]
fn a_cancelled_capture_kills_a_long_running_child() {
let cancel = CancellationToken::new();
let trigger = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
trigger.cancel();
});
let start = Instant::now();
let error = capture_command(sh("sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
canceller.join().unwrap();
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
assert!(start.elapsed() < Duration::from_secs(30));
}
#[test]
fn cancelling_before_the_start_spawns_nothing() {
let cancel = CancellationToken::new();
cancel.cancel();
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let mut cmd = sh(r#"touch "$1""#);
cmd.arg("sh").arg(&marker);
assert!(capture_command(cmd, None, &cancel, usize::MAX, "sh").is_err());
assert!(!marker.exists());
}
#[test]
fn megabytes_on_both_streams_are_captured_whole() {
// Both pipes fill at once: a wait that stopped draining one while blocked on the other,
// or on the exit, would deadlock here.
const SIZE: usize = 6_000_000;
let script = format!("(yes e | head -c {SIZE} >&2) & yes o | head -c {SIZE}; wait; exit 3");
let out = capture_command(sh(&script), None, &CancellationToken::new(), usize::MAX, "sh").unwrap();
assert_eq!((out.stdout.len(), out.stderr.len()), (SIZE, SIZE));
assert!(out.stdout.chunks(2).all(|c| c.starts_with(b"o")));
assert!(out.stderr.chunks(2).all(|c| c.starts_with(b"e")));
assert_eq!(out.code, Some(3));
}
#[test]
fn exit_status_and_both_streams_are_preserved() {
let out = capture_command(sh("echo out; echo err >&2; exit 7"), None, &CancellationToken::new(), 1 << 20, "sh")
.unwrap();
assert_eq!((out.stdout, out.stderr, out.code), (b"out\n".to_vec(), b"err\n".to_vec(), Some(7)));
}
#[test]
fn stdin_reaches_the_child() {
let out = capture_command(sh("cat"), Some(b"piped"), &CancellationToken::new(), 1 << 20, "sh").unwrap();
assert_eq!(out.stdout, b"piped");
}
#[test]
fn output_over_the_limit_stops_the_child() {
let start = Instant::now();
let error = capture_command(sh("yes"), None, &CancellationToken::new(), 1000, "sh").err().unwrap();
assert!(error.to_string().contains("exceeds 1000 bytes"), "{error}");
assert!(start.elapsed() < Duration::from_secs(30));
}
#[test]
fn a_child_that_closes_its_pipes_but_keeps_running_is_still_cancellable() {
let cancel = CancellationToken::new();
let trigger = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
trigger.cancel();
});
let start = Instant::now();
let error = capture_command(sh("exec >&- 2>&-; sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
canceller.join().unwrap();
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
assert!(start.elapsed() < Duration::from_secs(30));
}
}
+5 -15
View File
@@ -478,11 +478,12 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
all.request = None;
all.stop_at = None;
let repo = r.gix()?;
let (decorations, generation) = r.ref_decorations(&repo)?;
let decorations = decorations(&repo)?;
let shallow_vec =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let refs = r.log_refs()?;
let key = format!("{}:{refs:?}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
@@ -645,7 +646,7 @@ fn log_indexed(
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
let (decorations, _) = r.ref_decorations(&repo)?;
let decorations = decorations(&repo)?;
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
let ranges: Vec<_> = q.ranges.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
@@ -740,7 +741,7 @@ fn log_indexed_rows(
if tips.is_empty() && range.is_none() && ranges.is_empty() {
return Ok(Vec::new());
}
let (decorations, _) = r.ref_decorations(&repo)?;
let decorations = decorations(&repo)?;
let paths: Vec<String> = q
.path
.iter()
@@ -1405,19 +1406,8 @@ fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
Ok(tips)
}
#[cfg(test)]
thread_local!(static DECORATION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
/// How many times this thread listed all refs.
#[cfg(test)]
pub(crate) fn decorations_scans() -> usize {
DECORATION_SCANS.get()
}
/// Commit id → decoration labels.
pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId, Vec<String>>> {
#[cfg(test)]
DECORATION_SCANS.set(DECORATION_SCANS.get() + 1);
let mut map: HashMap<ObjectId, Vec<String>> = HashMap::new();
if let Ok(id) = repo.head_id() {
map.entry(id.detach()).or_default().push("HEAD".to_string());
+5 -5
View File
@@ -939,7 +939,6 @@ mod preserve;
mod push_preview;
mod push_report;
mod rebase_editor;
mod ref_decorations;
mod worktree_config;
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
mod incoming;
@@ -1079,7 +1078,6 @@ pub struct Repo {
cli_status: std::sync::atomic::AtomicBool,
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
log_index: std::sync::Mutex<log_index::LogIndex>,
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
log_signatures: std::sync::Mutex<history::LogSignatureCache>,
conflict_mutation: std::sync::Mutex<()>,
amend_recovery: std::sync::Mutex<Option<commit_rewrite::PendingAmend>>,
@@ -1139,9 +1137,11 @@ impl Repo {
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
let _scope = self.execution_scope();
// Restricted Mode reads this through git too: `cli::command` strips what the repository's
// config could run, and the status call empties its clean/process filters. The full
// gitoxide status it used to answer with walked the whole tree for one changed file.
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
// with a pathspec: answer with the full gitoxide status instead.
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
return status::status(self);
}
if paths.is_empty() {
return status::status_paths(self, &[]);
}
-264
View File
@@ -1,264 +0,0 @@
//! Ref decorations of the history, reused while git's ref storage has not changed.
//!
//! Listing and peeling every ref costs about 25 µs each, which a history page paid in full
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
use crate::Repo;
use crate::repo::absolute;
use gix::ObjectId;
use ide_core::IdeResult;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
/// A timestamp this close to the time it was read cannot tell two writes apart: a later write
/// may leave the same value (coarse file systems, FAT's 2 s). Such a snapshot is never reused.
const RACY_WINDOW: Duration = Duration::from_secs(2);
type Stat = Option<(SystemTime, u64)>;
pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
#[derive(Default)]
pub(crate) struct RefDecorations {
snapshot: Option<Snapshot>,
/// Changes when the decorations do, so cached views of them can be keyed by it.
generation: u64,
}
struct Snapshot {
map: Decorations,
stamp: Vec<(PathBuf, Stat)>,
reusable: bool,
}
fn stat(path: &Path) -> Stat {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
/// `HEAD`, `packed-refs` and every directory under `refs/`.
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
let mut pending = vec![common_dir.join("refs")];
while let Some(dir) = pending.pop() {
if let Ok(entries) = std::fs::read_dir(&dir) {
pending.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
}
paths.push(dir);
}
paths.into_iter().map(|path| (path.clone(), stat(&path))).collect()
}
impl RefDecorations {
fn get(&mut self, repo: &gix::Repository, git_dir: &Path, common_dir: &Path) -> IdeResult<(Decorations, u64)> {
if let Some(snapshot) = &self.snapshot
&& snapshot.reusable
&& snapshot.stamp.iter().all(|(path, before)| stat(path) == *before)
{
return Ok((snapshot.map.clone(), self.generation));
}
// Stamped before the refs are read, so a write after the stamp shows in the next one.
let taken = SystemTime::now();
let stamp = stamp(git_dir, common_dir);
let map = crate::history::decorations(repo)?;
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
let map = match &self.snapshot {
Some(old) if unchanged => old.map.clone(),
_ => {
self.generation += 1;
Arc::new(map)
}
};
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
Ok((map, self.generation))
}
}
impl Repo {
/// Commit id → decoration labels, and a number that changes whenever they do.
pub(crate) fn ref_decorations(&self, repo: &gix::Repository) -> IdeResult<(Decorations, u64)> {
let common_dir = absolute(repo.common_dir())?;
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
}
}
#[cfg(test)]
mod tests {
use crate::history::decorations_scans;
use crate::{LogOrder, LogQuery, Repo};
use std::path::Path;
use std::time::{Duration, SystemTime};
fn git(dir: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
.args(["-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn commit(dir: &Path, message: &str) -> String {
std::fs::write(dir.join("f"), message).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-qm", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
fn set_ref_times(repo: &Repo, time: SystemTime) {
let git = repo.git_dir.clone();
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
let mut pending = vec![git.join("refs")];
while let Some(dir) = pending.pop() {
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
paths.push(dir);
}
let mut options = std::fs::File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
options.access_mode(FILE_WRITE_ATTRIBUTES).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
}
for path in paths.into_iter().filter(|p| p.exists()) {
options.open(path).unwrap().set_modified(time).unwrap();
}
}
/// As if the refs were written long ago, then reads the history once so the decorations
/// are cached; a second read must not list the refs again.
fn settle(repo: &Repo) {
set_ref_times(repo, SystemTime::now() - Duration::from_secs(3600));
page(repo, 0, 1);
let scans = decorations_scans();
page(repo, 0, 1);
assert_eq!(decorations_scans(), scans, "the decorations were not reusable");
}
fn page(repo: &Repo, skip: u32, limit: u32) -> Vec<crate::Commit> {
repo.log(&LogQuery { skip, limit, summary_only: true, order: LogOrder::Topo, ..Default::default() }).unwrap()
}
fn labels(repo: &Repo, id: &str) -> Vec<String> {
let all = page(repo, 0, 0);
all.into_iter().find(|c| c.id == id).unwrap().refs
}
#[test]
fn warm_pages_do_not_list_the_refs() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
for i in 0..30 {
commit(dir, &format!("c{i}"));
}
for i in 0..20 {
git(dir, &["branch", &format!("b{i}")]);
}
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let after_first = decorations_scans();
for skip in [10, 20, 0, 5] {
assert_eq!(page(&repo, skip, 1).len(), 1);
assert_eq!(page(&repo, skip, 10).len(), 10);
}
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
}
#[test]
fn fresh_ref_timestamps_are_not_trusted() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
set_ref_times(&repo, SystemTime::now());
page(&repo, 0, 10);
let scans = decorations_scans();
// A write within the timestamp's resolution would leave it unchanged: rescan every time.
page(&repo, 0, 10);
assert!(decorations_scans() > scans);
assert!(labels(&repo, &first).contains(&"main".to_string()));
}
#[test]
fn decorations_follow_every_kind_of_ref_change() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let first_labels = labels(&repo, &first);
assert!(first_labels.contains(&"HEAD".to_string()) && first_labels.contains(&"main".to_string()));
// A new commit moves HEAD and the branch.
settle(&repo);
let second = commit(dir, "second");
assert_eq!(labels(&repo, &first), Vec::<String>::new());
assert!(labels(&repo, &second).contains(&"main".to_string()));
// A new tag, then an annotated one, in a directory that did not exist before.
settle(&repo);
git(dir, &["tag", "v1", &first]);
assert_eq!(labels(&repo, &first), ["tag: v1"]);
settle(&repo);
git(dir, &["tag", "-a", "-m", "m", "rel/v2", &first]);
assert_eq!(labels(&repo, &first), ["tag: rel/v2", "tag: v1"]);
// A new branch, one moved to another commit, and one deleted.
settle(&repo);
git(dir, &["branch", "side", &first]);
assert!(labels(&repo, &first).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-f", "side", &second]);
assert!(!labels(&repo, &first).contains(&"side".to_string()));
assert!(labels(&repo, &second).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-D", "side"]);
assert!(!labels(&repo, &second).contains(&"side".to_string()));
// Refs in packed-refs: packing changes nothing visible, deleting one rewrites the file.
git(dir, &["branch", "packed", &first]);
git(dir, &["pack-refs", "--all"]);
settle(&repo);
assert!(labels(&repo, &first).contains(&"packed".to_string()));
git(dir, &["branch", "-D", "packed"]);
assert!(!labels(&repo, &first).contains(&"packed".to_string()));
// A detached HEAD and a tag deleted again.
settle(&repo);
git(dir, &["checkout", "-q", "--detach", &first]);
assert!(labels(&repo, &first).contains(&"HEAD".to_string()));
assert!(!labels(&repo, &second).contains(&"HEAD".to_string()));
settle(&repo);
git(dir, &["tag", "-d", "v1"]);
assert_eq!(labels(&repo, &first), ["HEAD", "tag: rel/v2"]);
}
#[test]
fn a_ref_change_between_pages_replaces_the_cached_view() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
commit(dir, "second");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
page(&repo, 0, 10);
settle(&repo);
git(dir, &["tag", "v1", &first]);
let rows = page(&repo, 0, 10);
assert_eq!(rows.iter().find(|c| c.id == first).unwrap().refs, ["tag: v1"]);
}
}
-1
View File
@@ -88,7 +88,6 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
cli_status: Default::default(),
automatic_shelf: Default::default(),
log_index: Default::default(),
ref_decorations: Default::default(),
log_signatures: Default::default(),
conflict_mutation: Default::default(),
amend_recovery: Default::default(),
-56
View File
@@ -583,60 +583,4 @@ mod tests {
cli_status(&repo, &IgnoredNames::default()).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
fn committed_repo(dir: &Path) {
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "same\n").unwrap();
std::fs::write(dir.join("b.txt"), "same\n").unwrap();
commit_all(dir, "base");
}
/// The dirty-scope refresh in Restricted Mode reads the named paths only: it used to answer
/// with the full status, which walks the whole tree for one saved file.
#[test]
fn restricted_status_paths_reads_only_the_named_paths() {
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
std::fs::write(dir.join("a.txt"), "changed\n").unwrap();
std::fs::write(dir.join("b.txt"), "changed\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let one = repo.status_paths(&[repo.root().join("a.txt")]).unwrap();
assert_eq!(one.iter().map(|s| s.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
assert_eq!(repo.status().unwrap().len(), 2, "the full status still lists both");
}
/// The scoped read is `git status`, which applies the repository's clean filters to compare
/// content: Restricted Mode must empty them there as it does for the full read.
#[cfg(unix)]
#[test]
fn restricted_status_paths_does_not_run_repository_filters() {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
let marker = dir.join(".git/executed");
let script = dir.join(".git/marker.sh");
std::fs::write(&script, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
git(dir, &["config", "filter.marker.clean", script.to_str().unwrap()]);
std::fs::write(dir.join(".gitattributes"), "*.txt filter=marker\n").unwrap();
// Same size, new mtime: git has to read (and clean) the file to tell whether it changed.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "diff\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let paths = [repo.root().join("a.txt")];
let listed = repo.status_paths(&paths).unwrap();
assert_eq!(listed.len(), 1, "the change is still listed");
assert!(!marker.exists(), "Restricted Mode ran the repository's clean filter");
// Control: a trusted run does use the filter, so the fixture is live.
repo.set_execution_allowed(true);
repo.status_paths(&paths).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
}
+2 -11
View File
@@ -591,17 +591,8 @@ fn select_into(
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<String>> {
let index = r.git_dir.join("index");
match std::fs::File::open(index) {
Ok(mut source) => {
let metadata = source.metadata()?;
let mut copy = std::fs::File::create(&tmp.0)?;
copy.set_permissions(metadata.permissions())?;
std::io::copy(&mut source, &mut copy)?;
// Git uses the index timestamp to decide which same-size files need a content check.
copy.set_modified(metadata.modified()?)?;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
fill_commit_index(r, &env, options, encoding)
-9
View File
@@ -2017,17 +2017,11 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
#[test]
fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() {
let fx = Fixture::new();
fx.git(&["config", "core.checkStat", "minimal"]);
fx.git(&["config", "core.trustctime", "false"]);
let same_tick = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
let set_mtime =
|path| std::fs::File::options().write(true).open(fx.path(path)).unwrap().set_modified(same_tick).unwrap();
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
fx.write("f.txt", base);
fx.write("staged.txt", "s\n");
fx.write("old.txt", "moved\nfile\nwith\nlines\n");
fx.write("bin.dat", "\0\x01");
set_mtime("bin.dat");
fx.commit_all("base");
let repo = fx.repo();
let utf8 = |_: &Path| -> ide_core::IdeResult<&encoding_rs::Encoding> { Ok(encoding_rs::UTF_8) };
@@ -2038,9 +2032,6 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index()
fx.git(&["add", "staged.txt"]);
fx.git(&["mv", "old.txt", "new.txt"]);
fx.write("bin.dat", "\0\x02");
// Git must recheck a same-size edit made on the same clock tick as the index.
set_mtime("bin.dat");
set_mtime(".git/index");
fx.write("added.txt", "new\n");
let index_before = std::fs::read(fx.dir.join(".git/index")).unwrap();
+1 -2
View File
@@ -1753,8 +1753,7 @@ mod tests {
std::fs::write(root.join("src/a/after.rs"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/a/after.rs"))));
let paths = all_paths(&batches.lock());
let excluded = root.join("node_modules");
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
assert!(!paths.contains(&root.join("lib/out/o.txt")));
// Un-ignoring lib/out keeps its existing filename watch.
+2 -12
View File
@@ -113,13 +113,7 @@ fn restrict_project_layer(below: &Json, layer: &mut Json) {
// The IDE-wide interpreter list, its view options and the project interpreters of
// other projects belong to the user's settings, not to one project.
if let Some(python) = layer.get_mut("languages").and_then(|l| l.get_mut("python")).and_then(Json::as_object_mut) {
for key in [
"interpreters",
"hiddenInterpreters",
"hideOtherProjectInterpreters",
"showInterpreterPaths",
"interpreterPaths",
] {
for key in ["interpreters", "hiddenInterpreters", "hideOtherProjectInterpreters", "showInterpreterPaths"] {
python.remove(key);
}
}
@@ -736,8 +730,6 @@ mod tests {
let store = SettingsStore::load(&cfg, Some(&proj));
store.set(SettingsScope::Global, "languages.python.interpreters", json!(["/envs/a/bin/python"])).unwrap();
store.set(SettingsScope::Global, "languages.python.showInterpreterPaths", json!(false)).unwrap();
let paths = json!({ "/envs/a/bin/python": ["/shared/lib"] });
store.set(SettingsScope::Global, "languages.python.interpreterPaths", paths).unwrap();
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
assert!(!loaded.languages.python.show_interpreter_paths);
@@ -747,12 +739,10 @@ mod tests {
proj.join(".openidea/settings.toml"),
"[languages.python]\ninterpreters = [\"/proj/bin/python\"]\n\
hiddenInterpreters = [\"/envs/a/bin/python\"]\nhideOtherProjectInterpreters = true\n\
showInterpreterPaths = true\n\
[languages.python.interpreterPaths]\n\"/envs/a/bin/python\" = [\"/proj/evil\"]\n",
showInterpreterPaths = true\n",
)
.unwrap();
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
assert_eq!(loaded.languages.python.interpreter_paths["/envs/a/bin/python"], ["/shared/lib"]);
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
assert!(loaded.languages.python.hidden_interpreters.is_empty());
assert!(!loaded.languages.python.hide_other_project_interpreters);
+1 -1
View File
@@ -64,7 +64,7 @@ JSON-RPC 2.0 with `Content-Length` framing (`ide-jsonrpc`), over the server's st
| notification `plugin` | server → client | `{ window, event }` from code plugins of the remote project |
| request `plugin_secret` | server → client | `{ plugin, name }` → `string` or `null`: a secret from the desktop's keychain |
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`; the desktop refuses a server that speaks another one. Change it when an existing command's argument or result changes shape. A binary argument is an `IpcBytes` (a base64 string in JSON, `string` in the bindings), never a `Vec<u8>`, which is an array of numbers about 3.6 times the size. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
## Routing commands
+1 -7
View File
@@ -43,8 +43,7 @@ The project interpreter is chosen in this order:
1. The interpreter set in **Settings › Languages & Frameworks › Python Interpreter**.
2. A virtualenv in the project: `.venv`, `venv`, `env` or `.env` (a folder with `pyvenv.cfg`), or a pixi environment in `.pixi/envs/`.
3. The Pipenv environment for the nearest `Pipfile`, including one selected by a `.venv` file or `PIPENV_CUSTOM_VENV_NAME`.
4. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
3. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
The interpreter list on that page also shows what the IDE detects on the machine: the active `VIRTUAL_ENV`, virtualenvs made by virtualenvwrapper, pipenv and Poetry, pyenv versions, Pythons installed by uv, mise and asdf installs, conda environments (Miniconda, Anaconda, Miniforge, Mambaforge, micromamba, and every env that `conda env list` shows), and the `python` executables on `PATH`.
@@ -52,10 +51,6 @@ The selected interpreter is passed to basedpyright and Pyright (`python.pythonPa
The **Python Interpreter** item in the status bar shows the current interpreter. Click it to switch, or to open **Add New Interpreter…** and **Interpreter Settings…**.
### Interpreter paths
**Settings › Languages & Frameworks › Python › All Interpreters › Show Paths for Selected Interpreter** lists the interpreter's `sys.path` and lets you add folders outside the project to it, such as a checkout of a shared library. The added folders are saved per interpreter in the IDE settings, so they apply to every project that uses it. basedpyright and Pyright get them as `extraPaths`, runs, debug sessions, tests and the Python Console get them on `PYTHONPATH`, and they are listed under **External Libraries**. At run time they are searched before the interpreter's own entries. A folder that no longer exists is marked as missing and skipped, and so is one that `PYTHONPATH` cannot hold (not absolute, or with its separator in the name). A folder inside the project is not listed under External Libraries, so its files stay editable. The interpreter's own entries cannot be removed, and a Docker or Compose run target has no paths of its own to edit.
### A Docker or Compose run target as the interpreter
When the project's dependencies are installed only in an image, choose a Docker or Docker Compose [run target](/en/guide/remote/containers#docker-and-docker-compose-run-targets) as the interpreter: the interpreter list and the status bar item show those targets next to the local interpreters.
@@ -74,7 +69,6 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add
- **Virtualenv Environment**: `python -m venv` from the base interpreter you pick.
- **uv Environment**: `uv venv <location> --python <base>` (uv must be on `PATH`).
- **Poetry Environment**: `poetry env use <base>` in the project.
- **Pipenv Environment**: `pipenv --python <base>` in the project (pipenv must be on `PATH`). Pipenv writes a `Pipfile` when the project has none, importing `requirements.txt` if there is one. With **Install packages from Pipfile** it then runs `pipenv install --dev`. An environment the project already has is reused; if it was built on another Python version than the base interpreter, nothing is changed and the dialog says so (remove it with `pipenv --rm` to start over).
- **Conda Environment**: `conda create -n <name>` in conda's envs directory, with the chosen Python version.
You can also select an existing interpreter or environment folder. The new interpreter becomes the project interpreter.
+1 -1
View File
@@ -64,7 +64,7 @@ openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <por
| 通知 `plugin` | 服务端 → 客户端 | `{ window, event }`:远程项目中代码插件发出的事件 |
| 请求 `plugin_secret` | 服务端 → 客户端 | `{ plugin, name }` → `string` 或 `null`:从桌面端钥匙串取密钥 |
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`;桌面端会拒绝使用其他版本协议的服务端。已有命令的参数或结果形态改变时要修改它。二进制参数使用 `IpcBytes`(JSON 中是 base64 字符串,绑定中是 `string`),不要用 `Vec<u8>`——它会变成体积约 3.6 倍的数字数组。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
## 命令路由
+1 -7
View File
@@ -43,8 +43,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
1. **设置 › 语言和框架 › Python 解释器** 中选定的解释器。
2. 项目里的虚拟环境:`.venv`、`venv`、`env` 或 `.env`(含 `pyvenv.cfg` 的目录),或 `.pixi/envs/` 下的 pixi 环境。
3. 最近的 `Pipfile` 对应的 Pipenv 环境,包括通过 `.venv` 文件或 `PIPENV_CUSTOM_VENV_NAME` 指定的环境。
4. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
3. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
该页面的解释器列表还会列出 IDE 在本机找到的解释器:当前激活的 `VIRTUAL_ENV`,virtualenvwrapper、pipenv 和 Poetry 创建的虚拟环境,pyenv 的各个版本,uv 安装的 Python,mise 和 asdf 的安装,conda 环境(Miniconda、Anaconda、Miniforge、Mambaforge、micromamba,以及 `conda env list` 能看到的所有环境),还有 `PATH` 上的 `python` 可执行文件。
@@ -52,10 +51,6 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
状态栏上的 **Python 解释器** 显示当前解释器,点击可以切换,也可以打开 **添加新的解释器…** 和 **解释器设置…**。
### 解释器路径
**设置 › 语言和框架 › Python › 所有解释器 › 显示所选解释器的路径** 列出该解释器的 `sys.path`,并可以把项目之外的文件夹(例如共享库的检出目录)添加进去。添加的文件夹按解释器保存在 IDE 设置中,因此对使用该解释器的每个项目生效。basedpyright 和 Pyright 通过 `extraPaths` 获得这些文件夹,运行、调试、测试和 Python 控制台通过 `PYTHONPATH` 获得,它们也会显示在 **External Libraries** 下。运行时它们会先于解释器自带的条目被搜索。已不存在的文件夹会标记为缺失并被跳过;`PYTHONPATH` 无法容纳的文件夹(不是绝对路径,或名称中含有分隔符)同样会被跳过。位于项目内的文件夹不会列在 External Libraries 下,其中的文件仍可编辑。解释器自带的条目不能删除,Docker 或 Compose 运行目标没有可编辑的路径。
### 以 Docker 或 Compose 运行目标作为解释器
如果项目的依赖只安装在镜像里,可以把 Docker 或 Docker Compose [运行目标](/zh/guide/remote/containers#docker-和-docker-compose-运行目标)选为解释器:解释器列表和状态栏项会把这些目标列在本地解释器旁边。
@@ -74,7 +69,6 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
- **Pipenv 环境**:在项目中执行 `pipenv --python <base>`(`PATH` 上需要有 pipenv)。项目没有 `Pipfile` 时,Pipenv 会写入一个,有 `requirements.txt` 时从中导入。勾选 **安装 Pipfile 中的软件包** 时,随后执行 `pipenv install --dev`。项目已有的环境会被复用;如果它的 Python 版本与基础解释器不同,不做任何改动并在对话框中提示(可用 `pipenv --rm` 删除后重建)。
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
-57
View File
@@ -131,60 +131,3 @@ for (const home of [false, true]) {
}
}
}
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
await prepare(page, true, false);
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
const scroller = page.locator(".cm-scroller").filter({ has: box });
const overflow = () =>
scroller.evaluate((el) => ({
x: el.scrollWidth - el.clientWidth,
y: el.scrollHeight - el.clientHeight,
}));
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Reply with OK.");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Start", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState({
entries: new Map([
[
id,
[
{ type: "user", text: "Reply with OK.", attachments: [] },
{ type: "agent", text: "OK" },
],
],
]),
});
}, task.id);
await expect(page.getByText("OK", { exact: true })).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect(scroller).toHaveCSS("overflow-x", "hidden");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Short draft");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("word".repeat(2000));
await expect(scroller).toHaveCSS("overflow-y", "auto");
await expect
.poll(async () => {
const { x, y } = await overflow();
return x === 0 && y > 0;
})
.toBe(true);
await box.fill("");
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
});
-111
View File
@@ -1,111 +0,0 @@
import { Buffer } from "node:buffer";
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "tool-images",
title: "Render preview",
provider: "claude",
model: null,
status: "ready",
isolation: "local",
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="220" viewBox="0 0 900 220">
<rect width="900" height="220" fill="#f1f5f9"/>
<g fill="#0f766e"><circle cx="150" cy="92" r="48"/><rect x="103" y="137" width="94" height="42" rx="8"/></g>
<g fill="#2563eb"><ellipse cx="450" cy="92" rx="28" ry="48"/><rect x="420" y="137" width="60" height="42" rx="8"/></g>
<g fill="#b45309"><circle cx="750" cy="92" r="48"/><rect x="703" y="137" width="94" height="42" rx="8"/></g>
<g fill="#0f172a" font-size="20" font-family="sans-serif" text-anchor="middle"><text x="150" y="208">Front</text><text x="450" y="208">Side</text><text x="750" y="208">Back</text></g></svg>`;
const image = { mimeType: "image/svg+xml", data: Buffer.from(svg).toString("base64"), name: null };
const entries: AgentEntry[] = [
{
type: "user",
text: "Render three views of the sample model.",
attachments: [],
sentMs: 1000,
doneMs: 2000,
steered: false,
},
{ type: "thought", text: "Rendering the sample views." },
{
type: "tool",
id: "render",
title: "Render preview",
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
images: [image],
},
{
type: "tool",
id: "inspect",
title: "Read preview metadata",
kind: "read",
status: "completed",
locations: [],
output: "Preview generated successfully.",
diffs: [],
},
{ type: "agent", text: "The preview is ready: front, side and back." },
];
for (const foldTurns of [true, false]) {
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
workbench: page,
}) => {
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
await page.evaluate(
async ({ task, entries, foldTurns }) => {
const storePath = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { useProject } = await import(projectPath);
const { commands } = await import(ipcPath);
commands.agentEntries = async () => ({ status: "ok", data: entries });
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, entries]]),
unread: new Set(),
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
);
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
const preview = page.getByRole("img", { name: "Image", exact: true });
await expect(preview).toBeVisible();
await expect(preview).toHaveJSProperty("naturalWidth", 900);
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
const box = (await preview.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
await dialog.getByText("Close", { exact: true }).click();
await expect(dialog).toHaveCount(0);
await fold.locator("summary").first().click();
await expect(preview).toHaveCount(1);
await fold.locator("summary").first().click();
await expect(preview).toBeVisible();
});
}
-1
View File
@@ -274,7 +274,6 @@ test("completion clips long parameters before the suggestion name and return typ
});
await expect(row.locator(".cm-lsp-type")).toHaveText(returnType);
await page.setViewportSize({ width: 820, height: 760 });
await page.evaluate(() => document.fonts.ready);
await expect
.poll(() =>
row.evaluate((el) => {
-52
View File
@@ -1,52 +0,0 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(
async ({ fontSize, titles }) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
const at = { line: 0, col: 0 };
window.__ipc.handlers.lsp_code_lens = () =>
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
},
{ fontSize, titles },
);
// An edit asks the server for its lenses again.
await editor.locator(".cm-line").first().click();
await page.keyboard.press("End");
await page.keyboard.type(" ");
const row = editor.locator(".cm-openidea-lens");
await expect(row).toContainText(titles[0]!);
return { editor, row };
}
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
const overflow = await row.evaluate((el) => {
const box = el.getBoundingClientRect();
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
const range = document.createRange();
range.selectNodeContents(item);
const text = range.getBoundingClientRect();
return Math.max(box.top - text.top, text.bottom - box.bottom);
});
});
expect(overflow).toHaveLength(2);
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
// The editor measured the taller row: the lines below it still sit beside their numbers.
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
});
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
const { row } = await lensRow(page, 13, ["3 usages"]);
expect((await row.boundingBox())!.height).toBe(16);
});
-39
View File
@@ -487,45 +487,6 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
for (const mode of ["Preview Only", "Editor and Preview"]) {
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
const path = "/dev/acme-api/linked-heading.md";
const heading = "5.2 状态机";
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
const editor = await openFromTree(page, "README.md");
await page.evaluate(
async ({ path, target }) => {
const backendModule = "/src/editor/core/backend.ts";
const routeModule = "/src/platform/tauriCore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
docBackend().files.set(path, target);
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
);
},
{ path, target },
);
await editor.locator(".cm-content").focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(destinationTab).toHaveCount(0);
await preview.getByRole("link", { name: "Linked heading" }).click();
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
if (mode === "Editor and Preview") {
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
}
});
}
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
-52
View File
@@ -1,52 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
// #5402: an External Tool run from Find Action resolves $FilePath$ against the focused component,
// the Project view's selected file while the tree has focus, else the editor's file.
test("External Tools take $FilePath$ from the Project view selection, else the editor", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
const editor = page.locator(".cm-content");
await expect(editor).toBeFocused();
await stubDesktop(page);
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
// Exits at once, so the next run of the same tool doesn't ask to stop this one.
window.__ipc.emit({ type: "runExited", run: id, code: 0 });
return {
id,
configId: (config as { id: string }).id,
name: (config as { name: string }).name,
pid: 4242,
running: true,
pty: false,
};
};
});
const runTool = async () => {
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await search.getByRole("combobox").fill("Echo File Path");
await expect(search.getByRole("option", { name: /Echo File Path/ })).toBeVisible();
await search.getByRole("combobox").press("Enter");
await expect(search).toBeHidden();
};
const startedArgs = async () =>
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
await runTool();
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
await editor.click();
await runTool();
await expect.poll(startedArgs).toEqual([
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
["/dev/acme-api/README.md", "README.md"],
]);
});
-51
View File
@@ -1,51 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function stubProjectTypes(page: Page, types: string[]) {
await stubDesktop(page);
await page.evaluate((types) => {
const h = window.__ipc.handlers;
h.index_file_extensions = () => types.map((extension, i) => ({ extension, files: 100 - i }));
h.languages = () => types.map((extension) => ({ id: extension, name: extension, extensions: [extension] }));
h.search_validate = () => null;
}, types);
}
async function openMaskMenu(page: Page) {
await page.keyboard.press("Meta+Shift+f");
const dialog = page.getByRole("dialog", { name: "Find in Files" });
await dialog.getByRole("button", { name: "Recent file masks" }).click();
const menu = page.getByRole("menu").last();
await expect(menu).toBeVisible();
return menu;
}
test("the file mask menu offers every known file type in the project", async ({ workbench: page }) => {
await stubProjectTypes(page, ["rs", "md", "json", "toml", "yml", "properties"]);
const menu = await openMaskMenu(page);
await expect(menu.getByRole("menuitem")).toHaveText(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
await menu.getByRole("menuitem", { name: "*.properties" }).click();
await expect(page.getByRole("textbox", { name: "File mask" })).toHaveValue("*.properties");
});
test("a long file mask menu stays inside the window and scrolls to its last type", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 520 });
const types = Array.from({ length: 40 }, (_, i) => `type${String(i).padStart(2, "0")}`);
await stubProjectTypes(page, types);
const menu = await openMaskMenu(page);
const popup = menu.locator("..");
await expect(menu.getByRole("menuitem")).toHaveCount(40);
await expect
.poll(async () => {
const { y, height } = (await popup.boundingBox())!;
return y >= 0 && y + height <= 520;
})
.toBe(true);
await menu.getByRole("menuitem").first().focus();
await page.keyboard.press("End");
const last = menu.getByRole("menuitem", { name: "*.type39" });
await expect(last).toBeFocused();
await expect(last).toBeInViewport();
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
});
-1
View File
@@ -38,7 +38,6 @@ Object.assign(window, {
paddingRight: false,
tooltip: null,
parts: [],
textEdits: [],
},
]);
},
-31
View File
@@ -93,37 +93,6 @@ for (const activation of ["double-click", "Enter"] as const) {
});
}
test("records a modified wheel gesture and runs the assigned action", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Find Action/ });
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: "Mouse Shortcut: Find Action…", exact: true });
const pad = recorder.getByRole("textbox", { name: "Mouse shortcut" });
await pad.hover();
const scrollUp = async () => {
await page.keyboard.down("Control");
await page.mouse.wheel(0, -120);
await page.keyboard.up("Control");
};
await scrollUp();
await expect(pad).toHaveText("⌃Wheel Up");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await expect(search).toBeHidden();
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(row).toContainText("⌃Wheel Up");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
await page.mouse.move(700, 450);
await page.mouse.wheel(0, 120);
await expect(search).toBeHidden();
await scrollUp();
await expect(search).toBeVisible();
});
test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({
workbench: page,
}) => {
+6 -39
View File
@@ -5,29 +5,14 @@ test.use({ video: "on" });
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const markers: Record<string, string[]> = {
"/work/api": ["go.mod"],
"/work/web": ["pom.xml"],
"/work/library": ["pom.xml"],
"/work/tutor": ["package.json", "vite.config.ts"],
const markers: Record<string, string> = {
"/work/api": "go.mod",
"/work/web": "pom.xml",
"/work/library": "pom.xml",
};
window.__ipc.handlers.fs_read_dir = ({ path }) => {
const files = (markers[String(path)] ?? []).map((name) => ({
name,
path: `${path}/${name}`,
kind: "file",
size: 0,
mtimeMs: 0,
}));
return path === "/work/tutor"
? [...files, { name: "src", path: "/work/tutor/src", kind: "dir", size: 0, mtimeMs: 0 }]
: files;
};
const backend = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backend);
window.__ipc.handlers.fs_create_file = ({ path }) => {
docBackend().files.set(String(path), "");
return null;
const name = markers[String(path)];
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
};
window.__ipc.handlers.run_configs = () => [
{
@@ -69,7 +54,6 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Svelte Component", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
@@ -89,23 +73,6 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
const tutor = page.getByRole("treeitem", { name: "tutor /work/tutor", exact: true });
if ((await tutor.getAttribute("aria-expanded")) !== "true") await tutor.locator("[data-tree-toggle]").click();
await newMenu("/work/tutor/src");
const component = page.getByRole("menuitem", { name: "Svelte Component", exact: true });
await expect(component).toBeVisible();
await page.screenshot({ path: test.info().outputPath("svelte-new-menu.png"), animations: "disabled" });
await component.click();
const svelte = page.getByRole("dialog", { name: "New Svelte Component", exact: true });
const name = svelte.getByRole("textbox", { name: "Name", exact: true });
await name.fill("+page.svelte");
await name.press("Enter");
await expect(svelte).toBeHidden();
expect(await ipcCalls(page, "fs_create_file")).toEqual([{ path: "/work/tutor/src/+page.svelte" }]);
await expect(page.getByRole("tab", { name: "+page.svelte" })).toHaveAttribute("aria-selected", "true");
await expect(page.locator(".cm-content")).toContainText("<script>");
});
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
+2 -15
View File
@@ -37,15 +37,6 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
});
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
await page.setViewportSize({ width: 720, height: 480 });
const menu = page.getByRole("menu", { name: "Context menu" });
@@ -99,7 +90,6 @@ test("Git ignore submenu offers shared and local destinations for files and fold
});
test("keeps New open on a slow diagonal path across sibling items", async ({ workbench: page }) => {
await page.clock.install();
await page.getByRole("treeitem", { name: "README.md", exact: true }).click({ button: "right" });
const parent = page.getByRole("menuitem", { name: "New", exact: true });
const box = (await parent.boundingBox())!;
@@ -111,16 +101,13 @@ test("keeps New open on a slow diagonal path across sibling items", async ({ wor
.filter({ has: page.getByRole("menuitem", { name: "Directory", exact: true }) });
const target = (await submenu.getByRole("menuitem").last().boundingBox())!;
const end = { x: target.x + 20, y: target.y + target.height / 2 };
// Keep the gesture cadence independent of the runner's input and assertion round trips.
await page.clock.pauseAt(new Date(Date.now() + 1000));
for (let step = 1; step <= 10; step++) {
await page.mouse.move(start.x + ((end.x - start.x) * step) / 10, start.y + ((end.y - start.y) * step) / 10);
await page.clock.runFor(75);
await page.waitForTimeout(75);
await expect(parent).toHaveAttribute("aria-expanded", "true");
}
await page.clock.runFor(350);
await page.waitForTimeout(350);
await expect(parent).toHaveAttribute("aria-expanded", "true");
await page.clock.resume();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
});
+2 -1
View File
@@ -12,8 +12,9 @@ test("the scratch language chooser fits short windows and keeps recents separate
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
scratchesDir: async () => "/test-app-data/scratches",
dataDir: async () => "/test-app-data",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+1 -1
View File
@@ -14,7 +14,7 @@ test("double Shift opens Search Everywhere with its tabs; Escape closes it", asy
});
test("Search Everywhere finds and runs an action", async ({ workbench: page }) => {
await page.locator("header").getByRole("button", { name: "Search Everywhere", exact: true }).click();
await doubleShift(page);
const dialog = page.getByRole("dialog", { name: "Search Everywhere" });
await dialog.getByRole("combobox").fill("Language Servers");
const option = dialog.getByRole("option", { name: /Language Servers/ }).first();
+3 -3
View File
@@ -11,11 +11,11 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
configurable: true,
value: { transformCallback: () => 1 },
});
const stored: { id: number; data: string; mime: string }[] = [];
const stored: { id: number; data: number[]; mime: string }[] = [];
const writes: string[] = [];
commands.termSpawn = async () => ({ status: "ok", data: { id: 838, title: "pwsh", pid: 1 } });
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
commands.termStoreImage = async (id: number, data: string, mime: string) => {
commands.termStoreImage = async (id: number, data: number[], mime: string) => {
stored.push({ id, data, mime });
return { status: "ok", data: "C:\\Temp\\a'b c\\image.png" };
};
@@ -47,6 +47,6 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
}
});
expect(observed.claimed).toBe(true);
expect(observed.stored).toEqual([{ id: 838, data: "iVBORw==", mime: "image/png" }]);
expect(observed.stored).toEqual([{ id: 838, data: [137, 80, 78, 71], mime: "image/png" }]);
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
});
-40
View File
@@ -1,40 +0,0 @@
import { expect, test } from "./fixtures";
test("hovering a tinted project tab keeps its colour", async ({ workbench: page }) => {
await page.evaluate(async () => {
const tabColors = "/src/workbench/tabColors.ts";
const windowGroups = "/src/platform/windowGroups.ts";
const { setTabColorOverride } = await import(/* @vite-ignore */ tabColors);
const { useWindowGroup } = await import(/* @vite-ignore */ windowGroups);
setTabColorOverride("/tinted", "#d24b8f");
useWindowGroup.setState({
tabs: [
{ label: "main", name: "acme-api", root: "/plain", current: true },
{ label: "second", name: "acme-api", root: "/plain2", current: false },
{ label: "third", name: "acme-api", root: "/tinted", current: false },
],
});
});
const plain = page.locator('[data-project-tab="second"]');
const tinted = page.locator('[data-project-tab="third"]');
await expect(tinted).toBeVisible();
// A blank strip inside the tab: right of the hover close button, left of the centred label.
const strip = async (tab: typeof plain) => {
const box = (await tab.boundingBox())!;
return { x: box.x + 34, y: box.y + box.height / 2 - 5, width: 8, height: 10 };
};
const shoot = async (tab: typeof plain) => page.screenshot({ clip: await strip(tab), animations: "disabled" });
await tinted.hover();
const tintedHover = await shoot(tinted);
await page.mouse.move(700, 600);
const tintedRest = await shoot(tinted);
await plain.hover();
const plainHover = await shoot(plain);
// The opaque hover surface must not swallow the tint: a tinted tab renders differently from a plain one.
expect(tintedHover.equals(plainHover)).toBe(false);
// Hover still gives feedback on the tinted tab itself.
expect(tintedHover.equals(tintedRest)).toBe(false);
});
+1 -1
View File
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.18.0
Bundle-Version: 1.17.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+1 -1
View File
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.17.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
Binary file not shown.
-1
View File
@@ -19,7 +19,6 @@
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
<command id="openidea.java.refreshArchives"/>
<command id="openidea.java.updateProjectConfigurations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.sources.GeneratedSourcesCommand">
<command id="openidea.java.generatedSources"/>
@@ -1,12 +1,10 @@
package ai.openidea.archives;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -18,8 +16,6 @@ import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.ProjectUtils;
import org.eclipse.lsp4j.TextDocumentIdentifier;
/**
* Re-reads library archives replaced in place (a SNAPSHOT installed again keeps its path). The
@@ -30,17 +26,6 @@ import org.eclipse.lsp4j.TextDocumentIdentifier;
public final class RefreshArchivesCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
if ("openidea.java.updateProjectConfigurations".equals(command)) {
List<TextDocumentIdentifier> files = arguments.stream()
.filter(String.class::isInstance)
.map(uri -> new TextDocumentIdentifier((String) uri))
.toList();
Collection<IProject> projects = ProjectUtils.getProjectsFromDocumentIdentifiers(files);
if (!projects.isEmpty()) {
JavaLanguageServerPlugin.getProjectsManager().updateProjects(projects, true).join(0, monitor);
}
return null;
}
IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
model.refreshExternalArchives(null, monitor);
Set<IPath> archives = new HashSet<>();
+7 -73
View File
@@ -155,23 +155,6 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
});
}
/// Sends `event` to `peers` (failures ignored: a window may be closing) and then to `owner`,
/// whose result is returned. The event is serialised once; `send` gets each window's copy of the
/// JSON, which Tauri's `emit_to` would otherwise re-serialise per window (large for
/// diagnostics of a big file).
fn fan_out<T: serde::Serialize>(
event: &T,
peers: &[String],
owner: &str,
mut send: impl FnMut(&str, String) -> tauri::Result<()>,
) -> tauri::Result<()> {
let json = serde_json::to_string(event)?;
for peer in peers {
let _ = send(peer, json.clone());
}
send(owner, json)
}
impl EventSink for TauriSink {
fn emit(&self, event: IdeEvent) {
if matches!(
@@ -197,12 +180,13 @@ impl EventSink for TauriSink {
}
let result = match &self.window {
Some(label) => {
let peers = if matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }) {
Vec::new()
} else {
crate::windows::document_windows(&self.app, label)
};
fan_out(&event, &peers, label, |window, json| self.app.emit_str_to(window, IDE_EVENT, json))
for target in crate::windows::document_windows(&self.app, label)
.into_iter()
.filter(|_| !matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }))
{
let _ = self.app.emit_to(target.as_str(), IDE_EVENT, &event);
}
self.app.emit_to(label.as_str(), IDE_EVENT, &event)
}
None => self.app.emit(IDE_EVENT, &event),
};
@@ -256,56 +240,6 @@ mod tests {
}
}
/// Counts how often it is serialised.
struct CountingEvent<'a> {
event: &'a IdeEvent,
serialised: AtomicUsize,
}
impl serde::Serialize for CountingEvent<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.serialised.fetch_add(1, Ordering::Relaxed);
self.event.serialize(serializer)
}
}
#[test]
fn fan_out_serialises_once_for_every_window() {
let event = diagnostics("/p/a.rs", "rust-analyzer", "unused");
let counting = CountingEvent { event: &event, serialised: AtomicUsize::new(0) };
let peers: Vec<String> = (1..=7).map(|n| format!("comparison-project-1-{n}")).collect();
let mut sent = Vec::new();
fan_out(&counting, &peers, "project-1", |window, json| {
sent.push((window.to_owned(), json));
Ok(())
})
.unwrap();
assert_eq!(counting.serialised.load(Ordering::Relaxed), 1);
let expected = serde_json::to_string(&event).unwrap();
let windows: Vec<&str> = sent.iter().map(|(window, _)| window.as_str()).collect();
assert_eq!(windows.len(), 8);
assert_eq!(windows.last(), Some(&"project-1"));
assert_eq!(windows[..7], peers.iter().map(String::as_str).collect::<Vec<_>>()[..]);
assert!(sent.iter().all(|(_, json)| json == &expected));
}
#[test]
fn fan_out_ignores_peer_failures_and_returns_the_owners_result() {
let event = task("indexing", false);
let peers = vec!["comparison-project-1-1".to_owned(), "comparison-project-1-2".to_owned()];
let mut reached = Vec::new();
let result = fan_out(&event, &peers, "project-1", |window, _| {
reached.push(window.to_owned());
if window == "project-1" { Err(tauri::Error::WebviewNotFound) } else { Err(tauri::Error::WindowNotFound) }
});
assert!(matches!(result, Err(tauri::Error::WebviewNotFound)));
assert_eq!(reached, ["comparison-project-1-1", "comparison-project-1-2", "project-1"]);
}
#[tokio::test]
async fn coalesces_diagnostics_by_path_and_source() {
let (sink, events) = setup();
-3
View File
@@ -286,7 +286,6 @@ fs_read_range always project_host bin
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_scratches_dir always project_host bindings sync
fs_set_writable always project_host bindings sync
fs_synchronize_directories always project_host bindings async
fs_undo_delete always project_host bindings async
@@ -602,8 +601,6 @@ sdk_python_interpreter outside_restricted project_host bin
sdk_python_packages outside_restricted project_host bindings async
sdk_python_pip outside_restricted project_host bindings async
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_sys_path outside_restricted project_host bindings async
sdk_python_user_path_problems outside_restricted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
+5 -43
View File
@@ -680,7 +680,7 @@ export const commands = {
* `charset` (writes the BOM for `utf-8-bom` / UTF-16).
*/
fsCreateFile: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file", { path })),
fsCreateFileBytes: (path: string, data: IpcBytes) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
/** Moving to the trash can take a while (large trees): kept off the main thread. */
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
@@ -707,11 +707,6 @@ export const commands = {
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/**
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
* keeps its scratches on the server, where its file commands run.
*/
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
/**
* Toggle Read-only Attribute: sets the writable bit (and the open document's
* state). Returns whether the file is read-only now.
@@ -1646,11 +1641,8 @@ export const commands = {
* with the Maven / Gradle dependency jars of the build model.
*/
sdkProjectLibraries: (request: RequestId, onGroups: Channel<LibraryGroup[]>) => typedError<LibraryGroup[], IdeError>(__TAURI_INVOKE("sdk_project_libraries", { request, onGroups })),
/**
* Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
* `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
*/
sdkPythonCreateVenv: (tool: VenvTool, base: string, location: string, installPackages: boolean, request: RequestId, onOutput: Channel<string>) => typedError<Sdk, IdeError>(__TAURI_INVOKE("sdk_python_create_venv", { tool, base, location, installPackages, request, onOutput })),
/** Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`. */
sdkPythonCreateVenv: (tool: VenvTool, base: string, location: string, request: RequestId, onOutput: Channel<string>) => typedError<Sdk, IdeError>(__TAURI_INVOKE("sdk_python_create_venv", { tool, base, location, request, onOutput })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run. */
@@ -1678,13 +1670,6 @@ export const commands = {
sdkPythonPip: (python: string, requirement: string, uninstall: boolean, upgrade: boolean, request: RequestId, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("sdk_python_pip", { python, requirement, uninstall, upgrade, request, onOutput })),
/** The Python interpreters of the recently opened projects, each with its project. */
sdkPythonProjectInterpreters: () => typedError<ProjectInterpreter[], IdeError>(__TAURI_INVOKE("sdk_python_project_interpreters")),
/** `sys.path` of the interpreter `python`, for All Interpreters › Show Paths. */
sdkPythonSysPath: (python: string, request: RequestId) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("sdk_python_sys_path", { python, request })),
/**
* 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.
*/
sdkPythonUserPathProblems: (paths: string[]) => typedError<(UserPathProblem | null)[], IdeError>(__TAURI_INVOKE("sdk_python_user_path_problems", { paths })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -1833,7 +1818,7 @@ export const commands = {
* to start the shell takes tens of milliseconds, a frozen UI if run there.
*/
termSpawn: (options: TerminalOptions, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("term_spawn", { options, onOutput })),
termStoreImage: (id: TerminalId, data: IpcBytes, mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termStoreImage: (id: TerminalId, data: number[], mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
/**
* Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
@@ -2544,8 +2529,6 @@ chosen: string | null } | { type: "thought"; text: string;
startedMs?: number | null } | { type: "tool"; id: string; title: string;
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
kind: string; status: AgentToolStatus; locations: IpcPath[];
/** Images returned by the tool, kept separately from its truncated text. */
images?: AgentImage[];
/** Text the tool reported (command output…), truncated. */
output: string | null; diffs: AgentToolDiff[];
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
@@ -8140,8 +8123,6 @@ export type InlayHint = {
* their values concatenate to `label`.
*/
parts: InlayLabelPart[],
/** The edits that turn the hint into code (an annotation and any import it needs). */
textEdits: TextEdit[],
};
/** Editor › Inlay Hints. */
@@ -8383,9 +8364,6 @@ export type InvalidateCachesOptions = {
buildCaches?: boolean,
};
/** A binary argument or result of an IPC command. */
export type IpcBytes = string;
/** A path field of an IPC type. */
export type IpcPath = string;
@@ -9217,8 +9195,6 @@ export type LogcatLine = {
};
export type 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";
@@ -11395,11 +11371,6 @@ export type PythonSettings = {
hideOtherProjectInterpreters?: boolean,
/** Show each interpreter's path under its name on the interpreters page. */
showInterpreterPaths?: boolean,
/**
* Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
* by interpreter executable; absolute or `~/`.
*/
interpreterPaths?: { [key in string]: string[] },
};
/** Color Scheme › Language Defaults › Rainbow brackets: which delimiters are coloured. */
@@ -13682,13 +13653,6 @@ export type UpstreamTracking = {
branch: string,
};
/** Why a folder added to an interpreter's paths stays off the import path. */
export type UserPathProblem =
/** Not an existing folder. */
"missing" |
/** Not absolute or `~/`, or it holds the separator of `PYTHONPATH`. */
"invalid";
export type Variable = Variable_Serialize | Variable_Deserialize;
export type Variable_Deserialize = {
@@ -13793,9 +13757,7 @@ export type VenvTool =
/** `poetry env use <base>` in the project, then `poetry env info --path`. */
"poetry" |
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
"conda" |
/** `pipenv --python <base>` in the project (pipenv must be on PATH). */
"pipenv";
"conda";
/** What a view or custom editor shows. */
export type View = {
+2 -2
View File
@@ -172,10 +172,10 @@ it.each([
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
+2 -10
View File
@@ -238,13 +238,11 @@ function buildDecorations(state: EditorState): DecorationSet {
const lensTheme = EditorView.theme({
// IDEA paints code vision with the colour scheme's Inline hints attribute.
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
".cm-openidea-lens": {
display: "flex",
alignItems: "center",
gap: "12px",
minHeight: "16px",
height: "16px",
color: "var(--fg-inlay, var(--fg-muted))",
WebkitUserSelect: "none",
userSelect: "none",
@@ -278,10 +276,7 @@ const lensTheme = EditorView.theme({
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
// long one cannot stretch across the whole window first.
maxWidth: "min(60ch, 50vw)",
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
// inks above or below its em box (CJK fallback fonts) still shows whole.
overflowX: "clip",
overflowY: "visible",
overflow: "hidden",
pointerEvents: "auto",
},
".cm-openidea-lensItem": {
@@ -298,9 +293,6 @@ const lensTheme = EditorView.theme({
fontFamily: "var(--font-ui)",
fontSize: "calc(1em - 1px)",
},
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
// editor's line height, which `font: inherit` brings along.
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
".cm-openidea-lensAction": { cursor: "pointer" },
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
".cm-openidea-lensIcon-run": { color: "var(--success)" },
+7 -4
View File
@@ -1,9 +1,12 @@
import { toBase64 } from "@/platform/base64";
// Keep binary conversion off the editor thread, including for large clipboard images.
self.onmessage = async (event: MessageEvent<Blob>) => {
self.onmessage = async (event: MessageEvent<Blob | string>) => {
try {
self.postMessage({ data: toBase64(new Uint8Array(await event.data.arrayBuffer())) });
const source = event.data;
const data =
typeof source === "string"
? Array.from(atob(source.slice(source.indexOf(",") + 1)), (byte) => byte.charCodeAt(0))
: Array.from(new Uint8Array(await source.arrayBuffer()));
self.postMessage({ data });
} catch (error) {
self.postMessage({ error: String(error) });
}
-82
View File
@@ -1,82 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
let view: EditorView;
afterEach(() => view.destroy());
function expand(snippet: string) {
view = new EditorView({
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
parent: document.body,
});
applySnippet(view, [{ from: 0, to: 0, snippet }]);
}
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
const doc = () => view.state.doc.toString();
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
describe("linked snippets", () => {
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
expect(selected()).toEqual(["x"]);
expect(view.state.selection.main.from).toBe(0);
type("name");
expect(doc()).toBe("name/name y/y");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["y"]);
expect(view.state.selection.main.from).toBe("name/name ".length);
type("label");
expect(doc()).toBe("name/name label/label");
});
it("tracks adjacent empty occurrences and the next variable independently", () => {
expand("${1}${1}${2:end}${0}");
expect(selected()).toEqual([""]);
type("x");
type("y");
expect(doc()).toBe("xyxyend");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["end"]);
type("!");
expect(doc()).toBe("xyxy!");
});
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
expand("${1:x}/${1:x}${0}");
if (key === "Escape") {
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
}
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
const { head } = view.state.selection.main;
expect(head).toBe(key === "Escape" ? 1 : doc().length);
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
expect(doc()).toBe("changed/x");
});
it("keeps a repeated last placeholder active until the end of the snippet", () => {
expand("${1:one} ${2:two}/${2:two}");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["two"]);
type("new");
expect(doc()).toBe("one new/new");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
it("keeps fields linked after a separate edit before the snippet", () => {
expand("call(${1:arg}, ${1:arg})${0}");
const prefix = "import call;\n";
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
expect(selected()).toEqual(["arg"]);
type("value");
expect(doc()).toBe(prefix + "call(value, value)");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
});
-346
View File
@@ -1,346 +0,0 @@
import {
clearSnippet,
closeCompletion,
completionStatus,
pickedCompletion,
snippet,
type Completion,
} from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
ChangeSet,
EditorSelection,
EditorState,
MapMode,
Prec,
StateEffect,
StateField,
Text,
type ChangeSpec,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
import { isExternalChange } from "@/editor/api";
interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface SnippetRange {
from: number;
to: number;
field: number;
}
interface Segment extends SnippetRange {
site: number;
primary: boolean;
}
interface ActiveSnippet {
segments: readonly Segment[];
active: number;
last: number;
mainSite: number;
completion: boolean;
}
const setSnippet = StateEffect.define<ActiveSnippet | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
function primarySegments(value: ActiveSnippet, field = value.active) {
return value.segments.filter((segment) => segment.field === field && segment.primary);
}
function contains(range: SnippetRange, from: number, to: number): boolean {
return range.from <= from && to <= range.to;
}
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
const primaries = primarySegments(value);
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
}
const fields = StateField.define<ActiveSnippet | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((effect) => effect.is(setSnippet));
if (next) return next.value;
if (!value) return null;
if (tr.docChanged) {
const segments: Segment[] = [];
for (const segment of value.segments) {
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
segments.push({ ...segment, from, to });
}
value = { ...value, segments };
}
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
},
provide: (field) =>
EditorView.decorations.from(field, (value) =>
value
? Decoration.set(
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
true,
)
: Decoration.none,
),
});
// Keep the edit and its mirrors in one history entry.
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
const value = tr.startState.field(fields, false);
if (
!value ||
!tr.docChanged ||
isExternalChange(tr) ||
tr.isUserEvent("undo") ||
tr.isUserEvent("redo") ||
tr.effects.some((effect) => effect.is(setSnippet))
)
return tr;
const primaries = primarySegments(value);
const edited = new Map<Segment, number>();
let outside = false;
let touchesOtherSegment = false;
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
const segment = primaries.find((range) => contains(range, from, to));
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
else {
outside = true;
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
}
}, true);
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
const changes: ChangeSpec[] = [];
const replacements = new Map<number, Text>();
let typedOffset = 0;
let mirrorOffset = 0;
// Map in source order so neighboring stops keep their own boundaries even when they touch.
const segments = value.segments.map((segment) => {
const start = segment.from + typedOffset;
const from = start + mirrorOffset;
let length = segment.to - segment.from;
const delta = edited.get(segment);
if (delta !== undefined) {
length += delta;
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
typedOffset += delta;
} else if (segment.field === value.active && !segment.primary) {
const insert = replacements.get(segment.site);
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
changes.push({ from: start, to: start + length, insert });
mirrorOffset += insert.length - length;
length = insert.length;
}
}
return { ...segment, from, to: from + length };
});
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
const next = { ...value, segments };
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
});
function clearLinkedSnippet(view: EditorView): boolean {
if (!view.state.field(fields, false)) return false;
view.dispatch({ effects: setSnippet.of(null) });
return true;
}
export const escapeSnippet: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearLinkedSnippet(view) || clearSnippet(view);
};
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
return EditorSelection.create(
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
value.mainSite,
);
}
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
if (active < 0 || active > value.last) return false;
view.dispatch({
selection: fieldSelection(value, active),
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
const value = state.field(fields, false);
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
}
export const nextLiveSnippetField: Command = (view) => {
const value = view.state.field(fields, false);
return !!value && !value.completion && selectField(view, value, value.active + 1);
};
const linkedSnippetExtension = [
fields,
mirrorEdits,
Prec.highest(
keymap.of([
{
key: "Tab",
run: (view) => {
const value = view.state.field(fields);
return (
!!value &&
!view.state.readOnly &&
completionStatus(view.state) !== "active" &&
selectField(view, value, value.active + 1)
);
},
shift: (view) => {
const value = view.state.field(fields);
return !!value && selectField(view, value, value.active - 1);
},
},
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
]),
),
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const segment = value.segments.find((range) => contains(range, pos, pos));
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
},
}),
];
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
return tr.effects
.map(({ value }) => value)
.find((value) => {
return value && typeof value.active === "number" && Array.isArray(value.ranges);
});
}
export function snippetFieldMoved(tr: Transaction): number | undefined {
const linked = tr.effects.find((effect) => effect.is(setSnippet));
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
return codeMirrorSnippet(tr)?.active;
}
/** Render with CodeMirror to keep its snippet syntax and indentation. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
const state = EditorState.create({
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
selection: EditorSelection.cursor(to),
extensions: [indentUnit.of(source.facet(indentUnit))],
});
let insert = Text.empty;
let ranges: SnippetRange[] = [];
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
snippet(site.snippet + "#{}")(
{
state,
dispatch(tr) {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
},
},
null,
from,
to,
);
const end = ranges.at(-1);
const seen = new Set<number>();
const segments = ranges.slice(0, -1).map((range) => {
const primary = !seen.has(range.field);
seen.add(range.field);
return { ...range, primary };
});
return { ...site, offset: from, insert, segments, end };
}
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
const { state } = view;
const { main } = state.selection;
const entries = sites.map((site) =>
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
);
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
const { snippet: source, from, to } = sites[0]!;
clearLinkedSnippet(view);
snippet(source)(view, completion, from, to);
return;
}
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
const needsEnd = entries.some(({ segments }) =>
segments.some((segment) => segment.field === last && !segment.primary),
);
if (needsEnd) last++;
const segments = entries.flatMap((entry, site) => {
const offset = changes.mapPos(entry.from, -1) - entry.offset;
const ranges = [...entry.segments];
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
});
const value = {
segments,
active: 0,
last,
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
completion: !!completion,
};
clearSnippet(view);
view.dispatch({
changes,
selection: fieldSelection(value, 0),
effects: [
setSnippet.of(last > 0 ? value : null),
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
],
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
userEvent: completion ? "input.complete" : undefined,
scrollIntoView: true,
});
}
+4 -112
View File
@@ -68,27 +68,15 @@ function type(view: EditorView, text: string) {
);
}
/** One Backspace at every caret, or over every selection. */
/** One Backspace before every caret. */
function backspace(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => {
const from = r.empty ? Math.max(0, r.head - 1) : r.from;
return { changes: { from, to: r.to }, range: EditorSelection.cursor(from) };
}),
{ userEvent: "delete.backward" },
);
}
/** One Delete after every caret. */
function deleteForward(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => ({
changes: { from: r.head, to: Math.min(state.doc.length, r.head + 1) },
range: EditorSelection.cursor(r.head),
changes: { from: Math.max(0, r.head - 1), to: r.head },
range: EditorSelection.cursor(Math.max(0, r.head - 1)),
})),
{ userEvent: "delete.forward" },
{ userEvent: "delete.backward" },
);
}
@@ -204,84 +192,6 @@ describe("linked html tags", () => {
expect(closing.state.doc.toString()).toBe("<div>content</di>v>");
});
// #5314: removing a tag piece by piece is a deletion, not a rename. Once its `>` (or `</`)
// is gone the tag is incomplete, and the name edits after that must not follow.
describe("deleting a whole tag", () => {
it("leaves the opening tag alone while the closing tag is backspaced away", () => {
const v = make("<div>x</div>|");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(show(v)).toBe("<div>x|");
});
it("leaves the closing tag alone while the opening tag is backspaced away", () => {
const v = make("<div>|x</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|x</div>");
});
it("leaves the opening tag alone when the closing tag is deleted forwards", () => {
const v = make("<div>x|</div>\n<p>y</p>");
for (let i = 0; i < "</div>".length; i++) deleteForward(v);
expect(v.state.doc.toString()).toBe("<div>x\n<p>y</p>");
});
it("leaves the closing tag alone while an opening tag followed by children is backspaced away", () => {
const v = make("<div>|\n <span>y</span>\n</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|\n <span>y</span>\n</div>");
const inline = make("<div>|<span>y</span></div>");
for (let i = 0; i < "<div>".length; i++) backspace(inline);
expect(show(inline)).toBe("|<span>y</span></div>");
});
it("leaves the other tag alone when a selection covering a tag is deleted", () => {
const v = make("<div>x[</div>]");
backspace(v);
expect(show(v)).toBe("<div>x|");
const open = make("[<div>]x</div>");
backspace(open);
expect(show(open)).toBe("|x</div>");
});
it("leaves the other tag alone when a cut runs from inside the name past the tag", () => {
const v = make("<div>x</d[iv>\n]<p>y</p>");
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x</d<p>y</p>");
});
it("does not rename into or out of a tag that lost its `>`", () => {
const v = make("<div|>x</div");
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</div");
const open = make("<div\n x</di|v>");
backspace(open);
expect(open.state.doc.toString()).toBe("<div\n x</dv>");
});
it("deletes the closing tags at every caret, leaving the opening tags alone", () => {
const v = make("<p>a</p>|\n<b>c</b>|");
for (let i = 0; i < "</p>".length; i++) backspace(v);
expect(show(v)).toBe("<p>a|\n<b>c|");
});
it("undo brings back the deleted closing tag and keeps the opening one", () => {
const v = make("<div>x[</div>]", history());
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x");
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe("<div>x</div>");
});
it("still renames after the `>` is typed back", () => {
const v = make("<div>x</div|");
type(v, ">");
expect(v.state.doc.toString()).toBe("<div>x</div>");
v.dispatch({ selection: { anchor: "<div".length } });
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</divs>");
});
});
it("undoes the pair as one step and redoes it", () => {
const v = make("<div|></div>", history());
type(v, "x");
@@ -309,12 +219,6 @@ describe("linked html tags", () => {
type(v, "s");
expect(v.state.doc.toString()).toBe('<divs class="a">x</divs>');
});
it(`leaves the opening tag alone while the closing tag is backspaced away in ${name}`, () => {
const v = makeWith([language(), linkedTags], '<div class="a">x</div>|');
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe('<div class="a">x');
});
}
});
@@ -357,18 +261,6 @@ describe("linked html tags", () => {
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
});
it("leaves the other tag alone while a tag is backspaced away", () => {
const v = tsx("const a = <div>x</div>|;");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe("const a = <div>x;");
const m = tsx("const a = (\n <div>|\n <span>y</span>\n </div>\n);");
for (let i = 0; i < "<div>".length; i++) backspace(m);
expect(m.state.doc.toString()).toBe("const a = (\n \n <span>y</span>\n </div>\n);");
const w = tsx("const a = <Foo>|x</Foo>;");
for (let i = 0; i < "<Foo>".length; i++) backspace(w);
expect(w.state.doc.toString()).toBe("const a = x</Foo>;");
});
it("undoes both tags in one step", () => {
const v = tsx("const a = <div|></div>;");
type(v, "x");
+7 -17
View File
@@ -10,9 +10,9 @@
* A transaction whose change lies inside one tag's name is extended with
* the same edit at the same offset in the counterpart's name — one
* transaction, so undo takes both back together. Without a matching tag (void
* and self-closing tags, unclosed elements, a stray close tag), with either tag
* missing its `>` (a tag being deleted piece by piece), or with the two names
* already different (malformed markup) nothing follows: the tags stay as they are.
* and self-closing tags, unclosed elements, a stray close tag) or with the two
* names already different (malformed markup) nothing follows: the tags stay as
* they are.
*/
import { EditorState, type Extension, type Transaction } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";
@@ -39,31 +39,21 @@ function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null
return null;
}
/**
* Whether a tag still ends in its `>`. A tag that lost it — `</div` while Backspace
* works through `</div>` — is being deleted, not renamed.
*/
function isComplete(tag: SyntaxNode | null): tag is SyntaxNode {
const last = tag?.lastChild?.name;
return last === "EndTag" || last === "JSXEndTag";
}
/** The matching tag's name of the same element, or null without one or while either tag is incomplete. */
/** The matching tag's name of the same element, or null without one. */
function counterpartName(name: SyntaxNode): SyntaxNode | null {
const tag = name.parent;
const element = tag?.parent;
if (!isComplete(tag) || !element) return null;
if (!tag || !element) return null;
if (element.name === "JSXElement") {
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
if (!isComplete(other)) return null;
for (let c = other.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
return null;
}
if (element.name !== "Element") return null;
const other = element.getChild(
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
);
return isComplete(other) ? other.getChild("TagName") : null;
return other?.getChild("TagName") ?? null;
}
/** Insertions at a name's edge must extend the name; structural characters end it. */
+8 -22
View File
@@ -3,7 +3,6 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { history, undo } from "@codemirror/commands";
import { IpcError, commands } from "@/platform/ipc";
import { handleFileDrop } from "@/workbench/fileDrop";
import { imageName, imageTarget, markdownImages, relativeImagePath, saveImage } from "./markdownImages";
const views: EditorView[] = [];
@@ -39,7 +38,9 @@ describe("Markdown images", () => {
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockResolvedValue(null);
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", "AP8=", create)).toBe("![](assets/photo-2.png)");
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", [0, 255], create)).toBe(
"![](assets/photo-2.png)",
);
expect(create.mock.calls.map(([path]) => path)).toEqual([
"/p/docs/assets/photo.png",
"/p/docs/assets/photo-1.png",
@@ -48,7 +49,7 @@ describe("Markdown images", () => {
});
it("does not retry permission failures", async () => {
const create = vi.fn().mockRejectedValue(new IpcError({ kind: "permissionDenied", message: "denied" }));
await expect(saveImage("/p/a.md", "assets", "a.png", "", create)).rejects.toThrow("denied");
await expect(saveImage("/p/a.md", "assets", "a.png", [], create)).rejects.toThrow("denied");
expect(create).toHaveBeenCalledTimes(1);
});
it("computes nested paths and encodes spaces and Markdown delimiters", () => {
@@ -81,10 +82,10 @@ describe("Markdown images", () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
@@ -97,31 +98,16 @@ describe("Markdown images", () => {
paste(editor, [new File(["png"], "image.png", { type: "image/png" })]);
await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1));
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
});
it("writes the base64 from a native image drop directly", async () => {
const invoke = vi.fn().mockResolvedValue("data:image/png;base64,AP8=");
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const editor = view();
vi.spyOn(editor, "posAtCoords").mockReturnValue(7);
await handleFileDrop(["/source/photo.png"], 0, 0);
expect(invoke).toHaveBeenCalledWith("fs_read_image", { path: "/source/photo.png" }, undefined);
await vi.waitFor(() => expect(create).toHaveBeenCalledWith("/project/docs/assets/photo.png", "AP8="));
expect(editor.state.doc.toString()).toBe("before ![](assets/photo.png)after");
});
it("inserts a paste as one isolated undo step and tracks edits during saving", async () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: string } }) => void;
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
+4 -7
View File
@@ -65,8 +65,8 @@ export async function saveImage(
markdown: string,
folder: string,
name: string,
data: string,
create = (path: string, base64: string) => call(commands.fsCreateFileBytes(path, base64)),
data: number[],
create = (path: string, bytes: number[]) => call(commands.fsCreateFileBytes(path, bytes)),
): Promise<string> {
const dot = name.lastIndexOf(".");
const stem = dot > 0 ? name.slice(0, dot) : name;
@@ -82,15 +82,12 @@ export async function saveImage(
}
}
/** The image as base64, the form `fsCreateFileBytes` takes. */
function imageBytes(blob: Blob | string): Promise<string> {
function imageBytes(blob: Blob | string): Promise<number[]> {
if ((typeof blob === "string" ? blob.length * 0.75 : blob.size) > MAX_IMAGE_BYTES)
return Promise.reject(new Error(tx("Image exceeds 16 MB.")));
// The data URL from fs_read_image already contains standard base64.
if (typeof blob === "string") return Promise.resolve(blob.slice(blob.indexOf(",") + 1));
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./imageBytes.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (event: MessageEvent<{ data: string; error?: string }>) => {
worker.onmessage = (event: MessageEvent<{ data: number[]; error?: string }>) => {
worker.terminate();
if (event.data.error) reject(new Error(event.data.error));
else resolve(event.data.data);
-41
View File
@@ -8,7 +8,6 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerTextEditorWrapper,
setProjectViewLead,
useProjectViewLead,
@@ -580,46 +579,6 @@ describe("EditorController", () => {
useProject.setState({ project: null, settings: null });
});
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
const dispose = registerActions(
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
id,
title: id,
run: () => undefined,
})),
);
const links = registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
});
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const s = useTabs.getState();
const pane = s.panes[s.activePane]!;
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
(i) => i.label === "Copy Path/Reference…",
)!.submenu!;
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"GitHub Link",
]);
} finally {
dispose();
links();
useProject.setState({ project: null, settings: null });
}
});
it.each(["editor", "tab"])(
"offers grouped Git actions in the %s menu and preserves action enablement",
async (menu) => {
+2 -6
View File
@@ -52,8 +52,7 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
@@ -1300,7 +1299,7 @@ export class EditorController implements SlotHost {
* every tab showing it becomes a file tab.
*/
private async saveUntitled(model: import("./model/document").DocModel): Promise<boolean> {
const path = await chooseSavePath({
const path = await saveFileDialog({
title: tx("Save As"),
defaultPath: this.saveAsSuggestion(model),
filters: await languageFilters(),
@@ -2325,9 +2324,6 @@ export class EditorController implements SlotHost {
},
] as MenuItem[])
: []),
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
{ kind: "separator" },
...menuGroupItems("copyPath", { paths: [path] }),
],
},
{ kind: "separator" },
+1 -39
View File
@@ -1,10 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { useProject } from "@/platform/project";
import { registerAction } from "@/platform/actions";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
@@ -59,42 +57,6 @@ describe("editor font zoom (active editor by default, all editors when configure
expect(zoomOf(view)).toBe(0);
});
it("zooms when no enabled keymap action claims the gesture", () => {
const original = useKeymap.getState();
const view = makeView();
const run = vi.fn();
let enabled = true;
const unregister = registerAction({ id: "test.wheel", title: "Test", enabled: () => enabled, run });
const uninstall = installKeyboardDispatcher(window);
useKeymap.setState({ overrides: { "test.wheel": ["Ctrl+WheelUp"] } });
const scroll = (deltaY: number) => {
const event = new WheelEvent("wheel", {
bubbles: true,
cancelable: true,
ctrlKey: true,
deltaY,
deltaMode: WheelEvent.DOM_DELTA_LINE,
});
view.contentDOM.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
};
try {
scroll(-1);
expect(run).toHaveBeenCalledOnce();
expect(zoomOf(view)).toBe(0);
scroll(1);
expect(zoomOf(view)).toBe(-1);
enabled = false;
scroll(-1);
expect(run).toHaveBeenCalledOnce();
expect(zoomOf(view)).toBe(0);
} finally {
uninstall();
unregister();
useKeymap.setState(original);
}
});
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
const first = makeView();
-1
View File
@@ -11,7 +11,6 @@ import { VirtualBanner } from "./view/Banner";
const ipc = vi.hoisted(() => ({ support: vi.fn(), sources: vi.fn(), cancel: vi.fn(), choose: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { lspCanDownloadSources: ipc.support, lspLibrarySources: ipc.sources, cancelRequest: ipc.cancel },
}));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: ipc.choose }));
+2 -3
View File
@@ -1,7 +1,6 @@
import { useEffect, useState } from "react";
import { create } from "zustand";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -27,8 +26,8 @@ async function retrieve(path: string, choose: boolean) {
try {
let sources: string | null = null;
if (choose) {
const selected = await choosePath({
directory: false,
const { open } = await import("@/platform/dialog");
const selected = await open({
title: tx("Choose Sources…"),
filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }],
});
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff. Show more