Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai d8377952f5 test: fix the Windows ui_points and debugger stop tests, and a tight plugin budget
- ui_points: a Windows checkout has CRLF line ends, so removing
  "width = 110\n" from the fixture did nothing and the missing-width case
  passed. The fixture text is normalized to LF first.
- ide-dap: the fake adapter stops at a breakpoint after launch, and since
  Stop kills a suspended program's tree at once (#3658), the Windows stop
  test no longer saw the wait it checks. The adapter now continues right
  after that stop, so Stop meets a running program.
- plugin_data_tools: database_calls_enforce_grants… ran its plugin commands
  under a 250 ms budget it does not test; a slow runner's first call timed
  out. It gets 10 s.
2026-11-17 06:23:39 +08:00
154 змінених файлів з 394 додано та 3491 видалено

No files matched your search

Створено
+45 -45
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"dunce",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dunce",
"encoding_rs",
@@ -4254,7 +4254,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-run",
@@ -4268,7 +4268,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4297,7 +4297,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4333,7 +4333,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"serde",
@@ -4346,7 +4346,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4367,7 +4367,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4379,7 +4379,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4392,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"criterion",
"ide-core",
@@ -4410,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4483,7 +4483,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4502,7 +4502,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"criterion",
@@ -4524,7 +4524,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4536,7 +4536,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"encoding_rs",
"futures",
@@ -4553,7 +4553,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"libc",
"tempfile",
@@ -4562,7 +4562,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"futures",
"serde",
@@ -4573,7 +4573,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"criterion",
@@ -4631,7 +4631,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dunce",
"encoding_rs",
@@ -4659,7 +4659,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"bytes",
"dunce",
@@ -4678,7 +4678,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"futures",
"ide-core",
@@ -4701,7 +4701,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"dunce",
@@ -4724,7 +4724,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4738,7 +4738,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dunce",
"futures",
@@ -4758,7 +4758,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dunce",
"encoding_rs",
@@ -4782,7 +4782,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-tools",
@@ -4798,7 +4798,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dunce",
"flate2",
@@ -4821,7 +4821,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"criterion",
"encoding_rs",
@@ -4842,7 +4842,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"parking_lot",
@@ -4855,7 +4855,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4880,7 +4880,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-language",
@@ -4893,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"ide-language",
@@ -4908,7 +4908,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"ide-core",
"libc",
@@ -4921,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"criterion",
"ide-core",
@@ -4934,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"flate2",
"hex",
@@ -4955,7 +4955,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"dunce",
@@ -4976,7 +4976,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"chardetng",
"dunce",
@@ -5002,7 +5002,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5018,7 +5018,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"blake3",
"dunce",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.47"
version = "0.1.46"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.47"
version = "0.1.46"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+6 -11
Переглянути файл
@@ -72,8 +72,9 @@ async fn run_once(
config::add_client_options(&launch.id, &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let mut levels = BTreeMap::new();
let has_config = new.get("configOptions").is_some_and(Value::is_array);
if has_config && let Some(model) = model_option.and_then(|o| o.current.as_ref()) {
if new.get("configOptions").is_some_and(Value::is_array)
&& let Some(model) = model_option.and_then(|o| o.current.as_ref())
{
levels.insert(model.clone(), levels_for_model_from_slice(&options));
}
if let Some(selected) = selected_model
@@ -87,7 +88,7 @@ async fn run_once(
updates.config.lock().session = Some(session.to_owned());
let response: Value = conn.request(method, params, None).await.map_err(discovery_error)?;
let settings = if let Some(settings) = selected_settings(&response, selected) {
Some(settings)
settings
} else {
tokio::time::timeout(CONFIG_UPDATE_TIMEOUT, async {
loop {
@@ -105,15 +106,9 @@ async fn run_once(
}
})
.await
.ok()
};
match settings {
Some(settings) => levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings)),
// An agent on the legacy `models` field that says nothing more: the model has
// no settings of its own, and switching to it must not fail.
None if !has_config => levels.insert(selected.to_owned(), Vec::new()),
None => return Err("The agent did not report settings for the selected model".to_owned()),
.map_err(|_| "The agent did not report settings for the selected model".to_owned())?
};
levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings));
}
let commands = updates
.commands
-27
Переглянути файл
@@ -774,33 +774,6 @@ async fn selected_model_uses_legacy_set_model_and_authoritative_notifications()
assert!(!catalog.thought_levels.contains_key("default"), "legacy model lists alone do not assert no controls");
}
#[tokio::test]
async fn selected_legacy_model_without_settings_has_no_levels_instead_of_failing() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false, Some("second")).unwrap();
harness
.next()
.await
.reply
.send(Ok(json!({
"sessionId": "discovery-only",
"models": { "currentModelId": "default", "availableModels": [
{ "modelId": "default", "name": "Default" }, { "modelId": "second", "name": "Second" }
] }
})))
.unwrap();
let selected = harness.next().await;
assert_eq!(selected.method, "session/set_model");
selected.reply.send(Ok(json!({}))).unwrap();
let catalog = completed(&mut events).await;
assert!(catalog.error.is_none(), "{:?}", catalog.error);
assert_eq!(catalog.thought_levels.get("second"), Some(&Vec::new()));
}
#[tokio::test]
async fn catalog_replacement_removes_selected_metadata_for_models_no_longer_listed() {
let tmp = tempfile::tempdir().unwrap();
+6 -22
Переглянути файл
@@ -47,20 +47,13 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
fs::write(
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
r#"gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
def dir = p.tasks.getByName('processResources').destinationDir
def manifest = new File({})
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
def resources = p.tasks.named('processResources')
p.tasks.register('openideaUpdateResources') {{
dependsOn resources
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
"#,
literal(&p.path),
@@ -179,16 +172,7 @@ mod tests {
assert_eq!(gradle.command, "/tools/gradlew");
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
assert!(
script.contains("processResources")
&& script.contains(".destinationDir\n")
&& script.contains("setText(dir.absolutePath")
);
// `register` is Gradle 4.9+ (#3864).
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
+3 -7
Переглянути файл
@@ -30,8 +30,7 @@ def processedResources = { Project p, s ->
def describe = { Project p ->
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
if (p.gradle.parent != null) m.build = identity(p.rootProject)
// Gradle 4.x has it as a convention property, not an extension.
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
def sets = p.extensions.findByName('sourceSets')
if (sets != null) {
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
// and sets whose folders the `idea` plugin lists as test sources.
@@ -52,12 +51,9 @@ def describe = { Project p ->
}
}
try {
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
def java = p.extensions.findByName('java')
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
def lv = java?.toolchain?.languageVersion?.getOrNull()
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
} catch (ignored) {}
println '@openidea-model\t' + JsonOutput.toJson(m)
}
+7 -26
Переглянути файл
@@ -172,25 +172,13 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
fs::write(
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
r#"gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
def war = p.tasks.getByName('war')
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
def manifest = new File({})
t.doLast {{
def file = archive instanceof File ? archive : archive.get().asFile
manifest.setText(file.absolutePath, 'UTF-8')
}}
def warTask = p.tasks.named('war')
p.tasks.register('openideaTomcatArtifact') {{
dependsOn warTask
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
"#,
groovy_literal(path),
@@ -282,7 +270,7 @@ mod tests {
assert_eq!(a.len(), 1);
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
@@ -309,14 +297,7 @@ mod tests {
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
assert!(script.contains(&format!("rootProject.project('{}')", module)));
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
assert!(
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
);
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
}
}
}
+5 -8
Переглянути файл
@@ -167,11 +167,10 @@ const GRADLE: &[&str] = &["gradle", "gradlew"];
/// Gradle's own JVM and the compiler's source encoding are untouched.
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
tasks.withType(JavaExec).configureEach {
defaultCharacterEncoding = 'UTF-8'
}
}
";
@@ -622,12 +621,10 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(s.contains("? tasks.configureEach(action) : tasks.all(action)"), "{s}");
}
#[test]
+6 -14
Переглянути файл
@@ -6,16 +6,11 @@ use ide_run::wrap::{self, program_name};
use std::path::Path;
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
def xml = p.tasks.getByName('jacocoTestReport').reports.xml
// `Report.required` is Gradle 6.1+, `enabled` is gone in 8.0.
if (xml.hasProperty('required')) xml.required.set(true) else xml.enabled = true
allprojects {
plugins.withId('java') {
apply plugin: 'jacoco'
tasks.withType(Test).configureEach { t -> t.finalizedBy(tasks.named('jacocoTestReport')) }
tasks.named('jacocoTestReport') { r -> r.reports { xml.required.set(true) } }
}
}
"#;
@@ -396,10 +391,7 @@ mod tests {
let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args[0], "--init-script");
let script = std::fs::read_to_string(&l.args[1]).unwrap();
assert!(script.contains("p.apply plugin: 'jacoco'"), "{script}");
// `Report.required` is Gradle 6.1+, `configureEach` 4.9+ (#3864).
assert!(script.contains("else xml.enabled = true") && script.contains(": tasks.all(action)"), "{script}");
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco"));
assert!(matches!(report, CoverageReportSpec::Jacoco { .. }));
}
-3
Переглянути файл
@@ -1624,7 +1624,6 @@ impl DebugManager {
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
Ok(())
}
@@ -1673,7 +1672,6 @@ impl DebugManager {
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
@@ -1785,7 +1783,6 @@ impl DebugManager {
.await;
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
-4
Переглянути файл
@@ -116,8 +116,6 @@ pub(crate) struct Session {
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
/// The last trace that finished, until the stop its records were read in ends.
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
@@ -283,7 +281,6 @@ impl Session {
jvm_memory: tokio::sync::Mutex::default(),
stream_tracer: parking_lot::Mutex::new(None),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
}
@@ -777,7 +774,6 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
+8 -64
Переглянути файл
@@ -88,32 +88,6 @@ pub enum TraceUnavailable {
},
}
/// A trace that finished. Its records keep their objects from being collected until the stop they
/// were read in ends; then the UI no longer shows them and [`release_done`] lets them go.
pub(crate) struct DoneTrace {
tracer: Arc<dyn StreamTracer>,
target: VmTarget,
id: TraceId,
}
/// The stop a finished trace was read in ended (a resume, a step, a `continued` event).
pub(crate) fn release_done(s: &Session) {
let Some(done) = s.stream_trace_done.lock().take() else { return };
let ended = s.ended.clone();
let session = s.id.0;
tokio::spawn(async move {
tokio::select! {
biased;
() = ended.cancelled() => {}
result = done.tracer.release(&done.target, done.id) => {
if let Err(e) = result {
tracing::debug!(session, trace = done.id, "releasing a finished stream trace: {e}");
}
}
}
});
}
/// The session's running trace; `id` is `None` until `arm` answers.
pub(crate) struct ActiveTrace {
tracer: Arc<dyn StreamTracer>,
@@ -207,30 +181,10 @@ pub(crate) async fn run(
if !s.suspended.get() {
return unavailable(TraceUnavailable::NotSuspended);
}
// The bundle releases the previous trace itself when this one arms.
s.stream_trace_done.lock().take();
static TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let token =
format!("{}-{}-{}", std::process::id(), s.id.0, TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let mut trace = Trace {
mgr,
s,
tracer: &*tracer,
target: &target,
thread_id,
progress,
token,
arm_sent: false,
id: None,
last: Counts::default(),
};
let mut trace =
Trace { mgr, s, tracer: &*tracer, target: &target, thread_id, progress, id: None, last: Counts::default() };
match trace.drive(plan, cancel).await {
Ok(run) => {
if let (TraceRun::Done { .. }, Some(id)) = (&run, trace.id) {
*s.stream_trace_done.lock() = Some(DoneTrace { tracer: tracer.clone(), target: target.clone(), id });
}
run
}
Ok(run) => run,
Err(run) => {
// A stop from now on is the user's to see.
set_running(s, false);
@@ -277,9 +231,6 @@ struct Trace<'a, P> {
target: &'a VmTarget,
thread_id: i64,
progress: &'a P,
/// Names the trace to the bundle before `arm` answers (see [`StreamTracer::release_armed`]).
token: String,
arm_sent: bool,
/// Set once `arm` answers.
id: Option<TraceId>,
last: Counts,
@@ -290,9 +241,8 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
async fn drive(&mut self, plan: &Value, cancel: &CancellationToken) -> Result<TraceRun, TraceRun> {
let (s, tracer, target) = (self.s, self.tracer, self.target);
self.report(TracePhase::Arming);
self.arm_sent = true;
let id = self
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET, &self.token))
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET))
.await?
.map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?;
self.id = Some(id);
@@ -363,20 +313,14 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
/// After a trace that ended early. Left to the bundle, an armed trace would keep every
/// breakpoint off and a parked one its thread suspended behind java-debug's back; the bundle
/// undoes either, or does so once a terminal still running returns. Not after a finished
/// trace: the records it unpins are the values the result shows ([`release_done`] does, once
/// that stop ends). An `arm` that never answered (it timed out) may still have armed: released
/// by its token.
/// trace: the records it unpins are the values the result shows.
async fn release(&self) {
let Some(id) = self.id else { return };
if self.s.ended.is_cancelled() {
return;
}
let work = match self.id {
Some(id) => self.tracer.release(self.target, id),
None if self.arm_sent => self.tracer.release_armed(self.target, &self.token),
None => return,
};
if let Ok(Err(e)) = self.until_ended(work).await {
tracing::debug!(session = self.s.id.0, trace = ?self.id, "stream trace release: {e}");
if let Ok(Err(e)) = self.until_ended(self.tracer.release(self.target, id)).await {
tracing::debug!(session = self.s.id.0, trace = id, "stream trace release: {e}");
}
}
-36
Переглянути файл
@@ -55,7 +55,6 @@ impl StreamTracer for FakeTracer {
_thread_id: i64,
_plan: &'a Value,
_budget: u32,
_token: &'a str,
) -> InspectFuture<'a, TraceId> {
self.record("arm", target);
let error = self.arm_error.lock().clone();
@@ -97,11 +96,6 @@ impl StreamTracer for FakeTracer {
self.record("release", target);
Box::pin(async { Ok(()) })
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, _token: &'a str) -> InspectFuture<'a, ()> {
self.record("releaseArmed", target);
Box::pin(async { Ok(()) })
}
}
fn collected() -> TraceCollected {
@@ -449,36 +443,6 @@ async fn a_finished_trace_is_not_released() {
assert!(!tracer.names().contains(&"release"), "{:?}", tracer.names());
}
#[tokio::test]
async fn a_finished_trace_is_released_once_the_program_runs_on() {
let h = harness(java_debug());
let tracer = FakeTracer::scripted([parked()]);
let id = stopped_java(&h, &tracer).await;
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Done { .. }));
h.manager.resume(id, 1).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !tracer.names().contains(&"release") {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the finished trace was not released");
assert_eq!(tracer.names().iter().filter(|n| **n == "release").count(), 1);
}
#[tokio::test]
async fn an_arm_without_a_reply_is_released_by_its_token() {
// The bundle may still finish arming after the reply timed out: its breakpoints would stay off.
let h = harness(java_debug());
let tracer = FakeTracer::scripted([]);
let id = stopped_java(&h, &tracer).await;
*tracer.arm_error.lock() = Some(InspectError::TimedOut);
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Failed { .. }));
assert_eq!(tracer.names(), ["arm", "releaseArmed"]);
}
#[tokio::test]
async fn refused_stop_leaves_the_outcome_to_wait() {
let h = harness(java_debug());
+2 -4
Переглянути файл
@@ -179,9 +179,7 @@ fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
}
fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
// `~/.psqlrc` could switch databases or change settings before the dump runs.
let mut args = vec!["--no-psqlrc".to_owned()];
args.extend((!file.is_empty()).then(|| format!("--file={file}")));
let mut args: Vec<String> = (!file.is_empty()).then(|| format!("--file={file}")).into_iter().collect();
args.extend(flag(o.single_transaction, "--single-transaction"));
args.extend(flag(o.stop_on_error, "--set=ON_ERROR_STOP=1"));
args
@@ -319,7 +317,7 @@ mod tests {
let options = DbPsqlOptions { single_transaction: true, stop_on_error: true };
assert_eq!(
args(DbToolJob::Psql { file: "/tmp/shop.sql".into(), options }),
["--no-psqlrc", "--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
["--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
);
}
+1 -23
Переглянути файл
@@ -237,7 +237,7 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
args.push(format!("--username={}", source.user.trim()));
}
if !source.database.is_empty() {
args.push(format!("--dbname={}", dbname_arg(&source.database)));
args.push(format!("--dbname={}", source.database));
}
// Without a terminal a password prompt would wait forever: fail instead.
args.push("--no-password".into());
@@ -271,16 +271,6 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
(args, env)
}
/// `--dbname` reads a connection string or URI as connection parameters: such a database name
/// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials.
fn dbname_arg(name: &str) -> String {
if name.contains('=') || name.starts_with("postgresql://") || name.starts_with("postgres://") {
format!("dbname='{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
} else {
name.to_owned()
}
}
/// How a tool is started: connection arguments, then the job's, and the environment.
pub struct Prepared {
pub args: Vec<String>,
@@ -414,18 +404,6 @@ mod tests {
assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS"));
}
#[test]
fn a_database_named_like_connection_parameters_stays_a_name() {
for (name, arg) in [
("host=evil.example dbname=p", r"--dbname=dbname='host=evil.example dbname=p'"),
(r"it's=\x", r"--dbname=dbname='it\'s=\\x'"),
("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"),
] {
let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() });
assert!(args.contains(&arg.to_owned()), "{args:?}");
}
}
#[test]
fn default_port_and_optional_fields() {
let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() };
-6
Переглянути файл
@@ -191,12 +191,6 @@ impl Host {
};
host.apply_proxy();
host.apply_added_jdks();
// Before any project starts jdtls; the deleting itself can take a while.
let unused =
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
if !unused.is_empty() {
std::thread::spawn(move || ide_sdk::jdtls_workspaces::remove(unused));
}
ops::agent::move_user_mcp_values(&host);
host
}
+2 -7
Переглянути файл
@@ -25,17 +25,12 @@ impl Scope {
} else {
call.root().join(given)
});
let roots: Vec<PathBuf> =
std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots()).collect();
// Before touching the file system: on Windows, resolving `\\host\share` signs in to that host.
if !ide_vfs::content_path_allowed(&path, &roots) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
let path = dunce::canonicalize(&path).unwrap_or(path);
if !path.is_dir() {
return Err(IdeError::not_found(format!("scope {raw} is not a directory")));
}
if !roots.iter().any(|root| path.starts_with(root)) {
let roots = std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots());
if !roots.into_iter().any(|root| path.starts_with(root)) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
Ok(Self(Some(path)))
+9 -19
Переглянути файл
@@ -883,20 +883,14 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let host = call.host();
let project = call.project().clone();
let indexing_before = project.index.status().indexing;
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
let pool = if scope.is_all() && dir.dir().is_none() {
limit + 1
} else {
((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL)
};
let found = {
let (project, q, dir) = (project.clone(), q.clone(), dir.dir().map(Path::to_path_buf));
host.blocking(move || {
Ok(match dir {
// Filtered in the index: a pool cut before the filter could miss every match.
Some(dir) => project
.index
.find_symbols_until(&q, ide_index::SymbolFilter::All, pool, &|p| p.starts_with(&dir), &|| false)
.unwrap_or_default(),
None => project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool),
})
})
.await?
let (project, q) = (project.clone(), q.clone());
host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await?
};
let mut items: Vec<SearchItem> = found
.into_iter()
@@ -916,14 +910,10 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let budget = MEDIUM_TIMEOUT.saturating_sub(started.elapsed());
let (symbols, out_of_time) = workspace_symbols(&call, &q, budget).await;
timed_out = out_of_time;
let mut roots = project.content_roots();
roots.extend(crate::mcp::tool::attached_projects(call.root()));
for (name, container, location) in symbols {
let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path));
// Project files (attached projects' too) obey `scope` and `paths`; library symbols
// are what was asked for.
let inside = location.uri.is_none()
&& (!Path::new(&path).is_absolute() || roots.iter().any(|r| location.path.starts_with(r)));
// Project files obey `scope` and `paths`; library symbols are what was asked for.
let inside = location.uri.is_none() && !Path::new(&path).is_absolute();
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
continue;
}
-1
Переглянути файл
@@ -65,7 +65,6 @@ pub async fn spell_check(
end: r.end,
kind: match r.kind {
SpellingKind::Comment => RegionKind::Comment,
SpellingKind::String if r.raw => RegionKind::RawString,
SpellingKind::String => RegionKind::String,
SpellingKind::Name => RegionKind::Name,
},
-4
Переглянути файл
@@ -379,10 +379,6 @@ fn ready(
},
};
let mut linked = link_trace(plan, &recording, collected.skipped_breakpoints);
// A stream made parallel before the chain's statement, which the bundle found so at run time.
if collected.sequentialized && !plan.sequentialize {
linked.banners.push(TraceBanner::Sequentialized);
}
if resumed_stops > 0 {
linked.banners.push(TraceBanner::BreakpointsResumed { count: resumed_stops });
}
-17
Переглянути файл
@@ -442,20 +442,3 @@ fn chain_info_steps_keep_modifiers() {
let found = chains_at(service(), &snap, &frame(1), true, true, &CancellationToken::new()).unwrap();
assert_eq!(found[0].info.steps, ["filter", "unordered", "map"]);
}
#[test]
fn ready_says_a_stream_found_parallel_at_run_time_ran_sequentially() {
let java = LanguageId::new("java");
let snap = Snapshot::text(&java, SOURCE);
let found = chains_at(service(), &snap, &frame(line_of("C_SPIKE")), true, true, &CancellationToken::new()).unwrap();
let Candidate { info, chain } = found.into_iter().next().unwrap();
let chain = chain.unwrap();
let plan = real_run_plan(&chain).unwrap();
assert!(!plan.sequentialize);
let collected = TraceCollected { sequentialized: true, ..spike_collected() };
let StreamTraceResult::Ready { banners, .. } = ready(info, &chain, &plan, collected, 9, 0) else {
panic!("not ready");
};
assert!(banners.contains(&TraceBanner::Sequentialized), "{banners:?}");
}
-22
Переглянути файл
@@ -1304,25 +1304,6 @@ pub async fn vcs_create_patch(
.await
}
/// The changes a commit with `options` would make in `repo`, as one patch (what Commit
/// commits: the index with the selection applied, partial files' chosen hunks only).
pub async fn vcs_pending_patch(
host: &Host,
window: &str,
repo: Option<PathBuf>,
options: CommitOptions,
) -> IdeResult<String> {
const MAX_PATCH: usize = 1 << 20;
let project = host.project(window)?;
blocking(move || {
project.with_repo_at(repo.as_deref(), |r| {
let changes = r.pending_changes(&options, MAX_PATCH, &|path| project.vcs_encoding(path, None))?;
Ok(changes.into_iter().filter_map(|c| c.diff).collect())
})
})
.await
}
pub async fn vcs_patch_preview(
host: &Host,
window: &str,
@@ -1682,9 +1663,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_create_patch", |c| async move {
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
});
d.add("vcs_pending_patch", |c| async move {
vcs_pending_patch(&c.host, &c.window, c.arg("repo")?, c.arg("options")?).await
});
d.add("vcs_patch_preview", |c| async move {
vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await
});
+3 -55
Переглянути файл
@@ -13,7 +13,6 @@
//! [[contributes.keymaps]]
//! command = "check"
//! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`)
//! # key = "Escape" + when = "…" # API 1.10: Escape in an editor that the IDE had no use for
//!
//! [[contributes.statusBar]]
//! id = "branch"
@@ -204,16 +203,8 @@ struct KeymapDecl {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
mac: Option<String>,
/// Only with an `Escape` binding (API 1.10): when the command clears something.
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
}
/// The one plain key a plugin may bind (API 1.10): in a focused editor, after the IDE's own uses of
/// Escape (popups, completion, rename, selection, extra carets, Vim) found nothing to do, like a
/// handler at the end of IDEA's EditorEscape chain.
const ESCAPE: &str = "Escape";
const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"];
const NAMED_KEYS: [&str; 22] = [
"Enter",
@@ -271,21 +262,9 @@ pub fn validate_binding(binding: &str) -> Result<(), String> {
pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: KeymapDecl = decode(KEYMAPS, decl)?;
declared_command(pkg, KEYMAPS, &d.command)?;
let escape = d.key == ESCAPE || d.mac.as_deref() == Some(ESCAPE);
if escape {
if d.key != ESCAPE || d.mac.as_deref().is_some_and(|m| m != ESCAPE) {
return Err("contributes.keymaps: an Escape binding is Escape on every platform".into());
}
pkg.manifest.needs_api("contributes.keymaps key = \"Escape\"", 10)?;
let when = d.when.as_deref().ok_or("contributes.keymaps: an Escape binding needs a `when` clause")?;
validate_when(when).map_err(|e| format!("contributes.keymaps: {e}"))?;
} else if d.when.is_some() {
return Err("contributes.keymaps: `when` is only for an Escape binding".into());
}
for binding in std::iter::once(&d.key).chain(&d.mac) {
if binding != ESCAPE {
validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?;
}
validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?;
if let Some(m) = &d.mac {
validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?;
}
Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?))
}
@@ -1135,37 +1114,6 @@ mod tests {
}
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
let manifest = ide_extension::Manifest::parse(&format!(
"id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='clear'\ntitle='Clear'"
))
.unwrap();
Package::new(manifest, std::path::PathBuf::from("/unused"))
};
let check = |api: &str, decl: &str| keymap(&pkg(api), toml::from_str(decl).unwrap());
let escape = "command='clear'\nkey='Escape'\nwhen='plugin.test.active'";
let ok = check("^1.10", escape).unwrap();
assert_eq!(ok.json["when"], "plugin.test.active");
assert!(check("^1.10", &format!("{escape}\nmac='Escape'")).is_ok());
for (api, decl, error) in [
("^1.9", escape, "1.10"),
("^1.10", "command='clear'\nkey='Escape'", "when"),
("^1.10", "command='clear'\nkey='Escape'\nwhen='a &&'", "when"),
("^1.10", &format!("{escape}\nmac='Meta+K'") as &str, "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nmac='Escape'\nwhen='x'", "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nwhen='x'", "only for an Escape"),
("^1.10", "command='clear'\nkey='Enter'", "needs Ctrl"),
("^1.10", "command='clear'\nkey='Shift+Escape'", "needs Ctrl"),
] {
let err = check(api, decl).unwrap_err();
assert!(err.contains(error), "{api} {decl}\n→ {err}");
}
// Other bindings are unchanged.
assert!(check("^1.9", "command='clear'\nkey='Ctrl+Alt+C'").is_ok());
}
#[test]
fn bindings_need_a_modifier() {
for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] {
-1
Переглянути файл
@@ -286,7 +286,6 @@ impl Host {
lsp.set_prepare_hook(Box::new(move |cfg, _, cancel| {
let effective = settings.effective();
if cfg.name == "jdtls" {
ide_sdk::jdtls_workspaces::mark_used(cfg);
crate::java_runtime::prepare(
cfg,
&data_dir,
-21
Переглянути файл
@@ -481,27 +481,6 @@ async fn scope_limits_the_query_tools_to_a_directory() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_scoped_symbol_search_finds_matches_past_the_unscoped_ones() {
let h = Harness::new();
std::fs::create_dir_all(h.root.join("many")).unwrap();
for i in 0..60 {
std::fs::write(h.root.join(format!("many/m{i:02}.rs")), "pub fn pool_marker() {}\n").unwrap();
}
std::fs::create_dir_all(h.root.join("zz")).unwrap();
std::fs::write(h.root.join("zz/last.rs"), "pub fn pool_marker() {}\n").unwrap();
// Files written after the project opened reach the index through the watcher.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while h.json("search_symbol", json!({"q":"pool_marker","limit":100})).await["items"].as_array().map_or(0, Vec::len)
< 61
{
assert!(std::time::Instant::now() < deadline, "the files were never indexed");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let found = h.json("search_symbol", json!({"q":"pool_marker","scope":"zz","limit":1})).await;
assert_eq!(found["items"][0]["filePath"], "zz/last.rs", "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
let h = Harness::new();
+1 -6
Переглянути файл
@@ -64,15 +64,13 @@ pub struct TraceCollected {
}
pub trait StreamTracer: Send + Sync {
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. `token`
/// names the trace for [`release_armed`](Self::release_armed) when no reply arrives.
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept.
fn arm<'a>(
&'a self,
target: &'a VmTarget,
thread_id: i64,
plan: &'a serde_json::Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId>;
/// Blocks up to `ms` milliseconds for the trace to leave `Running`.
fn wait<'a>(&'a self, target: &'a VmTarget, trace: TraceId, ms: u32) -> InspectFuture<'a, TraceState>;
@@ -83,7 +81,4 @@ pub trait StreamTracer: Send + Sync {
/// with; reading each takes a round trip to the JVM, so the time allowed grows with them.
fn collect<'a>(&'a self, target: &'a VmTarget, trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected>;
fn release<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, ()>;
/// Releases the trace armed with `token` whose `arm` reply never came (it timed out); nothing
/// when there is none.
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()>;
}
+3 -34
Переглянути файл
@@ -73,33 +73,6 @@ pub struct SpellingRegion {
pub start: usize,
pub end: usize,
pub kind: SpellingKind,
/// A raw / verbatim string: backslashes are literal text, not escapes
/// (`r"\user"`, `r#"…"#`, `` `…` ``, `@"…"`). The spelling layer must not
/// skip the character after a `\` in one of these.
pub raw: bool,
}
/// Whether `node` is a string literal whose backslashes are not escapes.
fn is_raw_string(node: &Node<'_>, text: &str) -> bool {
let kind = node.kind();
// Rust/C++/C# grammars name the node directly.
if kind == "raw_string_literal" || kind == "verbatim_string_literal" || kind.contains("raw_string") {
return true;
}
// Go backtick strings and Python `r`/`fr`/`rb` prefixes: the grammar uses
// the generic `string` node, so inspect the literal's own prefix.
if kind == "string" || kind == "string_literal" {
let literal = &text[node.start_byte()..node.end_byte()];
if literal.starts_with('`') {
return true;
}
let quote = literal.find(['"', '\'']);
let prefix = quote.map_or("", |i| &literal[..i]);
return !prefix.is_empty()
&& prefix.chars().any(|c| c == 'r' || c == 'R')
&& prefix.chars().all(|c| matches!(c, 'r' | 'R' | 'b' | 'B' | 'f' | 'F' | 'u' | 'U'));
}
false
}
fn is_name_leaf(kind: &str) -> bool {
@@ -128,20 +101,16 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
}
/// Comments, string literals and declared names, for spell checking.
pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> Vec<SpellingRegion> {
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let literal = kind_of(&node);
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
match literal {
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
Some(LiteralKind::String) => {
let mut r = region(SpellingKind::String);
r.raw = is_raw_string(&node, text);
out.push(r);
}
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
None if node.is_named()
&& node.child_count() == 0
&& is_name_leaf(node.kind())
+1 -1
Переглянути файл
@@ -294,7 +294,7 @@ impl Syntax {
/// Comments, string literals and declared names (byte ranges, document
/// order) for the Typo inspection; `None` like [`Self::literals`].
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
-29
Переглянути файл
@@ -1422,35 +1422,6 @@ fn spelling_regions_cover_declared_names_only() {
assert_eq!(names, ["Bird", "fly", "text"]);
}
#[test]
fn spelling_regions_mark_raw_strings() {
let py = r#"a = r"\user" + R'\mesage' + fr"\wrd" + rb"\foo" + "\user""#;
let found: Vec<(&str, bool)> = syntax()
.spelling_regions(&lang("python"), py)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::String)
.map(|r| (&py[r.start..r.end], r.raw))
.collect();
assert_eq!(
found,
vec![
(r#"r"\user""#, true),
(r"R'\mesage'", true),
(r#"fr"\wrd""#, true),
(r#"rb"\foo""#, true),
(r#""\user""#, false),
]
);
// C# verbatim / Rust raw literals are named by the grammar itself.
let cs = r#"var s = @"C:\mesage";"#;
let raw = syntax().spelling_regions(&lang("csharp"), cs).unwrap().iter().any(|r| r.raw);
assert!(raw, "C# verbatim string should be raw");
let rs = r#"let s = r"\mesage";"#;
let raw = syntax().spelling_regions(&lang("rust"), rs).unwrap().iter().any(|r| r.raw);
assert!(raw, "Rust raw string should be raw");
}
// ---------------------------------------------------------------------------
// Script regions of Vue SFCs and HTML documents
-5
Переглянути файл
@@ -1,5 +0,0 @@
doctrine-mapping.xsd is from Doctrine ORM (https://github.com/doctrine/orm),
MIT License. Copyright (c) Doctrine Project.
The copy published at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd
is broken (wrong targetNamespace / XMLSchema URI after an http→https rewrite);
this file is the upstream schema with the correct namespace.
-643
Переглянути файл
@@ -1,643 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:orm="http://doctrine-project.org/schemas/orm/doctrine-mapping"
elementFormDefault="qualified">
<xs:annotation>
<xs:documentation><![CDATA[
This is the XML Schema for the object/relational
mapping file used by the Doctrine ORM.
]]></xs:documentation>
</xs:annotation>
<xs:element name="doctrine-mapping">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="mapped-superclass" type="orm:mapped-superclass" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="entity" type="orm:entity" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="embeddable" type="orm:embeddable" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:element>
<xs:complexType name="emptyType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="cascade-type">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cascade-all" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-persist" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-merge" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-remove" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-refresh" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-detach" type="orm:emptyType" minOccurs="0"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="lifecycle-callback-type">
<xs:restriction base="xs:token">
<xs:enumeration value="prePersist"/>
<xs:enumeration value="postPersist"/>
<xs:enumeration value="preUpdate"/>
<xs:enumeration value="postUpdate"/>
<xs:enumeration value="preRemove"/>
<xs:enumeration value="postRemove"/>
<xs:enumeration value="postLoad"/>
<xs:enumeration value="preFlush"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cache-usage-type">
<xs:restriction base="xs:token">
<xs:enumeration value="READ_ONLY"/>
<xs:enumeration value="READ_WRITE"/>
<xs:enumeration value="NONSTRICT_READ_WRITE"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="lifecycle-callback">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:lifecycle-callback-type" use="required" />
<xs:attribute name="method" type="xs:NMTOKEN" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="lifecycle-callbacks">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-query">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="query" type="xs:string" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-queries">
<xs:sequence>
<xs:element name="named-query" type="orm:named-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="named-native-query">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="query" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="result-class" type="orm:fqcn" />
<xs:attribute name="result-set-mapping" type="xs:string" />
</xs:complexType>
<xs:complexType name="named-native-queries">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="named-native-query" type="orm:named-native-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="entity-listener">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn"/>
</xs:complexType>
<xs:complexType name="entity-listeners">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-listener" type="orm:entity-listener" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="column-result">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="field-result">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="column" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity-result">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field-result" type="orm:field-result" minOccurs="0" maxOccurs="unbounded" />
</xs:choice>
<xs:attribute name="entity-class" type="orm:fqcn" use="required" />
<xs:attribute name="discriminator-column" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="sql-result-set-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-result" type="orm:entity-result"/>
<xs:element name="column-result" type="orm:column-result"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="sql-result-set-mappings">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="cache">
<xs:attribute name="usage" type="orm:cache-usage-type" />
<xs:attribute name="region" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:element name="indexes" type="orm:indexes" minOccurs="0"/>
<xs:element name="unique-constraints" type="orm:unique-constraints" minOccurs="0"/>
<xs:element name="discriminator-column" type="orm:discriminator-column" minOccurs="0"/>
<xs:element name="discriminator-map" type="orm:discriminator-map" minOccurs="0"/>
<xs:element name="lifecycle-callbacks" type="orm:lifecycle-callbacks" minOccurs="0" maxOccurs="1" />
<xs:element name="entity-listeners" type="orm:entity-listeners" minOccurs="0" maxOccurs="1" />
<xs:element name="named-queries" type="orm:named-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="named-native-queries" type="orm:named-native-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="sql-result-set-mappings" type="orm:sql-result-set-mappings" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="id" type="orm:id" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="field" type="orm:field" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="embedded" type="orm:embedded" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-one" type="orm:one-to-one" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-many" type="orm:one-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-one" type="orm:many-to-one" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-many" type="orm:many-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="association-overrides" type="orm:association-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="attribute-overrides" type="orm:attribute-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="table" type="orm:tablename" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:attribute name="repository-class" type="orm:fqcn"/>
<xs:attribute name="inheritance-type" type="orm:inheritance-type"/>
<xs:attribute name="change-tracking-policy" type="orm:change-tracking-policy" />
<xs:attribute name="read-only" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="tablename" id="tablename">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff.]+" id="tablename.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="option" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="options">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="mapped-superclass" >
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="embeddable">
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="change-tracking-policy">
<xs:restriction base="xs:token">
<xs:enumeration value="DEFERRED_IMPLICIT"/>
<xs:enumeration value="DEFERRED_EXPLICIT"/>
<xs:enumeration value="NOTIFY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="inheritance-type">
<xs:restriction base="xs:token">
<xs:enumeration value="SINGLE_TABLE"/>
<xs:enumeration value="JOINED"/>
<xs:enumeration value="TABLE_PER_CLASS"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generator-strategy">
<xs:restriction base="xs:token">
<xs:enumeration value="NONE"/>
<xs:enumeration value="SEQUENCE"/>
<xs:enumeration value="IDENTITY"/>
<xs:enumeration value="AUTO"/>
<xs:enumeration value="UUID"/>
<xs:enumeration value="CUSTOM" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fk-action">
<xs:restriction base="xs:token">
<xs:enumeration value="CASCADE"/>
<xs:enumeration value="RESTRICT"/>
<xs:enumeration value="SET NULL"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fetch-type">
<xs:restriction base="xs:token">
<xs:enumeration value="EAGER"/>
<xs:enumeration value="LAZY"/>
<xs:enumeration value="EXTRA_LAZY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generated-type">
<xs:restriction base="xs:token">
<xs:enumeration value="NEVER"/>
<xs:enumeration value="INSERT"/>
<xs:enumeration value="ALWAYS"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updatable" type="xs:boolean" default="true" />
<xs:attribute name="generated" type="orm:generated-type" default="NEVER" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="embedded">
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="optional" />
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
</xs:complexType>
<xs:complexType name="discriminator-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="xs:NMTOKEN"/>
<xs:attribute name="field-name" type="xs:NMTOKEN" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraint">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraints">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="unique-constraint" type="orm:unique-constraint" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="index">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:attribute name="flags" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="indexes">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="index" type="orm:index" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="value" type="orm:type" use="required"/>
<xs:attribute name="class" type="orm:fqcn" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-map">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="discriminator-mapping" type="orm:discriminator-mapping" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="strategy" type="orm:generator-strategy" use="optional" default="AUTO" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="id">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="generator" type="orm:generator" minOccurs="0" />
<xs:element name="sequence-generator" type="orm:sequence-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="custom-id-generator" type="orm:custom-id-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="association-key" type="xs:boolean" default="false" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="sequence-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="sequence-name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="allocation-size" type="xs:integer" use="optional" default="1" />
<xs:attribute name="initial-value" type="xs:integer" use="optional" default="1" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="custom-id-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn" use="required" />
</xs:complexType>
<xs:simpleType name="fqcn" id="fqcn">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+" id="fqcn.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="type" id="type">
<xs:restriction base="xs:token">
<xs:pattern value="([a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+)|(\c+)" id="type.class.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="inverse-join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional" />
<xs:attribute name="referenced-column-name" type="xs:NMTOKEN" use="optional" default="id" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="true" />
<xs:attribute name="on-delete" type="orm:fk-action" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-table">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-columns" type="orm:join-columns" />
<xs:element name="inverse-join-columns" type="orm:join-columns" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="order-by-field" type="orm:order-by-field" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="direction" type="orm:order-by-direction" default="ASC" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="order-by-direction">
<xs:restriction base="xs:token">
<xs:enumeration value="ASC"/>
<xs:enumeration value="DESC"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="columntoken" id="columntoken">
<xs:restriction base="xs:token">
<xs:pattern value="[-._:A-Za-z0-9`]+" id="columntoken.pattern"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="many-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" use="required" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="many-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="association-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="association-override" type="orm:association-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="association-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="join-columns" type="orm:join-columns" minOccurs="0" />
<xs:element name="inversed-by" type="orm:inversed-by-override" minOccurs="0" maxOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="fetch" type="orm:fetch-type" use="optional" />
</xs:complexType>
<xs:complexType name="inversed-by-override">
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="attribute-override" type="orm:attribute-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="attribute-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field" type="orm:attribute-override-field" minOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-override-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updateable" type="xs:boolean" default="true" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:schema>
+1 -9
Переглянути файл
@@ -182,10 +182,9 @@ impl StreamTracer for JdtStreamTracer {
thread_id: i64,
plan: &'a Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId> {
Box::pin(async move {
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget, "token": token});
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget});
Ok(self.call::<Armed>("arm", target, args, COMMAND_TIMEOUT).await?.trace_id)
})
}
@@ -224,13 +223,6 @@ impl StreamTracer for JdtStreamTracer {
self.call::<Value>("release", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await.map(drop)
})
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()> {
Box::pin(async move {
// Waits for an arm still setting up: as long as an arm may take.
self.call::<Value>("release", target, json!({"token": token}), COMMAND_TIMEOUT).await.map(drop)
})
}
}
#[cfg(test)]
-4
Переглянути файл
@@ -40,7 +40,6 @@ mod uri;
mod virtual_doc;
mod vue_navigation;
mod vue_refs;
mod xml_catalog;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
@@ -3796,9 +3795,6 @@ impl LspManager {
if cfg.name == compose::SERVER {
compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files());
}
if cfg.name == xml_catalog::SERVER {
xml_catalog::configure_lemminx_catalogs(&mut cfg);
}
cfg
}
-149
Переглянути файл
@@ -1,149 +0,0 @@
//! Bundled XML catalogs for LemMinX so known-broken remote XSDs resolve locally.
//!
//! Doctrine's hosted `doctrine-mapping.xsd` advertises the wrong `targetNamespace`
//! (the schema URL itself) after an http→https rewrite, so any mapping file that
//! points `xsi:schemaLocation` at that URL fails with `TargetNamespace.1` /
//! `cvc-elt.1.a`. An OASIS catalog maps the namespace and those system IDs to the
//! correct upstream schema we ship.
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const SERVER: &str = "lemminx";
const DOCTRINE_XSD: &str = include_str!("../schemas/xml/doctrine-mapping.xsd");
const CATALOG_TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://doctrine-project.org/schemas/orm/doctrine-mapping" uri="doctrine-mapping.xsd"/>
<uri name="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
</catalog>
"#;
/// Writes the bundled catalog (idempotent) and prepends it to LemMinX `xml.catalogs`.
pub fn configure_lemminx_catalogs(cfg: &mut LanguageServerConfig) {
if cfg.name != SERVER {
return;
}
let Some(catalog) = ensure_catalog() else { return };
let catalog = path_for_settings(&catalog);
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
let Some(root) = settings.as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(xml) = root.entry("xml").or_insert_with(|| json!({})).as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(catalogs) = xml.entry("catalogs").or_insert_with(|| json!([])).as_array_mut() else {
cfg.settings = Some(settings);
return;
};
if catalogs.iter().any(|v| v.as_str() == Some(catalog.as_str())) {
cfg.settings = Some(settings);
return;
}
catalogs.insert(0, Value::String(catalog));
cfg.settings = Some(settings);
}
fn ensure_catalog() -> Option<PathBuf> {
// Per-pid directory: shared `/tmp/openidea-xml-catalog` would let another
// local user plant a catalog that remaps arbitrary schema URIs.
let dir = std::env::temp_dir().join(format!("openidea-xml-catalog-{}", std::process::id()));
if let Err(e) = ide_vfs::create_private_dir(&dir) {
tracing::warn!("xml catalog: cannot create {}: {e}", dir.display());
return None;
}
let xsd = dir.join("doctrine-mapping.xsd");
if !write_if_changed(&xsd, DOCTRINE_XSD.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", xsd.display());
return None;
}
let catalog = dir.join("catalog.xml");
if !write_if_changed(&catalog, CATALOG_TEMPLATE.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", catalog.display());
return None;
}
Some(catalog)
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> bool {
if std::fs::read(path).ok().as_deref() == Some(bytes) {
return true;
}
ide_vfs::write_atomic_private(path, bytes).is_ok()
}
fn path_for_settings(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use ide_language::LanguageRegistry;
const DOCTRINE_NS: &str = "http://doctrine-project.org/schemas/orm/doctrine-mapping";
const DOCTRINE_SCHEMA_HTTPS: &str = "https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
const DOCTRINE_SCHEMA_HTTP: &str = "http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
#[test]
fn bundled_xsd_keeps_http_namespace() {
assert!(DOCTRINE_XSD.contains(&format!("targetNamespace=\"{DOCTRINE_NS}\"")));
assert!(!DOCTRINE_XSD.contains("xmlns:xs=\"https://www.w3.org/2001/XMLSchema\""));
assert!(!DOCTRINE_XSD.contains("targetNamespace=\"https://www.doctrine-project.org"));
}
#[test]
fn catalog_maps_namespace_and_system_ids() {
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTP}""#)));
assert_eq!(CATALOG_TEMPLATE.matches(r#"uri="doctrine-mapping.xsd""#).count(), 4);
}
#[test]
fn prepends_catalog_without_dropping_user_entries() {
let reg = LanguageRegistry::load(None).unwrap();
let xml = reg.get(&ide_core::LanguageId::new("xml")).unwrap();
let mut cfg = xml.language_servers[0].clone();
cfg.settings = Some(json!({"xml": {"catalogs": ["/user/catalog.xml"]}}));
configure_lemminx_catalogs(&mut cfg);
let list: Vec<String> = cfg.settings.as_ref().unwrap()["xml"]["catalogs"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
assert_eq!(list.len(), 2);
assert!(list[0].ends_with("catalog.xml"));
assert!(list[0].contains(&format!("openidea-xml-catalog-{}", std::process::id())));
assert_eq!(list[1], "/user/catalog.xml");
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings.as_ref().unwrap()["xml"]["catalogs"].as_array().unwrap().len(), 2);
let catalog = PathBuf::from(&list[0]);
let body = std::fs::read_to_string(&catalog).unwrap();
assert_eq!(body, CATALOG_TEMPLATE);
assert!(body.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
let xsd = catalog.with_file_name("doctrine-mapping.xsd");
assert_eq!(std::fs::read_to_string(xsd).unwrap(), DOCTRINE_XSD);
}
#[test]
fn ignores_other_servers() {
let reg = LanguageRegistry::load(None).unwrap();
let yaml = reg.get(&ide_core::LanguageId::new("yaml")).unwrap();
let mut cfg = yaml.language_servers[0].clone();
let before = cfg.settings.clone();
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings, before);
}
}
+3 -9
Переглянути файл
@@ -3193,7 +3193,7 @@ async fn stream_commands_send_target_then_named_fields() {
let plan = json!({"root": {"line": 14}});
s.respond("workspace/executeCommand", json!({"ok": {"traceId": 3}}));
assert_eq!(tracer.arm(&target, 7, &plan, 500, "t1").await.unwrap(), 3);
assert_eq!(tracer.arm(&target, 7, &plan, 500).await.unwrap(), 3);
s.respond(
"workspace/executeCommand",
json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}),
@@ -3211,24 +3211,18 @@ async fn stream_commands_send_target_then_named_fields() {
tracer.collect(&target, 3, 2).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release(&target, 3).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release_armed(&target, "t1").await.unwrap();
let asked = s.requested("workspace/executeCommand");
let seen: Vec<_> = asked.iter().map(|p| (p["command"].clone(), p["arguments"].clone())).collect();
assert_eq!(
seen,
vec![
(
json!("openidea.jvm.stream.arm"),
json!([target_json, {"threadId": 7, "plan": plan, "budget": 500, "token": "t1"}])
),
(json!("openidea.jvm.stream.arm"), json!([target_json, {"threadId": 7, "plan": plan, "budget": 500}])),
(json!("openidea.jvm.stream.wait"), json!([target_json, {"traceId": 3, "ms": 250}])),
(json!("openidea.jvm.stream.stop"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.abort"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.collect"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"token": "t1"}])),
]
);
}
@@ -3309,7 +3303,7 @@ async fn stream_errors_map() {
];
for (reply, expected) in cases {
s.respond("workspace/executeCommand", reply.clone());
assert_eq!(tracer.arm(&target, 1, &json!({}), 10, "t").await.unwrap_err(), expected, "{reply}");
assert_eq!(tracer.arm(&target, 1, &json!({}), 10).await.unwrap_err(), expected, "{reply}");
}
}
+9 -57
Переглянути файл
@@ -23,7 +23,7 @@
<script>
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
// in its highlight colour; the visible area as a frame that can be dragged; the wheel
// scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out.
// scrolls the editor.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -33,10 +33,6 @@
let colors = new Map();
let loading = new Set();
let view = null;
let problems = [];
let folds = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
let queued = false;
@@ -46,39 +42,17 @@
};
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
const rowOf = (line) => {
let hidden = 0;
for (const f of folds) {
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
else break;
}
return line - hidden;
};
const lineOfRow = (row) => {
let hidden = 0;
for (const f of folds) {
const r = f.fromLine - hidden;
if (row >= r + 1) hidden += f.toLine - f.fromLine;
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
else break;
}
return row + hidden;
};
function layout() {
const H = canvas.clientHeight;
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
const L = Math.max(1, rowOf(view.lineCount));
const firstRow = rowOf(view.firstLine);
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
const L = Math.max(1, view.lineCount);
const visible = Math.max(0, view.lastLine - view.firstLine);
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
const mapH = L * LINE;
const offset = p * Math.max(0, mapH - H);
const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
}
function redraw() {
@@ -91,7 +65,7 @@
queued = false;
const dpr = window.devicePixelRatio || 1;
const W = canvas.clientWidth;
const { H, offset, top, height, L } = layout();
const { H, offset, top, height } = layout();
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
@@ -100,12 +74,11 @@
ctx.clearRect(0, 0, W, H);
if (!view) return;
const first = Math.floor(offset / LINE);
const last = Math.min(L, Math.ceil((offset + H) / LINE));
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
const missing = [];
const muted = cssVar("--openidea-fg-muted");
for (let row = first; row < last; row++) {
const i = lineOfRow(row);
const y = row * LINE - offset;
for (let i = first; i < last; i++) {
const y = i * LINE - offset;
const line = text[i] || "";
// Text without a syntax colour: faint, so the coloured spans stand out.
ctx.globalAlpha = 0.2;
@@ -122,13 +95,6 @@
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
}
}
// Problems: errors drawn last, on top; weak warnings in the muted colour.
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
const y = Math.floor(rowOf(p.line));
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
}
// The visible area: a light accent tint and a 1px border, stronger while dragged.
const frameH = Math.max(height, 4);
ctx.fillStyle = cssVar("--openidea-accent");
@@ -168,9 +134,6 @@
}
const doc = await editor.document.get();
text = doc.text.split("\n");
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -188,17 +151,6 @@
for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k);
redraw();
});
if (editor.onProblems)
editor.onProblems((p) => {
problems = p;
redraw();
});
// `onLayout` is API 1.10.
if (editor.onLayout)
editor.onLayout((l) => {
folds = l.folded;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
@@ -206,7 +158,7 @@
const scrollToFrameTop = (frameTop) => {
const { range, visible, L } = layout();
const p = Math.min(1, Math.max(0, frameTop / range));
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
void editor.scrollTo(p * Math.max(0, L - visible));
};
canvas.addEventListener("pointerdown", (e) => {
if (!view) return;
+4 -10
Переглянути файл
@@ -26,13 +26,9 @@ pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
}}\n"
)
}
@@ -79,10 +75,8 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
}
#[test]
+1 -27
Переглянути файл
@@ -53,12 +53,6 @@ struct JavaProbe {
static JAVA_PROBES: Mutex<BTreeMap<PathBuf, JavaProbe>> = Mutex::new(BTreeMap::new());
/// How long `java -version` may take before the JDK counts as unable to run. The first
/// run of a JDK can be slow: Rosetta translates an x86_64 JDK on Apple silicon, and
/// malware scans check a freshly downloaded one. Excluded, a project's JDK 8 leaves its
/// `JavaSE-1.8` to a newer JDK, and APIs JDK 8 has (`jdk.nashorn`) stop resolving.
const JAVA_PROBE_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(8) } else { Duration::from_secs(30) };
/// Metadata can describe a JDK built for another architecture. Probe the executable
/// before giving it to JDT, with a short cache shared by server and project selection.
pub(crate) fn java_runs(java: &Path) -> bool {
@@ -78,7 +72,7 @@ pub(crate) fn java_runs(java: &Path) -> bool {
return probe.runnable;
}
}
let runnable = crate::exec::query(java, &["-version"], JAVA_PROBE_TIMEOUT).is_some();
let runnable = crate::exec::query(java, &["-version"], Duration::from_secs(5)).is_some();
JAVA_PROBES.lock().unwrap_or_else(|e| e.into_inner()).insert(
java.to_path_buf(),
JavaProbe { modified, len: metadata.len(), permissions: metadata.permissions(), at: Instant::now(), runnable },
@@ -986,26 +980,6 @@ mod tests {
assert_eq!(std::fs::read_to_string(&probes).unwrap().lines().count(), 1, "probed once");
}
#[cfg(unix)]
#[test]
fn a_jdk_8_slow_on_its_first_run_stays_the_java_8_runtime() {
let tmp = tempfile::tempdir().unwrap();
let jdk8 = test_jdk(tmp.path(), 8, "rosetta8");
let jdk25 = test_jdk(tmp.path(), 25, "native25");
// Longer than the 5 seconds a first run under Rosetta used to be allowed.
std::fs::write(
java_executable(&jdk8.home),
"#!/bin/sh
/bin/sleep 6
echo 'openjdk version 1.8'
",
)
.unwrap();
let rt = runtimes(&[jdk8.clone(), jdk25.clone()]);
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": jdk8.home }));
assert_eq!(rt[1]["name"], "JavaSE-25");
}
#[cfg(unix)]
#[test]
fn slow_java_probe_does_not_hold_the_cache_lock() {
-172
Переглянути файл
@@ -1,172 +0,0 @@
//! jdtls workspaces (`<local data>/lsp/jdtls/<key>`) that no project uses any more.
//!
//! A workspace is keyed by the project folder and by the settings that need a clean import
//! (source paths, output folder, libraries, linked Gradle projects, unlinked Maven poms), so
//! each change of those, and each moved or deleted project, leaves the previous workspace
//! behind: 50–200 MB of imported model and indexes. Like a cache, one unused for a month is
//! removed at start-up; a project that comes back imports again.
use ide_language::LanguageServerConfig;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// Touched each time jdtls starts on a workspace.
const USED_MARKER: &str = ".openidea-last-used";
/// Workspaces being removed (renamed first, so a server never starts on a half-deleted one).
const TRASH_PREFIX: &str = ".removed-";
/// How long a workspace may go unused before start-up removes it.
pub const UNUSED_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
}
}
/// When a workspace was last used: the latest of our marker (written when jdtls starts) and what
/// jdtls itself touches while it runs and when it saves on exit (a server can run for weeks).
fn last_used(dir: &Path) -> Option<SystemTime> {
let metadata = dir.join(".metadata");
[
dir.join(USED_MARKER),
metadata.join(".log"),
metadata.join(".plugins").join("org.eclipse.core.resources"),
metadata,
]
.into_iter()
.filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
.max()
}
/// Moves the workspaces unused for longer than `max_age` aside, before any server starts, and
/// returns what [`remove`] deletes. Quick: only renames.
pub fn take_unused(data_dir: &Path, max_age: Duration) -> Vec<PathBuf> {
let root = root(data_dir);
let Ok(entries) = std::fs::read_dir(&root) else { return Vec::new() };
let now = SystemTime::now();
let mut taken = Vec::new();
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with(TRASH_PREFIX) {
// Left by a start-up that quit before deleting it.
taken.push(path);
continue;
}
let unused = last_used(&path).and_then(|t| now.duration_since(t).ok()).is_some_and(|age| age > max_age);
if !unused {
continue;
}
let trash = root.join(format!("{TRASH_PREFIX}{name}"));
match std::fs::rename(&path, &trash) {
Ok(()) => taken.push(trash),
Err(e) => tracing::debug!("jdtls: cannot move unused workspace {}: {e}", path.display()),
}
}
taken
}
/// Deletes what [`take_unused`] moved aside; slow for large workspaces, so off the start-up path.
pub fn remove(taken: Vec<PathBuf>) {
for dir in taken {
match std::fs::remove_dir_all(&dir) {
Ok(()) => tracing::info!("jdtls: removed unused workspace {}", dir.display()),
Err(e) => tracing::warn!("jdtls: cannot remove unused workspace {}: {e}", dir.display()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn days_ago(days: u64) -> SystemTime {
SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
}
/// Back-dates a file, or (on Unix, where a folder opens as a file) a folder.
fn age(path: &Path, days: u64) {
let file =
if path.is_dir() { std::fs::File::open(path) } else { std::fs::File::options().write(true).open(path) };
file.unwrap().set_modified(days_ago(days)).unwrap();
}
fn cfg(data: &Path) -> LanguageServerConfig {
let languages = ide_language::LanguageRegistry::load(None).unwrap();
let mut cfg = languages.get(&ide_core::LanguageId::new("java")).unwrap().language_servers.remove(0);
cfg.args = vec!["-data".into(), data.to_string_lossy().into_owned()];
cfg
}
#[test]
fn removes_workspaces_unused_for_longer_than_the_limit() {
let tmp = tempfile::tempdir().unwrap();
let root = root(tmp.path());
let (old, recent) = (root.join("old"), root.join("recent"));
mark_used(&cfg(&old));
mark_used(&cfg(&recent));
age(&old.join(USED_MARKER), 40);
age(&recent.join(USED_MARKER), 5);
std::fs::write(root.join("defaults.prefs"), "").unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken.len(), 1, "{taken:?}");
assert!(!old.exists() && recent.exists() && root.join("defaults.prefs").exists());
remove(taken);
let mut left: Vec<_> = std::fs::read_dir(&root).unwrap().map(|e| e.unwrap().file_name()).collect();
left.sort();
assert_eq!(left, ["defaults.prefs", "recent"]);
}
#[test]
fn a_started_server_marks_its_workspace_again() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
mark_used(&cfg(&ws));
age(&ws.join(USED_MARKER), 40);
mark_used(&cfg(&ws));
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
assert!(ws.exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
for p in [ws.join(".metadata/.log"), ws.join(".metadata")] {
age(&p, 90);
}
assert_eq!(take_unused(tmp.path(), UNUSED_FOR).len(), 1);
// The log alone being recent keeps it.
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
age(&ws.join(".metadata"), 90);
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
}
#[test]
fn leftovers_of_an_interrupted_removal_are_removed() {
let tmp = tempfile::tempdir().unwrap();
let trash = root(tmp.path()).join(format!("{TRASH_PREFIX}gone"));
std::fs::create_dir_all(trash.join(".metadata")).unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken, std::slice::from_ref(&trash));
remove(taken);
assert!(!trash.exists());
}
}
-1
Переглянути файл
@@ -16,7 +16,6 @@ pub mod go;
pub mod godot;
pub mod java;
pub mod jdtls;
pub mod jdtls_workspaces;
pub mod libraries;
pub mod locate;
pub mod lombok;
+2 -13
Переглянути файл
@@ -24,8 +24,6 @@ pub use words::{MIN_WORD_CHARS, WordSpan, words};
pub enum RegionKind {
Comment,
String,
/// A raw / verbatim string: `\` is literal text, not an escape (`r"\user"`).
RawString,
/// A declared identifier (`camelCase` / `snake_case` split).
Name,
/// Plain text / Markdown prose.
@@ -55,7 +53,7 @@ impl From<RegionKind> for TypoContext {
fn from(kind: RegionKind) -> Self {
match kind {
RegionKind::Name => Self::Code,
RegionKind::String | RegionKind::RawString => Self::Literal,
RegionKind::String => Self::Literal,
RegionKind::Comment => Self::Comment,
RegionKind::Prose => Self::Prose,
}
@@ -91,7 +89,7 @@ impl SpellScope {
pub fn includes(&self, kind: RegionKind) -> bool {
match kind {
RegionKind::Name => self.code,
RegionKind::String | RegionKind::RawString => self.literals,
RegionKind::String => self.literals,
RegionKind::Comment => self.comments,
RegionKind::Prose => true,
}
@@ -680,15 +678,6 @@ mod tests {
assert_eq!(found, [("mesage", TypoContext::Code)]);
}
#[test]
fn raw_strings_do_not_lose_the_letter_after_a_backslash() {
let s = Speller::default();
let text = r#"r"\user \mesage""#;
let regions = [Region { start: 0, end: text.len(), kind: RegionKind::RawString }];
let typos = s.check(text, &regions, &|| false).unwrap();
assert_eq!(typos.iter().map(|t| t.word.as_str()).collect::<Vec<_>>(), ["mesage"]);
}
#[test]
fn scope_filters_region_kinds() {
let comments_only = SpellScope { code: false, literals: false, comments: true };
+1 -12
Переглянути файл
@@ -18,7 +18,7 @@ pub struct WordSpan {
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
let Some(slice) = text.get(start..end) else { return };
let escapes = match kind {
RegionKind::Name | RegionKind::RawString => Escapes::None,
RegionKind::Name => Escapes::None,
RegionKind::String => Escapes::Char,
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
};
@@ -186,17 +186,6 @@ mod tests {
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
}
#[test]
fn raw_strings_keep_the_letter_after_a_backslash() {
// `\u` in a normal string is an escape: the letter is consumed and only
// `ser` is prose. In a raw string the backslash is literal, so `user`
// must be checked whole (issue: r"\user" flagged as typo 'ser').
assert_eq!(split(r#""\user""#, RegionKind::String), ["ser"]);
assert_eq!(split(r#""\user""#, RegionKind::RawString), ["user"]);
assert_eq!(split(r"\n\t \wrd", RegionKind::RawString), ["wrd"]);
assert_eq!(split(r"C:\Users\mesage", RegionKind::RawString), ["Users", "mesage"]);
}
#[test]
fn skips_backslash_commands_in_comments() {
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
+4 -6
Переглянути файл
@@ -332,10 +332,9 @@ impl<'t> Finder<'_, 't> {
/// Subtrees where calls that exit before the root can be: the statement holding
/// the chain, or, for a chain in a compound statement's header, that statement.
/// For an `else if` also the conditions of the `if`s before it that start on the
/// line the trace starts from (`} else if` on a line of its own stops after they
/// ran); their branch bodies never count, since the later condition is only
/// reached when they were skipped.
/// For an `else if` also the conditions of the `if`s before it, which all ran;
/// their branch bodies did not, since the later condition is only reached when
/// they were skipped.
fn skip_regions(&self, anchor: Node<'t>, scope: Node<'t>) -> Vec<Node<'t>> {
let is_statement = |n: Node| n.kind().ends_with("_statement") || n.kind() == "switch_expression";
if anchor.kind() != "method_invocation" {
@@ -345,13 +344,12 @@ impl<'t> Finder<'_, 't> {
.take_while(|n| *n != scope)
.find(|n| is_statement(*n))
.unwrap_or(anchor);
let stop_row = anchor.start_position().row;
let mut regions = vec![region];
while let Some(outer) = region
.parent()
.filter(|p| p.kind() == "if_statement" && p.child_by_field_name("alternative") == Some(region))
{
regions.extend(outer.child_by_field_name("condition").filter(|c| c.start_position().row >= stop_row));
regions.extend(outer.child_by_field_name("condition"));
region = outer;
}
regions
-1
Переглянути файл
@@ -125,7 +125,6 @@ public class Chains {
} else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF_BODY
base--;
}
if (names.stream().anyMatch(x -> x.isEmpty())) base++; else if (list.stream().noneMatch(x -> x.isEmpty())) base--; // C_PLAN_ELSE_IF_ONE_LINE
List<String> out = nums.stream() // C_PLAN_FIRST_LINE
.filter(x -> x > 0)
.map(x -> x * 2)
+2 -10
Переглянути файл
@@ -172,17 +172,9 @@ fn root_skip_counts_sibling_chain_in_if_header() {
}
#[test]
fn root_skip_leaves_out_an_earlier_condition_that_ran_before_the_stop() {
// Stopped on the `} else if` line, the first condition has already returned.
fn root_skip_counts_earlier_condition_of_else_if() {
let root = plan_of("C_PLAN_ELSE_IF").root.unwrap();
assert_eq!(root, spec("stream", 0, 0));
}
#[test]
fn root_skip_counts_an_earlier_condition_on_the_same_line() {
let chains = chains_at("C_PLAN_ELSE_IF_ONE_LINE");
let later = chains.iter().find(|c| c.terminal.name == "noneMatch").expect("else-if chain");
assert_eq!(real_run_plan(later).unwrap().root, Some(spec("stream", 0, 1)));
assert_eq!(root, spec("stream", 0, 1));
}
#[test]
+1 -55
Переглянути файл
@@ -13,10 +13,6 @@ pub struct RecentProject {
/// Git branch shown on the welcome screen. Persisted as of last open; [`RecentProjects::list_live`]
/// refreshes it from `.git/HEAD` when the list is shown.
pub branch: Option<String>,
/// The local folder no longer exists (set by [`with_live_branches`] when the list is shown): the
/// welcome screen shows the entry as unavailable.
#[serde(default)]
pub missing: bool,
}
pub const MAX_RECENT_PROJECTS: usize = 30;
@@ -143,25 +139,11 @@ pub fn with_live_branches(mut items: Vec<RecentProject>) -> Vec<RecentProject> {
for item in &mut items {
if let Ok(branch) = read_head_branch(item.path.as_ref()) {
item.branch = branch;
} else if is_missing(item.path.as_ref()) {
// A deleted repository has no branch to show.
item.missing = true;
item.branch = None;
}
}
items
}
/// A local project folder that is gone. Remote locations (`ssh://`, `wsl://`, `devcontainer://`)
/// and WSL shares, which a stopped distribution only hides, never count as missing.
fn is_missing(path: &Path) -> bool {
let text = path.to_string_lossy();
// Stored paths may use `/` (`//wsl.localhost/Ubuntu/...`); host names ignore case.
let unc = text.replace('/', r"\").to_ascii_lowercase();
let wsl = unc.starts_with(r"\\wsl$") || unc.starts_with(r"\\wsl.localhost");
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -210,7 +192,7 @@ impl RecentProjects {
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch });
cap(&mut items, &self.groups.lock());
self.persist(&items)
}
@@ -260,15 +242,6 @@ impl RecentProjects {
mod tests {
use super::*;
#[test]
fn wsl_shares_stored_with_forward_slashes_are_never_missing() {
for path in
[r"\\wsl.localhost\Ubuntu\home\me\gone", "//wsl.localhost/Ubuntu/home/me/gone", "//WSL$/Ubuntu/gone"]
{
assert!(!is_missing(Path::new(path)), "{path}");
}
}
#[test]
fn newest_first_capped_and_persisted() {
let tmp = tempfile::tempdir().unwrap();
@@ -368,33 +341,6 @@ mod tests {
assert_eq!(recent.list().iter().find(|i| i.path.as_ref() == repo).unwrap().branch.as_deref(), Some("stale"));
}
#[test]
fn list_live_marks_deleted_folders_missing_without_their_branch() {
let tmp = tempfile::tempdir().unwrap();
let gone = tmp.path().join("removed-worktree");
write_head(&gone.join(".git"), "ref: refs/heads/feature-x\n");
let plain = tmp.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
let recent = RecentProjects::load(tmp.path().join("config").as_path());
recent.touch(&gone, Some("feature-x".into())).unwrap();
recent.touch(&plain, Some("kept".into())).unwrap();
recent.touch(Path::new("ssh://server/home/me/app"), None).unwrap();
std::fs::remove_dir_all(&gone).unwrap();
let live = recent.list_live();
let by_path = |p: &Path| live.iter().find(|i| i.path.as_ref() == p).unwrap();
assert!(by_path(&gone).missing);
assert_eq!(by_path(&gone).branch, None);
assert!(!by_path(&plain).missing);
assert_eq!(by_path(&plain).branch.as_deref(), Some("kept"));
assert!(!by_path(Path::new("ssh://server/home/me/app")).missing, "remote locations are not checked");
// Only the shown list: the saved one keeps the last branch.
let stored = recent.list();
let stored = stored.iter().find(|i| i.path.as_ref() == gone).unwrap();
assert!(!stored.missing);
assert_eq!(stored.branch.as_deref(), Some("feature-x"));
}
#[test]
fn list_live_follows_worktree_gitdir_and_shows_short_detached_head() {
let tmp = tempfile::tempdir().unwrap();
-18
Переглянути файл
@@ -132,24 +132,6 @@ mac = "Meta+Alt+C" # optional; macOS uses `key` as written when it is mis
the user already uses that keystroke, or when the action already has a binding. The user
can rebind it in **Settings › Keymap**.
### Escape in the editor
API 1.10 lets a command answer a plain <kbd>Escape</kbd> in a focused editor, to clear
something the plugin shows there (a highlight, a mode):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # required; set it with set-context while there is something to clear
```
- It runs only after everything the IDE does with Escape in the editor found nothing to do:
closing a popup, completion or rename, collapsing a selection or extra carets, Vim.
- `when` is required and `key` (and `mac`, if given) must be `Escape`. Escape is the only plain
key a plugin can bind, and `when` is accepted only on such a binding.
- When several plugins' `when` hold, the most recently loaded one runs.
## Menus
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
-15
Переглянути файл
@@ -119,21 +119,6 @@ mac = "Meta+Alt+C" # 可选;缺省时 macOS 原样使用 `key`
- 插件快捷键只是默认值,优先级低于 IDE:按键映射预设或用户已经占用该按键、或该动作已有绑定时,
插件的快捷键会被丢弃。用户可以在 **设置 › 按键映射** 中重新绑定。
### 编辑器中的 Escape
API 1.10 起,命令可以响应焦点编辑器中单独按下的 <kbd>Escape</kbd>,用来清除插件在编辑器里显示的内容(高亮、某种模式):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # 必填;有内容可清除时用 set-context 设置
```
- 只有 IDE 在编辑器里对 Escape 的处理都没有生效时才会执行:关闭弹窗、补全或重命名,收起选区或多余的光标,Vim。
- 必须写 `when`,且 `key`(以及给出的 `mac`)必须是 `Escape`。Escape 是插件唯一能绑定的单独按键,`when` 也只用于这种绑定。
- 多个插件的 `when` 同时成立时,执行最后加载的那个插件的命令。
## 菜单
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ optional = ["net:api.openai.com", "secrets"]
| ------------------- | ---------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
-58
Переглянути файл
@@ -902,61 +902,3 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
// Output-less running tool rows align their kind icon with expandable tool rows.
expect(layout.iconLeftDiff).toBeLessThanOrEqual(1);
});
test("aligns Mermaid diagrams in replies to their container align attribute", async ({ page }) => {
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await openReply(
page,
[
"Summary across the full width of the reply column so diagrams sit inside a wider message body.",
"",
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
store.openTaskInEditorLocation(id);
}, TASK.id);
const reply = page.locator("[class*='_stream_']:visible [class*='_markdown_']").first();
const outputs = reply.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
+4 -6
Переглянути файл
@@ -70,7 +70,7 @@ async function stubRepositoryAndAgent(page: Page, reply: string) {
operation: null,
});
h.vcs_status = () => changes;
h.vcs_pending_patch = () => patch;
h.vcs_create_patch = () => patch;
h.vcs_log = () => [{ id: "1111111", summary: "Bump the wrapper" }];
h.agent_create = (args) => {
const created = { ...task, id: "new", title: "Write a commit message", status: "starting", updatedMs: 9 };
@@ -131,11 +131,9 @@ test("the agent of the latest task writes the commit message of the included cha
// Only the included file's diff, and the style of the latest commits, go to the agent.
expect(created.prompt.text).toContain("+++ b/build.gradle.kts");
expect(created.prompt.text).toContain("- Bump the wrapper");
// What Commit would commit: the included file only (read again before the message is filled in).
const pending = await ipcCalls(page, "vcs_pending_patch");
expect(pending.length).toBeGreaterThan(0);
for (const call of pending)
expect(call).toMatchObject({ options: expect.objectContaining({ stage: [`${ROOT}/build.gradle.kts`] }) });
expect(await ipcCalls(page, "vcs_create_patch")).toEqual([
expect.objectContaining({ source: { from: "changes", paths: [`${ROOT}/build.gradle.kts`], reverse: false } }),
]);
// The task ran for the message only: it is gone again, and nothing was left to read.
expect(await ipcCalls(page, "agent_delete")).toEqual([expect.objectContaining({ task: "new" })]);
await expect(page.getByRole("alert")).toHaveCount(0);
-54
Переглянути файл
@@ -273,60 +273,6 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await page.keyboard.insertText(
[
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
const outputs = preview.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const column = editor.locator(".cm-gutter.cm-openidea-bookmarks");
Бінарний файл не відображається.
+3 -15
Переглянути файл
@@ -6,7 +6,6 @@ import ai.openidea.jvminspect.JavaDebugSessions.HubEvent;
import ai.openidea.jvminspect.RealRunPlan.StepSpec;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.ArrayReference;
import com.sun.jdi.BooleanValue;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.IncompatibleThreadStateException;
@@ -163,8 +162,6 @@ final class RealRunTrace {
/** Recorder number of the next wrapped op; modifiers take none. */
private int nextStep;
private ObjectReference lastWrapped;
/** Whether the stream was made sequential: the plan asked, or the stream the chain starts from was parallel. */
private volatile boolean sequentialized;
/** {@code forceEarlyReturn} at a method exit makes that frame exit once more, returning the forced value. */
private Method echoMethod;
private Value echoValue;
@@ -243,14 +240,11 @@ final class RealRunTrace {
subscription = hub.subscribe(this::onEvent, e -> errors.add("event listener: " + e));
if (held != null) {
// Not put back: the program consumes the stream right after.
// A stream made parallel before this statement shows no `parallel` in the chain.
sequentialized = plan.sequentialize() || isParallel(held);
lastWrapped = wrap(held, nextStep++, sequentialized);
lastWrapped = wrap(held, nextStep++, plan.sequentialize());
// The invokes resumed the thread, which invalidated the frame read before them.
thread.frame(0).setValue(local, lastWrapped);
} else {
rootSkip = plan.root().skip();
sequentialized = plan.sequentialize();
}
// Last: with these on, an invoke into the thread would raise the trace's own events inside it.
// The step out of the frame never fires inside an invoke, which runs above it.
@@ -408,8 +402,7 @@ final class RealRunTrace {
}
ObjectReference stream = returned(exit, root);
setEnabled(false);
if (!sequentialized && isParallel(stream)) sequentialized = true;
replace(exit, wrap(stream, nextStep++, sequentialized));
replace(exit, wrap(stream, nextStep++, plan.sequentialize()));
return;
}
if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return;
@@ -604,11 +597,6 @@ final class RealRunTrace {
return sequentialize ? invoke(wrapped, "sequential") : wrapped;
}
private boolean isParallel(ObjectReference stream) throws Exception {
Method method = streamMethod(stream.referenceType(), "isParallel", 0);
return stream.invokeMethod(thread, method, List.of(), INVOKE) instanceof BooleanValue b && b.value();
}
private ObjectReference invoke(ObjectReference stream, String name, Value... arguments) throws Exception {
Method method = streamMethod(stream.referenceType(), name, arguments.length);
return keep(RecorderLoader.pin(() -> (ObjectReference) stream.invokeMethod(thread, method, List.of(arguments), INVOKE)));
@@ -1020,7 +1008,7 @@ final class RealRunTrace {
};
int skipped = silencers.stream().mapToInt(Silencer::silencedBreakpoints).sum();
return Values.json("records", records, "dropped", longOf(fields.get(field("dropped"))), "terminal", terminal,
"skippedBreakpoints", skipped, "sequentialized", sequentialized);
"skippedBreakpoints", skipped, "sequentialized", plan.sequentialize());
}
/**
+1 -24
Переглянути файл
@@ -40,8 +40,6 @@ public final class StreamCommand implements IDelegateCommandHandler {
private static final int GONE_KEPT = 16;
private static final AtomicLong IDS = new AtomicLong();
private static final Map<VirtualMachine, RealRunTrace> TRACES = new IdentityHashMap<>();
/** The {@code token} each trace was armed with: a client whose {@code arm} timed out releases by it. */
private static final Map<RealRunTrace, String> TOKENS = new IdentityHashMap<>();
/** By trace id, the answer {@link RealRunTrace#ended} gave: the trace itself would keep its dead VM's mirrors. */
private static final Map<Long, Map<String, Object>> GONE = new LinkedHashMap<>() {
private static final long serialVersionUID = 1L;
@@ -66,7 +64,6 @@ public final class StreamCommand implements IDelegateCommandHandler {
} catch (Failure e) {
Map<String, Object> gone = name.equals("arm") ? null : gone(args);
if (gone == null) throw e;
if (name.equals("release") && args.get("token") instanceof String) return InspectCommand.ok(Map.of());
return InspectCommand.ok(switch (name) {
case "wait" -> gone;
case "release" -> Map.of();
@@ -79,9 +76,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
case "stop" -> Values.json("records", trace(vm, args).stopRecording());
case "abort" -> trace(vm, args).abort();
case "collect" -> collect(vm, target, trace(vm, args));
case "release" -> args.get("token") instanceof String token && !(args.get("traceId") instanceof Number)
? releaseArmed(vm, token)
: release(vm, trace(vm, args));
case "release" -> release(vm, trace(vm, args));
default -> throw new IllegalArgumentException("unknown command " + command);
});
} catch (Failure e) {
@@ -136,7 +131,6 @@ public final class StreamCommand implements IDelegateCommandHandler {
RealRunTrace trace = RealRunTrace.arm(IDS.incrementAndGet(), vm, thread, plan, budget, target.generation(), hub);
synchronized (TRACES) {
TRACES.put(vm, trace);
if (args.get("token") instanceof String token) TOKENS.put(trace, token);
}
return trace.id;
}
@@ -172,27 +166,11 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (!trace.state().wire.equals("running")) {
synchronized (TRACES) {
TRACES.remove(vm, trace);
TOKENS.remove(trace);
}
}
return Map.of();
}
/**
* The trace armed with {@code token}, whose {@code arm} reply the client gave up on: released,
* so its breakpoints come back on. Under the arm lock, so an arm still setting up finishes first.
*/
private static Map<String, Object> releaseArmed(VirtualMachine vm, String token) {
synchronized (InspectCommand.handlesFor(vm)) {
RealRunTrace current;
synchronized (TRACES) {
current = TRACES.get(vm);
if (current == null || !token.equals(TOKENS.get(current))) return Map.of();
}
return release(vm, current);
}
}
/** Releases the traces of VMs java-debug no longer has; their requests and objects went with the VM. */
private static void forgetGone(List<VmInfo> vms) {
Set<VirtualMachine> live = Collections.newSetFromMap(new IdentityHashMap<>());
@@ -204,7 +182,6 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (live.contains(e.getKey())) continue;
RealRunTrace trace = e.getValue();
trace.vmGone();
TOKENS.remove(trace);
GONE.put(trace.id, trace.ended());
gone.add(trace);
i.remove();
-71
Переглянути файл
@@ -91,8 +91,6 @@ public class Real {
case "H": h(); break;
case "local": local(); break;
case "parallel": parallel(); break;
case "plocal": parallelLocal(); break;
case "elif": elseIf(); break;
case "nested": nested(); break;
case "hostile": hostile(); break;
case "sr": stopRecording(Integer.parseInt(a[1])); break;
@@ -169,20 +167,6 @@ public class Real {
System.out.println("P " + p + " " + q);
}
static void parallelLocal() {
Stream<Integer> s = nums.parallelStream();
List<Integer> r = s.map(x -> x + 1).collect(Collectors.toList()); // @plocal
System.out.println("PL " + r);
}
static void elseIf() {
if (nums.stream().anyMatch(x -> x > 100)) {
System.out.println("ELIF no");
} else if (nums.stream().anyMatch(x -> x == 8)) { // @elif
System.out.println("ELIF yes");
}
}
static void nested() {
long n = nums.stream().flatMap(x -> Stream.of(x, x)).count(); // @nested
System.out.println("NESTED " + n);
@@ -849,61 +833,6 @@ def real_run_parallel():
dbg.end()
@case
def real_run_parallel_local():
dbg = real('plocal')
try:
# No `parallel` in the chain: the stream was made parallel before the statement.
trace, state, _ = run_until_parked(dbg, 'plocal', root=None, local='s', steps=(spec('map', 1),), step_kinds=('sync',),
class_filters=('java.util.stream.*',))
c = step_out_and_collect(dbg, trace)
collected_ok('parallel local', c, records='0=5 1=6 0=3 1=4 0=8 1=9 0=1 1=2 0=4 1=5 0=2 1=3 0=9 1=10 0=6 1=7'.split())
check('parallel local: sequentialized', c['sequentialized'] is True, c['sequentialized'])
resume(dbg)
check('parallel local: program output', output_line(dbg, 'PL ') == 'PL [6, 4, 9, 2, 5, 3, 10, 7]')
finally:
dbg.end()
@case
def real_run_else_if():
dbg = real('elif')
try:
# Stopped on the `else if` line, the first condition's `stream()` has already returned.
trace, state, _ = run_until_parked(dbg, 'elif', steps=(), terminal=spec('anyMatch', 1), step_kinds=(), timeout=20)
check('else if: the trace parks with nothing skipped', state['state'] == 'parked', state)
c = step_out_and_collect(dbg, trace)
collected_ok('else if', c, terminal='true')
resume(dbg)
check('else if: program output', output_line(dbg, 'ELIF ') == 'ELIF yes')
finally:
dbg.end()
@case
def release_by_arm_token():
dbg = launch()
try:
def arm_with(token):
return stream('arm', dbg, threadId=dbg.thread, plan=plan('loop'), budget=50_000, token=token)
ok(arm_with('first'))
check('release by another token leaves the trace', ok(stream('release', dbg, token='other')) == {})
check('so the next arm is busy', error(arm_with('second')) == 'busy')
check('release by the arm\'s token answers {}', ok(stream('release', dbg, token='first')) == {})
trace = ok(arm_with('third'))['traceId']
check('arm works again after it', trace is not None, trace)
ok(stream('release', dbg, traceId=trace))
resume(dbg)
try:
body = expect_stop(dbg, 10, 'stop after release')
check('breakpoints are back after a release by token', body.get('reason') == 'breakpoint', body)
except TimeoutError:
check('breakpoints are back after a release by token', False, 'no stop within 10 s')
finally:
dbg.end()
@case
def real_run_nested():
dbg = real('nested')
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.47",
"version": "0.1.46",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+15 -40
Переглянути файл
@@ -150,7 +150,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` |
@@ -443,21 +443,6 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
`build.dependencies`) returns the Maven / Gradle graph the Dependency Analyzer
has, as a flat list with conflict and omission status, behind the low-risk
`build.read` capability. No build tool runs. See _Build dependency graph_.
- **Escape in the editor.** `[[contributes.keymaps]]` takes `key = "Escape"` with a
required `when`: the command runs on a plain Escape in a focused editor once the
IDE's own Escape handling (popups, completion, rename, selection, extra carets,
Vim) found nothing to do.
- **The marker bar's problems in editor panels.** An editor panel's page reads
the problems its group's marker bar shows with `openidea.editor.problems()`
and hears them change through `onProblems`. See _Editor panels_.
- **Semantic highlighting in editor panels.** `openidea.editor.highlights()`
returns the colours the editor shows, semantic highlighting from the language
server layered over the syntax colours, and `onHighlights` reports the lines
whose colours change when semantic tokens arrive. See _Editor panels_.
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
lines are folded with `openidea.editor.folded()`, how many rows each line takes
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
through `onLayout`. See _Editor panels_.
### API 1.9
@@ -1923,32 +1908,22 @@ sit side by side.
The page gets `openidea.editor` (only an editor panel's page has it). Lines are
0-based, columns UTF-16:
| `openidea.editor` | What it does |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the colour the editor shows in the current scheme (a CSS colour; API 1.10: semantic highlighting included) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
| `openidea.editor` | What it does |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the syntax colour in the current scheme (a CSS colour) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed |
Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
highlighting over it (a semantic colour wins where both apply). The
Colours come from syntax highlighting only (no semantic highlighting yet); the
panel's other colours are the frame's theme variables (`openidea.theme`,
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped` or
`onLayout`: check for them (`if (editor.problems)`) when the page also runs in
older IDEs. Outside the visible area the editor estimates wrapped rows from the
line's length until it lays the line out; `onLayout` follows when it does. Not
there yet: the caret and selections, and the marker bar's changes.
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
2 px, its frame draggable, problems marked at its right edge, folded lines left out) to install and try.
`onThemeChange`). Not there yet: the caret and selections, and the marker bar's
problems and changes. `crates/ide-plugin/tests/fixtures/editor-panel` is a
minimal minimap (each line 2 px, its frame draggable) to install and try.
### Web frame PTYs (API 1.3)
+1 -1
Переглянути файл
@@ -332,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
267 themeable tokens: 125 in the UI theme file, 142 in the editor colour scheme file.
### Surfaces (UI theme)
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+1 -2
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
world plugin {
import log;
@@ -20,7 +20,6 @@ world plugin {
import decorations;
import invocation;
import vcs;
import build;
import commit;
import events;
import tasks;
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+1 -10
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -135,10 +135,6 @@ interface views {
}
/// A comparison opened by a content action reply.
record content-diff { left: string, right: string, left-label: option<string>, right-label: option<string>, title: option<string> }
/// A file's before and after for `open-file-diff` (API 1.10): none is a side
/// where the file doesn't exist (an added file has no left side, a deleted
/// one no right side).
record file-diff { left: option<string>, right: option<string>, left-label: option<string>, right-label: option<string>, title: option<string> }
/// Optional updates to an outstanding action or Save request.
record content-tab-reply {
content: option<string>, saved: option<bool>, read-only: option<bool>,
@@ -160,11 +156,6 @@ interface views {
/// of a window. Each side at most 8 MiB (earlier hosts: 1 MiB); a larger
/// side fails with `invalid("diff too large: …")`.
open-diff: func(diff: content-diff, file-name: option<string>) -> result<_, error>;
/// `open-diff` for a file that may not exist on one side (API 1.10): the
/// diff viewer shows the existing side alone, as for the IDE's own added
/// and deleted files, instead of next to an empty text. Both sides none is
/// `invalid`.
open-file-diff: func(diff: file-diff, file-name: option<string>) -> result<_, error>;
/// The view (or every custom editor of that id) shows outdated content:
/// the IDE renders it again.
+1 -63
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.10.0;
package openidea:plugin@1.9.0;
interface workspace {
use types.{error, location};
@@ -227,65 +227,3 @@ interface vcs {
/// Long-running: call it inside a task.
fetch: func(project: borrow<project>) -> result<_, error>;
}
/// The Maven / Gradle dependency graph of a project, as the Dependency Analyzer
/// has it (API 1.10). Read-only: no call runs a build tool.
interface build {
use types.{error};
use workspace.{project};
/// How an occurrence of a dependency was resolved.
enum dependency-status {
/// Part of the resolved graph.
resolved,
/// Another version won (Maven: nearer the root; Gradle: the version the
/// build selected). `version` is the winner, `requested-version` what
/// this occurrence asked for.
omitted-for-conflict,
/// Listed with its dependencies elsewhere in the graph (Maven: a
/// duplicate or a cycle; Gradle: `(*)`); its children are not repeated.
omitted-for-duplicate,
/// The version comes from dependency management (Maven
/// `<dependencyManagement>`, a Gradle platform or constraint);
/// `requested-version` is the one declared here, when there is one.
version-managed,
}
/// One occurrence in the graph. Records don't nest, so the graph is a flat
/// list: `parent` is the index of the occurrence that brings this one in.
/// Each module is a root (`parent` none, empty `scope`) with its direct
/// dependencies under it, so walking `parent` up answers "why is this
/// artifact here".
record dependency-node {
/// Empty for a Gradle project of the build.
group: string,
/// Artifact id; a Gradle project's path (`:core`).
artifact: string,
/// The version in use; empty when there is none (a Gradle project of
/// the build) or it could not be resolved (Gradle `FAILED`).
version: string,
/// Maven scope (`compile`, `test`, …); the Gradle configuration
/// (`runtimeClasspath`, …).
scope: string,
status: dependency-status,
/// What this occurrence asked for, when it differs from `version`.
requested-version: option<string>,
parent: option<u32>,
}
/// The dependency graph of `module` (a Maven module's `groupId:artifactId`
/// or a Gradle project's path, `:` for the root project), or of every
/// module of the project's builds with `none`; an unknown module is
/// `not-found`. Answered from what the IDE already resolved:
///
/// - Maven: the trees of the last Reload in the Maven tool window (with
/// the occurrences Maven omitted); before one, or after a POM changed,
/// only the dependencies the POMs declare.
/// - Gradle: the configurations the Dependency Analyzer has read for the
/// project, until a build file changes; none read yet is the module's
/// own node only.
///
/// At most 100,000 nodes (else `failed`: ask for one module). Trusted
/// projects only; requires `build.read`.
dependencies: func(project: borrow<project>, module: option<string>) -> result<list<dependency-node>, error>;
}
-1
Переглянути файл
@@ -402,7 +402,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_has_hook,
vcs::vcs_merge_base,
vcs::vcs_create_patch,
vcs::vcs_pending_patch,
vcs::vcs_patch_preview,
vcs::vcs_apply_patch,
vcs::vcs_shelve,
-11
Переглянути файл
@@ -803,17 +803,6 @@ pub async fn vcs_create_patch(
ide_host::ops::vcs::vcs_create_patch(&state.host, window.label(), repo, source).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_pending_patch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
options: CommitOptions,
) -> IdeResult<String> {
ide_host::ops::vcs::vcs_pending_patch(&state.host, window.label(), repo, options).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_patch_preview(
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ mod tests {
use ide_core::IpcPath;
fn item(name: &str, path: &str) -> RecentProject {
RecentProject { path: IpcPath::from(path), name: name.into(), opened_at_ms: 0.0, branch: None, missing: false }
RecentProject { path: IpcPath::from(path), name: name.into(), opened_at_ms: 0.0, branch: None }
}
#[test]
-1
Переглянути файл
@@ -2056,7 +2056,6 @@ mod tests {
name: "openidea".into(),
opened_at_ms: 0.0,
branch: None,
missing: false,
}];
let items = recent_items(&recent, Some(Path::new("/home/me")));
assert_eq!(items[0].label, "openidea — ~/code/openidea");
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.47",
"version": "0.1.46",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
-1
Переглянути файл
@@ -649,7 +649,6 @@ vcs_move_worktree trusted project_host bin
vcs_open_external_log always project_host bindings async
vcs_operation trusted project_host bindings async
vcs_patch_preview trusted project_host bindings async
vcs_pending_patch trusted project_host bindings async
vcs_rebase trusted project_host bindings async
vcs_rebase_with trusted project_host bindings async
vcs_remote trusted project_host bindings async
-6
Переглянути файл
@@ -841,7 +841,6 @@ export const commands = {
/** The best common ancestor of `a` and `b` (`git merge-base`), if any. */
vcsMergeBase: (repo: string | null, a: string, b: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })),
vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { repo, source })),
vcsPendingPatch: (repo: string | null, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_pending_patch", { repo, options })),
vcsPatchPreview: (repo: string | null, patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })),
vcsApplyPatch: (repo: string | null, patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })),
/** Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. */
@@ -9588,11 +9587,6 @@ export type RecentProject = {
* refreshes it from `.git/HEAD` when the list is shown.
*/
branch: string | null,
/**
* The local folder no longer exists (set by [`with_live_branches`] when the list is shown): the
* welcome screen shows the entry as unavailable.
*/
missing?: boolean,
};
/** A named group of recent projects on the welcome screen (New Project Group…, Move to Group). */
+4 -1
Переглянути файл
@@ -20,7 +20,7 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
import { LINE_INSET } from "./lineInset";
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
import { BRACKET_COLORS, bracketScanner, type BracketScanner } from "./rainbowBrackets";
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
const GUIDE_SHIFT = 2;
@@ -188,6 +188,9 @@ export function braceGuide(state: EditorState, step: number): Guide | null {
return blockGuide(state, openLine.number, col, step);
}
/** Lines at least this long get no guides, and open no bracket block for them. */
const LONG_LINE = 10_000;
/**
* Bracket colour (depth within the palette) per guide level on each of the lines `first`..`last` (index `n - first`).
* The guide at `level` belongs to the block opened by the nearest line above indented
+1 -47
Переглянути файл
@@ -6,9 +6,7 @@ import { languages } from "@codemirror/language-data";
import {
BracketScanner,
DEFAULT_RAINBOW_OPTIONS,
LONG_LINE,
bracketClass,
bracketScanner,
rainbowBrackets,
type RainbowBracketOptions,
} from "./rainbowBrackets";
@@ -159,13 +157,7 @@ describe("rainbow brackets", () => {
});
it("keeps interpolation depth across chunks, viewports and edits", async () => {
// Newlines keep every line under `LONG_LINE`; the template still crosses chunk boundaries.
const doc =
"f(`" +
("literal ([ ".repeat(20) + "\n").repeat(30) +
"${g([1])}" +
(" tail ) ".repeat(20) + "\n").repeat(40) +
"`); h()";
const doc = "f(`" + "literal ([ ".repeat(500) + "${g([1])}" + " tail ) ".repeat(700) + "`); h()";
const ext = await javascript();
const scanner = new BracketScanner();
const from = doc.indexOf("[1]");
@@ -233,44 +225,6 @@ describe("rainbow brackets", () => {
expect(new BracketScanner().openAt(js, [js.doc.length]).map((m) => m?.depth)).toEqual([1]);
});
it("jumps over minified lines, keeping the nesting across them", async () => {
// The long line starts inside a scan chunk; one of its brackets is never closed.
const pad = "y()\n".repeat(1100);
const long = `f(${"x({a:[1,2]});".repeat(Math.ceil(LONG_LINE / 13))}`;
const doc = `{\n${pad}${long}\n[z]\n}`;
const from = doc.indexOf(long);
for (const ext of [cStyle, await javascript()]) expect(marks(doc, ext, from)).toEqual(["[1", "]1", "}0"]);
// One character shorter, it is scanned like any other line.
const short = "x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 1) / 13));
expect(marks(`{\n${short}\n[z]\n}`, cStyle).slice(0, 7)).toEqual(["{0", "(1", "{2", "[3", "]3", "}2", ")1"]);
const state = EditorState.create({ doc, extensions: cStyle });
expect(new BracketScanner().openAt(state, [doc.indexOf("[z]") + 1]).map((m) => m?.depth)).toEqual([1]);
});
it("drops a line's brackets once it grows past the limit and brings them back when it shrinks", () => {
// Checkpoints fall inside the line while it is short; its open `f(` must not leak past it once long.
const line = `f(${"x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 100) / 13))}`;
const doc = `${"y()\n".repeat(1100)}${line}\n[z]\n`;
const view = new EditorView({
state: EditorState.create({ doc, extensions: [cStyle, rainbowBrackets()] }),
parent: document.body,
});
const depthOfZ = () => {
const state = view.state;
const at = state.doc.toString().indexOf("[z]");
return bracketScanner(view)!
.marks(state, at, state.doc.length)
.map((m) => m.depth);
};
expect(depthOfZ()).toEqual([1, 1]);
const end = doc.indexOf("\n[z]");
view.dispatch({ changes: { from: end, insert: "x".repeat(200) } });
expect(depthOfZ()).toEqual([0, 0]);
view.dispatch({ changes: { from: end, to: end + 200 } });
expect(depthOfZ()).toEqual([1, 1]);
view.destroy();
});
it("is installed by the Rainbow brackets setting", () => {
const render = (rainbowBrackets: boolean) => {
const view = new EditorView({
+2 -22
Переглянути файл
@@ -64,12 +64,6 @@ const CHUNK = 4096;
const LOOKAHEAD = 64_000;
/** Longest comment / quote token the lexical scanner needs to see past a chunk end. */
const TOKEN_SLACK = 8;
/**
* Lines at least this long (minified code) are jumped over: their brackets are neither
* coloured nor counted, and they get no indent guides. Scanning one would cost time in
* proportion to its length after every keystroke, since the viewport always holds all of it.
*/
export const LONG_LINE = 10_000;
/** Closer char code of each opener char code: `(` `[` `{`. */
const CLOSER: Record<number, number> = { 40: 41, 91: 93, 123: 125 };
@@ -353,19 +347,7 @@ export class BracketScanner {
const blockFirst = comments.block ? comments.block.open.charCodeAt(0) : -1;
const angles: AngleEvents | undefined = tree && this.angleNames ? { doc, kindOf: this.kindOf, out: [] } : undefined;
while (s.pos < end) {
const line = doc.lineAt(s.pos);
if (line.length >= LONG_LINE && s.pos < line.to) {
// Intentionally leave minified lines unmarked and exclude their brackets from nesting.
// Resume at its line break, which ends a line comment or string as on a short line.
s.pos = line.to;
continue;
}
let chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
// A long line can start inside this chunk only on the chunk's last line: stop before it.
if (chunkEnd < doc.length) {
const last = doc.lineAt(chunkEnd);
if (last.from > s.pos && last.length >= LONG_LINE) chunkEnd = last.from;
}
const chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
const base = s.pos;
const text = doc.sliceString(base, Math.min(doc.length, chunkEnd + TOKEN_SLACK));
const stop = chunkEnd - base;
@@ -570,9 +552,7 @@ const plugin = ViewPlugin.fromClass(
if (reconfigured) this.scanner = new BracketScanner(options);
else if (u.docChanged) {
let first = Infinity;
// From the line start: a line grown past `LONG_LINE` must not keep checkpoints inside it.
const old = u.startState.doc;
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, old.lineAt(fromA).from)));
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, fromA)));
this.scanner.invalidate(first);
}
if (reconfigured || u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state))
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ export function installColorScheme(): () => void {
: null;
observer?.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme", "data-red-green"],
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme"],
});
return () => {
unsubscribe();
-13
Переглянути файл
@@ -92,19 +92,6 @@ describe("EditorController", () => {
expect(ctrl.nav.snapshot().entries.map((e) => e.path)).toEqual(["/p/x.ts", "/p/b.ts"]);
});
it("goes back to a diff closed without leaving it first", async () => {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a\n" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const diff = { kind: "diff", key: "diff:/p/a.ts", path: "/p/a.ts" };
await ctrl.openInput(diff, { preview: true });
await ctrl.closeEverything();
await ctrl.back();
expect(ctrl.activeInput()?.key).toBe(diff.key);
await ctrl.back();
expect(ctrl.activeSlot!.model.path).toBe("/p/a.ts");
});
it("goes back to a diff where it was left, open or closed", async () => {
// The diff viewer gives the input that reopens it at its caret.
const dispose = registerEditorKind({
-8
Переглянути файл
@@ -1566,14 +1566,6 @@ export class EditorController implements SlotHost {
Object.values(initial.panes).flatMap((p) => p.tabs.filter((t) => !remainingIds.has(t.id)).map((t) => t.id)),
);
const emptyPanes = paneIds(initial).filter((id) => !planned.panes[id] && !initial.panes[id]?.tabs.length);
// Closing the active diff leaves it as a place, so Back reopens it.
const active = this.activeInput();
if (
active &&
!isTextInput(active) &&
Object.values(initial.panes).some((p) => p.tabs.some((t) => targets.has(t.id) && t.input.key === active.key))
)
this.recordLeaving();
return this.enqueueRemoval(async () => {
if (generation !== this.projectGeneration || this.closeSession) return false;
const prepared: CustomDocument[] = [];
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more