дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-18 07:35:39 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7eed99745a | ||
|
|
ebc879dc8b | ||
|
|
7096a1c374 | ||
|
|
a1d4d6fb7f | ||
|
|
7596e95b76 | ||
|
|
cc471029d2 | ||
|
|
ee8afe39a2 | ||
|
|
5f606219b2 | ||
|
|
0590a255e8 | ||
|
|
32d5232010 | ||
|
|
382f5d71fa | ||
|
|
0cd7d9c30e | ||
|
|
dfbe87161b | ||
|
|
7a351fe4b0 | ||
|
|
153a184eac | ||
|
|
868f5b18d0 | ||
|
|
8d87b0de6e | ||
|
|
c791f2c34c | ||
|
|
a52e416ad5 | ||
|
|
a7464bf631 | ||
|
|
26810fbcbd | ||
|
|
72b17683c9 | ||
|
|
e916af15d4 | ||
|
|
88eeb57000 | ||
|
|
ba5c56ade8 | ||
|
|
88a5602239 | ||
|
|
907ed1d85f | ||
|
|
7f229acbd9 | ||
|
|
41bae970e0 | ||
|
|
44b5515432 | ||
|
|
64d5618cc7 |
No files matched your search
Створено
+45
-45
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4254,7 +4254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4268,7 +4268,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4297,7 +4297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4333,7 +4333,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4346,7 +4346,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4367,7 +4367,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4379,7 +4379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4410,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4483,7 +4483,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4502,7 +4502,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4524,7 +4524,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4536,7 +4536,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4553,7 +4553,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4562,7 +4562,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4573,7 +4573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4631,7 +4631,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4659,7 +4659,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4678,7 +4678,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4701,7 +4701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4724,7 +4724,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4738,7 +4738,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4758,7 +4758,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4782,7 +4782,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4798,7 +4798,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"flate2",
|
||||
@@ -4821,7 +4821,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4842,7 +4842,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4855,7 +4855,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4880,7 +4880,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4893,7 +4893,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4908,7 +4908,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4921,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4934,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4955,7 +4955,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4976,7 +4976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5002,7 +5002,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5018,7 +5018,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6647,7 +6647,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.46"
|
||||
version = "0.1.47"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -72,9 +72,8 @@ 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();
|
||||
if new.get("configOptions").is_some_and(Value::is_array)
|
||||
&& let Some(model) = model_option.and_then(|o| o.current.as_ref())
|
||||
{
|
||||
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()) {
|
||||
levels.insert(model.clone(), levels_for_model_from_slice(&options));
|
||||
}
|
||||
if let Some(selected) = selected_model
|
||||
@@ -88,7 +87,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) {
|
||||
settings
|
||||
Some(settings)
|
||||
} else {
|
||||
tokio::time::timeout(CONFIG_UPDATE_TIMEOUT, async {
|
||||
loop {
|
||||
@@ -106,9 +105,15 @@ async fn run_once(
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "The agent did not report settings for the selected model".to_owned())?
|
||||
.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()),
|
||||
};
|
||||
levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings));
|
||||
}
|
||||
let commands = updates
|
||||
.commands
|
||||
|
||||
@@ -774,6 +774,33 @@ 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();
|
||||
|
||||
@@ -47,13 +47,20 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def resources = p.tasks.named('processResources')
|
||||
p.tasks.register('openideaUpdateResources') {{
|
||||
dependsOn resources
|
||||
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
|
||||
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') }}
|
||||
}}
|
||||
// `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),
|
||||
@@ -172,7 +179,16 @@ 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.absolutePath"));
|
||||
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("build/resources/main")); // The task owns custom output locations.
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,8 @@ 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)
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
// Gradle 4.x has it as a convention property, not an extension.
|
||||
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('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.
|
||||
@@ -51,9 +52,12 @@ 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 = java?.toolchain?.languageVersion?.getOrNull()
|
||||
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
|
||||
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)
|
||||
} catch (ignored) {}
|
||||
println '@openidea-model\t' + JsonOutput.toJson(m)
|
||||
}
|
||||
|
||||
@@ -172,13 +172,25 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def warTask = p.tasks.named('war')
|
||||
p.tasks.register('openideaTomcatArtifact') {{
|
||||
dependsOn warTask
|
||||
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
|
||||
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')
|
||||
}}
|
||||
}}
|
||||
// `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),
|
||||
@@ -270,7 +282,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("archiveFile.get()"));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
|
||||
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
|
||||
}
|
||||
|
||||
@@ -297,7 +309,14 @@ 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("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,10 +167,11 @@ 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 {
|
||||
tasks.withType(JavaExec).configureEach {
|
||||
defaultCharacterEncoding = 'UTF-8'
|
||||
}
|
||||
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
|
||||
}
|
||||
";
|
||||
|
||||
@@ -621,10 +622,12 @@ mod tests {
|
||||
#[test]
|
||||
fn gradle_script_respects_the_builds_own_file_encoding() {
|
||||
let s = GRADLE_FILE_ENCODING_SCRIPT;
|
||||
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
|
||||
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
|
||||
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
|
||||
assert!(s.contains("t.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,11 +6,16 @@ use ide_run::wrap::{self, program_name};
|
||||
use std::path::Path;
|
||||
|
||||
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
|
||||
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) } }
|
||||
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
|
||||
}
|
||||
}
|
||||
"#;
|
||||
@@ -391,7 +396,10 @@ 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");
|
||||
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco"));
|
||||
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!(matches!(report, CoverageReportSpec::Jacoco { .. }));
|
||||
}
|
||||
|
||||
|
||||
@@ -1624,6 +1624,7 @@ 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(())
|
||||
}
|
||||
@@ -1672,6 +1673,7 @@ 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(())
|
||||
}
|
||||
@@ -1783,6 +1785,7 @@ 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(())
|
||||
}
|
||||
|
||||
@@ -116,6 +116,8 @@ 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>,
|
||||
@@ -281,6 +283,7 @@ 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()),
|
||||
}
|
||||
@@ -774,6 +777,7 @@ 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),
|
||||
|
||||
@@ -88,6 +88,32 @@ 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>,
|
||||
@@ -181,10 +207,30 @@ pub(crate) async fn run(
|
||||
if !s.suspended.get() {
|
||||
return unavailable(TraceUnavailable::NotSuspended);
|
||||
}
|
||||
let mut trace =
|
||||
Trace { mgr, s, tracer: &*tracer, target: &target, thread_id, progress, id: None, last: Counts::default() };
|
||||
// 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(),
|
||||
};
|
||||
match trace.drive(plan, cancel).await {
|
||||
Ok(run) => run,
|
||||
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
|
||||
}
|
||||
Err(run) => {
|
||||
// A stop from now on is the user's to see.
|
||||
set_running(s, false);
|
||||
@@ -231,6 +277,9 @@ 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,
|
||||
@@ -241,8 +290,9 @@ 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))
|
||||
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET, &self.token))
|
||||
.await?
|
||||
.map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?;
|
||||
self.id = Some(id);
|
||||
@@ -313,14 +363,20 @@ 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.
|
||||
/// 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.
|
||||
async fn release(&self) {
|
||||
let Some(id) = self.id else { return };
|
||||
if self.s.ended.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
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}");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ 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();
|
||||
@@ -96,6 +97,11 @@ 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 {
|
||||
@@ -443,6 +449,36 @@ 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());
|
||||
|
||||
@@ -179,7 +179,9 @@ fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
|
||||
}
|
||||
|
||||
fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
|
||||
let mut args: Vec<String> = (!file.is_empty()).then(|| format!("--file={file}")).into_iter().collect();
|
||||
// `~/.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}")));
|
||||
args.extend(flag(o.single_transaction, "--single-transaction"));
|
||||
args.extend(flag(o.stop_on_error, "--set=ON_ERROR_STOP=1"));
|
||||
args
|
||||
@@ -317,7 +319,7 @@ mod tests {
|
||||
let options = DbPsqlOptions { single_transaction: true, stop_on_error: true };
|
||||
assert_eq!(
|
||||
args(DbToolJob::Psql { file: "/tmp/shop.sql".into(), options }),
|
||||
["--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
|
||||
["--no-psqlrc", "--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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={}", source.database));
|
||||
args.push(format!("--dbname={}", dbname_arg(&source.database)));
|
||||
}
|
||||
// Without a terminal a password prompt would wait forever: fail instead.
|
||||
args.push("--no-password".into());
|
||||
@@ -271,6 +271,16 @@ 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>,
|
||||
@@ -404,6 +414,18 @@ 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() };
|
||||
|
||||
@@ -25,12 +25,17 @@ 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")));
|
||||
}
|
||||
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)) {
|
||||
if !roots.iter().any(|root| path.starts_with(root)) {
|
||||
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
|
||||
}
|
||||
Ok(Self(Some(path)))
|
||||
|
||||
@@ -883,14 +883,20 @@ 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() && dir.dir().is_none() {
|
||||
limit + 1
|
||||
} else {
|
||||
((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL)
|
||||
};
|
||||
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
|
||||
let found = {
|
||||
let (project, q) = (project.clone(), q.clone());
|
||||
host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await?
|
||||
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 mut items: Vec<SearchItem> = found
|
||||
.into_iter()
|
||||
@@ -910,10 +916,14 @@ 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 obey `scope` and `paths`; library symbols are what was asked for.
|
||||
let inside = location.uri.is_none() && !Path::new(&path).is_absolute();
|
||||
// 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)));
|
||||
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ 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,
|
||||
},
|
||||
|
||||
@@ -379,6 +379,10 @@ 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 });
|
||||
}
|
||||
|
||||
@@ -442,3 +442,20 @@ 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:?}");
|
||||
}
|
||||
@@ -1304,6 +1304,25 @@ 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,
|
||||
@@ -1663,6 +1682,9 @@ 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
|
||||
});
|
||||
|
||||
@@ -481,6 +481,27 @@ 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();
|
||||
|
||||
@@ -64,13 +64,15 @@ pub struct TraceCollected {
|
||||
}
|
||||
|
||||
pub trait StreamTracer: Send + Sync {
|
||||
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept.
|
||||
/// `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.
|
||||
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>;
|
||||
@@ -81,4 +83,7 @@ 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, ()>;
|
||||
}
|
||||
@@ -73,6 +73,33 @@ 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 {
|
||||
@@ -101,16 +128,20 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
|
||||
}
|
||||
|
||||
/// Comments, string literals and declared names, for spell checking.
|
||||
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
|
||||
pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> 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 };
|
||||
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
|
||||
match literal {
|
||||
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
|
||||
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
|
||||
Some(LiteralKind::String) => {
|
||||
let mut r = region(SpellingKind::String);
|
||||
r.raw = is_raw_string(&node, text);
|
||||
out.push(r);
|
||||
}
|
||||
None if node.is_named()
|
||||
&& node.child_count() == 0
|
||||
&& is_name_leaf(node.kind())
|
||||
|
||||
@@ -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, _| Some(literals::spelling_regions(tree)))
|
||||
self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
|
||||
}
|
||||
|
||||
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
|
||||
|
||||
@@ -1422,6 +1422,35 @@ 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
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
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.
|
||||
@@ -0,0 +1,643 @@
|
||||
<?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>
|
||||
@@ -182,9 +182,10 @@ 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});
|
||||
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget, "token": token});
|
||||
Ok(self.call::<Armed>("arm", target, args, COMMAND_TIMEOUT).await?.trace_id)
|
||||
})
|
||||
}
|
||||
@@ -223,6 +224,13 @@ 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)]
|
||||
|
||||
@@ -40,6 +40,7 @@ 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};
|
||||
@@ -3795,6 +3796,9 @@ 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
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -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).await.unwrap(), 3);
|
||||
assert_eq!(tracer.arm(&target, 7, &plan, 500, "t1").await.unwrap(), 3);
|
||||
s.respond(
|
||||
"workspace/executeCommand",
|
||||
json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}),
|
||||
@@ -3211,18 +3211,24 @@ 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}])),
|
||||
(
|
||||
json!("openidea.jvm.stream.arm"),
|
||||
json!([target_json, {"threadId": 7, "plan": plan, "budget": 500, "token": "t1"}])
|
||||
),
|
||||
(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"}])),
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -3303,7 +3309,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).await.unwrap_err(), expected, "{reply}");
|
||||
assert_eq!(tracer.arm(&target, 1, &json!({}), 10, "t").await.unwrap_err(), expected, "{reply}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
// scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out.
|
||||
const editor = window.openidea.editor;
|
||||
const canvas = document.getElementById("map");
|
||||
const ctx = canvas.getContext("2d");
|
||||
@@ -33,6 +33,10 @@
|
||||
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;
|
||||
|
||||
@@ -42,17 +46,39 @@
|
||||
};
|
||||
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, view.lineCount);
|
||||
const visible = Math.max(0, view.lastLine - view.firstLine);
|
||||
const L = Math.max(1, rowOf(view.lineCount));
|
||||
const firstRow = rowOf(view.firstLine);
|
||||
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
|
||||
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: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
|
||||
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
|
||||
}
|
||||
|
||||
function redraw() {
|
||||
@@ -65,7 +91,7 @@
|
||||
queued = false;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const W = canvas.clientWidth;
|
||||
const { H, offset, top, height } = layout();
|
||||
const { H, offset, top, height, L } = 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);
|
||||
@@ -74,11 +100,12 @@
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
if (!view) return;
|
||||
const first = Math.floor(offset / LINE);
|
||||
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
|
||||
const last = Math.min(L, Math.ceil((offset + H) / LINE));
|
||||
const missing = [];
|
||||
const muted = cssVar("--openidea-fg-muted");
|
||||
for (let i = first; i < last; i++) {
|
||||
const y = i * LINE - offset;
|
||||
for (let row = first; row < last; row++) {
|
||||
const i = lineOfRow(row);
|
||||
const y = row * LINE - offset;
|
||||
const line = text[i] || "";
|
||||
// Text without a syntax colour: faint, so the coloured spans stand out.
|
||||
ctx.globalAlpha = 0.2;
|
||||
@@ -95,6 +122,13 @@
|
||||
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");
|
||||
@@ -134,6 +168,9 @@
|
||||
}
|
||||
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();
|
||||
}
|
||||
@@ -151,6 +188,17 @@
|
||||
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);
|
||||
|
||||
@@ -158,7 +206,7 @@
|
||||
const scrollToFrameTop = (frameTop) => {
|
||||
const { range, visible, L } = layout();
|
||||
const p = Math.min(1, Math.max(0, frameTop / range));
|
||||
void editor.scrollTo(p * Math.max(0, L - visible));
|
||||
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
|
||||
};
|
||||
canvas.addEventListener("pointerdown", (e) => {
|
||||
if (!view) return;
|
||||
|
||||
@@ -26,9 +26,13 @@ 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 \
|
||||
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
|
||||
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
|
||||
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
|
||||
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
|
||||
}}\n"
|
||||
)
|
||||
}
|
||||
@@ -75,8 +79,10 @@ 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!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
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}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -53,6 +53,12 @@ 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 {
|
||||
@@ -72,7 +78,7 @@ pub(crate) fn java_runs(java: &Path) -> bool {
|
||||
return probe.runnable;
|
||||
}
|
||||
}
|
||||
let runnable = crate::exec::query(java, &["-version"], Duration::from_secs(5)).is_some();
|
||||
let runnable = crate::exec::query(java, &["-version"], JAVA_PROBE_TIMEOUT).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 },
|
||||
@@ -980,6 +986,26 @@ 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() {
|
||||
|
||||
@@ -24,6 +24,8 @@ 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.
|
||||
@@ -53,7 +55,7 @@ impl From<RegionKind> for TypoContext {
|
||||
fn from(kind: RegionKind) -> Self {
|
||||
match kind {
|
||||
RegionKind::Name => Self::Code,
|
||||
RegionKind::String => Self::Literal,
|
||||
RegionKind::String | RegionKind::RawString => Self::Literal,
|
||||
RegionKind::Comment => Self::Comment,
|
||||
RegionKind::Prose => Self::Prose,
|
||||
}
|
||||
@@ -89,7 +91,7 @@ impl SpellScope {
|
||||
pub fn includes(&self, kind: RegionKind) -> bool {
|
||||
match kind {
|
||||
RegionKind::Name => self.code,
|
||||
RegionKind::String => self.literals,
|
||||
RegionKind::String | RegionKind::RawString => self.literals,
|
||||
RegionKind::Comment => self.comments,
|
||||
RegionKind::Prose => true,
|
||||
}
|
||||
@@ -678,6 +680,15 @@ 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, ®ions, &|| 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 };
|
||||
|
||||
@@ -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 => Escapes::None,
|
||||
RegionKind::Name | RegionKind::RawString => Escapes::None,
|
||||
RegionKind::String => Escapes::Char,
|
||||
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
|
||||
};
|
||||
@@ -186,6 +186,17 @@ 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"]);
|
||||
|
||||
@@ -332,9 +332,10 @@ 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, which all ran;
|
||||
/// their branch bodies did not, since the later condition is only reached when
|
||||
/// they were skipped.
|
||||
/// 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.
|
||||
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" {
|
||||
@@ -344,12 +345,13 @@ 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"));
|
||||
regions.extend(outer.child_by_field_name("condition").filter(|c| c.start_position().row >= stop_row));
|
||||
region = outer;
|
||||
}
|
||||
regions
|
||||
|
||||
@@ -125,6 +125,7 @@ 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)
|
||||
|
||||
@@ -172,9 +172,17 @@ fn root_skip_counts_sibling_chain_in_if_header() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_skip_counts_earlier_condition_of_else_if() {
|
||||
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.
|
||||
let root = plan_of("C_PLAN_ELSE_IF").root.unwrap();
|
||||
assert_eq!(root, spec("stream", 0, 1));
|
||||
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)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -156,7 +156,9 @@ pub fn with_live_branches(mut items: Vec<RecentProject>) -> Vec<RecentProject> {
|
||||
/// 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();
|
||||
let wsl = text.starts_with(r"\\wsl$") || text.starts_with(r"\\wsl.localhost");
|
||||
// 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()
|
||||
}
|
||||
|
||||
@@ -258,6 +260,15 @@ 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();
|
||||
|
||||
@@ -902,3 +902,61 @@ 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);
|
||||
});
|
||||
@@ -70,7 +70,7 @@ async function stubRepositoryAndAgent(page: Page, reply: string) {
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => changes;
|
||||
h.vcs_create_patch = () => patch;
|
||||
h.vcs_pending_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,9 +131,11 @@ 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");
|
||||
expect(await ipcCalls(page, "vcs_create_patch")).toEqual([
|
||||
expect.objectContaining({ source: { from: "changes", paths: [`${ROOT}/build.gradle.kts`], reverse: false } }),
|
||||
]);
|
||||
// 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`] }) });
|
||||
// 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);
|
||||
|
||||
@@ -273,6 +273,60 @@ 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");
|
||||
|
||||
Бінарний файл не відображається.
@@ -6,6 +6,7 @@ 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;
|
||||
@@ -162,6 +163,8 @@ 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;
|
||||
@@ -240,11 +243,14 @@ 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.
|
||||
lastWrapped = wrap(held, nextStep++, plan.sequentialize());
|
||||
// A stream made parallel before this statement shows no `parallel` in the chain.
|
||||
sequentialized = plan.sequentialize() || isParallel(held);
|
||||
lastWrapped = wrap(held, nextStep++, sequentialized);
|
||||
// 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.
|
||||
@@ -402,7 +408,8 @@ final class RealRunTrace {
|
||||
}
|
||||
ObjectReference stream = returned(exit, root);
|
||||
setEnabled(false);
|
||||
replace(exit, wrap(stream, nextStep++, plan.sequentialize()));
|
||||
if (!sequentialized && isParallel(stream)) sequentialized = true;
|
||||
replace(exit, wrap(stream, nextStep++, sequentialized));
|
||||
return;
|
||||
}
|
||||
if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return;
|
||||
@@ -597,6 +604,11 @@ 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)));
|
||||
@@ -1008,7 +1020,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", plan.sequentialize());
|
||||
"skippedBreakpoints", skipped, "sequentialized", sequentialized);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,6 +40,8 @@ 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;
|
||||
@@ -64,6 +66,7 @@ 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();
|
||||
@@ -76,7 +79,9 @@ 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" -> release(vm, trace(vm, args));
|
||||
case "release" -> args.get("token") instanceof String token && !(args.get("traceId") instanceof Number)
|
||||
? releaseArmed(vm, token)
|
||||
: release(vm, trace(vm, args));
|
||||
default -> throw new IllegalArgumentException("unknown command " + command);
|
||||
});
|
||||
} catch (Failure e) {
|
||||
@@ -131,6 +136,7 @@ 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;
|
||||
}
|
||||
@@ -166,11 +172,27 @@ 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<>());
|
||||
@@ -182,6 +204,7 @@ 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();
|
||||
|
||||
@@ -91,6 +91,8 @@ 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;
|
||||
@@ -167,6 +169,20 @@ 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);
|
||||
@@ -833,6 +849,61 @@ 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.46",
|
||||
"version": "0.1.47",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
+35
-14
@@ -447,6 +447,17 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
|
||||
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
|
||||
|
||||
@@ -1912,22 +1923,32 @@ 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 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 |
|
||||
| `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 |
|
||||
|
||||
Colours come from syntax highlighting only (no semantic highlighting yet); the
|
||||
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
|
||||
panel's other colours are the frame's theme variables (`openidea.theme`,
|
||||
`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.
|
||||
`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.
|
||||
|
||||
### Web frame PTYs (API 1.3)
|
||||
|
||||
|
||||
@@ -332,7 +332,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
267 themeable tokens: 125 in the UI theme file, 142 in the editor colour scheme file.
|
||||
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.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,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.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,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.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,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.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,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -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.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
@@ -20,6 +20,7 @@ world plugin {
|
||||
import decorations;
|
||||
import invocation;
|
||||
import vcs;
|
||||
import build;
|
||||
import commit;
|
||||
import events;
|
||||
import tasks;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -135,6 +135,10 @@ 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>,
|
||||
@@ -156,6 +160,11 @@ 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,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.10.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -227,3 +227,65 @@ 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>;
|
||||
}
|
||||
@@ -402,6 +402,7 @@ 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,
|
||||
|
||||
@@ -803,6 +803,17 @@ 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,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.46",
|
||||
"version": "0.1.47",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -649,6 +649,7 @@ 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
|
||||
|
||||
@@ -841,6 +841,7 @@ 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. */
|
||||
|
||||
@@ -92,6 +92,19 @@ 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({
|
||||
|
||||
@@ -1566,6 +1566,14 @@ 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[] = [];
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEditorBanners, type EditorBannerContribution } from "@/workbench/con
|
||||
import { useDocMeta } from "../model/document";
|
||||
import styles from "./EditorArea.module.css";
|
||||
import { classFileBreakpointReason } from "@/platform/classFiles";
|
||||
import { gitRevisionOf } from "@/platform/virtualDocs";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useLibrarySources } from "../librarySources";
|
||||
@@ -50,7 +51,9 @@ export function VirtualBanner({
|
||||
? path.startsWith("csharp:")
|
||||
? tx("Decompiled assembly (read-only).")
|
||||
: tx("Decompiled .class file: sources are not available.")
|
||||
: tx("Library source (read-only).")}
|
||||
: gitRevisionOf(path)
|
||||
? tx("File at a Git revision (read-only).")
|
||||
: tx("Library source (read-only).")}
|
||||
{reason && ` ${tx(reason)}`}
|
||||
</span>
|
||||
{sources.message && <span>{tx(sources.message)}</span>}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useEditorPrefs } from "@/platform/editorSettings";
|
||||
import { basename, dirname } from "@/platform/project";
|
||||
import { gitRevisionOf } from "@/platform/virtualDocs";
|
||||
import {
|
||||
EDITOR_TAB_MIME,
|
||||
acceptsEditorDrop,
|
||||
@@ -204,7 +205,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
: t.input.kind === "file" && t.input.path
|
||||
? (hints.get(t.input.path) ?? null)
|
||||
: names.filter((n) => n === name).length > 1 && t.input.path
|
||||
? basename(dirname(t.input.path))
|
||||
? (gitRevisionOf(t.input.path)?.revision.slice(0, 8) ?? basename(dirname(t.input.path)))
|
||||
: null;
|
||||
const kindMark = tabTrailing(t.input, kinds);
|
||||
const pin = t.pinned ? <Icon name="pin" size={11} className={styles.pin} label="Pinned" /> : null;
|
||||
|
||||
@@ -10,7 +10,13 @@ import { BarButton, Icon, Menu, badgeKind, fileIconName } from "@/ui";
|
||||
import { notifications, useProjectViewLead } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { ENCODING_CHOICES, useEditorPrefs } from "@/platform/editorSettings";
|
||||
import { isUntitledUri, isVirtualUri, invalidateVirtualDocument, untitledTitle } from "@/platform/virtualDocs";
|
||||
import {
|
||||
gitRevisionOf,
|
||||
isUntitledUri,
|
||||
isVirtualUri,
|
||||
invalidateVirtualDocument,
|
||||
untitledTitle,
|
||||
} from "@/platform/virtualDocs";
|
||||
import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs } from "../controller";
|
||||
import { useDocMeta, useOutline } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
@@ -81,6 +87,20 @@ function pathCrumbs(project: { root: string; name: string } | null, path: string
|
||||
const label = untitledTitle(path);
|
||||
return [{ label, icon: fileIconName(label), title: label }];
|
||||
}
|
||||
// A file at a Git revision: the short revision, then the file's folders in the working tree.
|
||||
const revision = gitRevisionOf(path);
|
||||
if (revision) {
|
||||
const parts = revision.path.split("/");
|
||||
const file = parts.pop()!;
|
||||
return [
|
||||
{ label: revision.revision.slice(0, 8), icon: "commit", title: revision.revision },
|
||||
...parts.map((label, i): Crumb => {
|
||||
const at = `${revision.repo}/${parts.slice(0, i + 1).join("/")}`;
|
||||
return { label, icon: "folder", title: parts.slice(0, i + 1).join("/"), nav: { kind: "dir", path: at, label } };
|
||||
}),
|
||||
{ label: file, icon: fileIconName(file), title: revision.path },
|
||||
];
|
||||
}
|
||||
const target = dir ? path : dirname(path);
|
||||
const segments: Crumb[] = [];
|
||||
if (project && target !== project.root && !target.startsWith(project.root + "/")) project = null;
|
||||
|
||||
@@ -273,3 +273,22 @@ it("shows only the name of a new-file buffer", () => {
|
||||
expect(screen.getByRole("navigation", { name: "Breadcrumbs" }).textContent).toBe("Untitled-1");
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("shows the revision and the file's folders for a file at a Git revision", () => {
|
||||
useProject.setState({
|
||||
project: { root: "/repo", name: "repo", settings: {}, trusted: true, isGit: true },
|
||||
settings: { appearance: { navigationBar: "top" } } as unknown as Settings,
|
||||
});
|
||||
const target = JSON.stringify({
|
||||
repo: "/repo",
|
||||
revision: "617f744a0123456789abcdef0123456789abcdef",
|
||||
path: "web/src/app.ts",
|
||||
});
|
||||
const hex = Array.from(new TextEncoder().encode(target), (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
useEditorStatus.setState({ status: { ...caret(0, 0), path: `git-revision:${hex}/app.ts` } });
|
||||
const view = render(<Breadcrumbs className="nav" />);
|
||||
const crumbs = screen.getByRole("navigation", { name: "Breadcrumbs" });
|
||||
expect(crumbs.textContent).toBe("617f744awebsrcapp.ts");
|
||||
view.unmount();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
@@ -359,8 +359,19 @@ describe("applying completions", () => {
|
||||
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
|
||||
expect(view.state.selection.ranges).toHaveLength(2);
|
||||
const local: string[] = [];
|
||||
view.dispatch({
|
||||
effects: StateEffect.appendConfig.of(
|
||||
EditorView.updateListener.of((u) => {
|
||||
for (const tr of u.transactions)
|
||||
if (tr.docChanged && !tr.annotation(remoteChange)) local.push(tr.newDoc.toString());
|
||||
}),
|
||||
),
|
||||
});
|
||||
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.doc.toString()).toBe("p.refreshName()\nq.refreshName()\n");
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("p.refreshName()\nq.refreshName()\n"));
|
||||
// The repeated edit is the editor's own: the document model receives it.
|
||||
expect(local).toEqual(["p.refreshName()\nq.refreshName()\n"]);
|
||||
expect(view.state.selection.ranges.map((r) => r.head)).toEqual([15, 31]);
|
||||
expect(view.state.selection.main.head).toBe(15);
|
||||
} finally {
|
||||
@@ -368,6 +379,34 @@ describe("applying completions", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("repeats a server's insertion only at carets after the same typed text", async () => {
|
||||
setInvokeRoute(() => Promise.resolve(null));
|
||||
try {
|
||||
const { view, req } = setup("p.ref|\nq.oth\n", "", [
|
||||
completionExtension(),
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
]);
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(5), EditorSelection.cursor(11)], 0) });
|
||||
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
|
||||
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 2, 5, "insert");
|
||||
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(view.state.doc.toString()).toBe("p.refreshName()\nq.oth\n");
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("adds parentheses at each caret only where no call follows", () => {
|
||||
const { view, req } = setup("a.cr|\nb.cr()", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(4), EditorSelection.cursor(9)], 0) });
|
||||
applyLspCompletion(view, makeCompletion(item({ insertText: "create" }), req), 2, 4, "insert");
|
||||
expect(view.state.doc.toString()).toBe("a.create()\nb.create()");
|
||||
expect(view.state.selection.ranges.map((r) => r.head)).toEqual([9, 19]);
|
||||
});
|
||||
|
||||
it("does not register a scope when jumping outside closing brackets is off", () => {
|
||||
const { view, req } = setup("service.cr|");
|
||||
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type CompletionResult,
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { ChangeSet, EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
call,
|
||||
@@ -268,10 +268,11 @@ export function applyLspCompletion(
|
||||
.map((c) => ({ from: mapOld(c.from), to: mapOld(c.to), insert: c.insert }))
|
||||
.filter((c) => c.to <= start || c.from >= end);
|
||||
|
||||
if (applyAtCarets(view, completion, item, start, end, extra)) {
|
||||
const atCarets = applyAtCarets(view, completion, item, start, end, extra);
|
||||
if (atCarets) {
|
||||
if (item === completion.lsp && !item.additionalEdits.length && item.data != null)
|
||||
void applyLateEdits(view, completion, start);
|
||||
runCommand(view, item);
|
||||
runCommand(view, item, atCarets === true ? [] : atCarets);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -331,6 +332,7 @@ export function applyLspCompletion(
|
||||
* caret's (the typed prefix, and what a replacing edit overwrites), as IDEA completes at all
|
||||
* carets. Snippets go in as plain text with the caret at their first stop, since fields cannot
|
||||
* be edited at several places at once. False with a single caret, or no other caret matches.
|
||||
* For an item its server inserts: the other carets the server's edit is to be repeated at.
|
||||
*/
|
||||
function applyAtCarets(
|
||||
view: EditorView,
|
||||
@@ -339,13 +341,20 @@ function applyAtCarets(
|
||||
start: number,
|
||||
end: number,
|
||||
extra: { from: number; to: number; insert: string }[],
|
||||
): boolean {
|
||||
): boolean | number[] {
|
||||
const state = view.state;
|
||||
const { ranges, mainIndex } = state.selection;
|
||||
if (ranges.length < 2) return false;
|
||||
// The server inserts the item at the main caret; `caretAfterServerInsert` repeats it at the others.
|
||||
if (serverInserts(item)) return true;
|
||||
const head = state.selection.main.head;
|
||||
// The server inserts the item at the main caret; `caretAfterServerInsert` repeats it at the
|
||||
// others that have the same text before them.
|
||||
if (serverInserts(item)) {
|
||||
const prefix = state.sliceDoc(start, head);
|
||||
return ranges
|
||||
.filter((r, i) => i !== mainIndex && r.empty && r.head >= prefix.length)
|
||||
.filter((r) => state.sliceDoc(r.head - prefix.length, r.head) === prefix)
|
||||
.map((r) => r.head);
|
||||
}
|
||||
if (head < start || head > end) return false;
|
||||
const prefix = state.sliceDoc(start, head);
|
||||
const suffix = state.sliceDoc(head, end);
|
||||
@@ -364,19 +373,21 @@ function applyAtCarets(
|
||||
for (let i = 1; i < sites.length; i++) if (sites[i]!.from < sites[i - 1]!.to) return false;
|
||||
if (extra.some((c) => sites.some((site) => c.from < site.to && c.to > site.from))) return false;
|
||||
|
||||
let text: string;
|
||||
let caret: number;
|
||||
if (item.isSnippet) {
|
||||
({ text, caret } = lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path)));
|
||||
} else {
|
||||
// Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not.
|
||||
const textAt = (site: { from: number; to: number }): { text: string; caret: number } => {
|
||||
if (item.isSnippet) return lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path));
|
||||
const parens = editorPrefs().completion.insertParentheses
|
||||
? callParens(item, state.doc.lineAt(start), start, end)
|
||||
? callParens(item, state.doc.lineAt(site.from), site.from, site.to)
|
||||
: null;
|
||||
text = item.insertText + (parens ? "()" : "");
|
||||
caret = text.length - (parens === "inside" ? 1 : 0);
|
||||
}
|
||||
const changes = state.changes([...extra, ...sites.map((site) => ({ from: site.from, to: site.to, insert: text }))]);
|
||||
const cursors = sites.map((site) => EditorSelection.cursor(changes.mapPos(site.from, -1) + caret));
|
||||
const text = item.insertText + (parens ? "()" : "");
|
||||
return { text, caret: text.length - (parens === "inside" ? 1 : 0) };
|
||||
};
|
||||
const texts = sites.map(textAt);
|
||||
const changes = state.changes([
|
||||
...extra,
|
||||
...sites.map((site, i) => ({ from: site.from, to: site.to, insert: texts[i]!.text })),
|
||||
]);
|
||||
const cursors = sites.map((site, i) => EditorSelection.cursor(changes.mapPos(site.from, -1) + texts[i]!.caret));
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: EditorSelection.create(
|
||||
@@ -433,26 +444,73 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
|
||||
view.dispatch({ changes: edits, userEvent: "input.complete" });
|
||||
}
|
||||
|
||||
/** Where the caret was when an item its server inserts was picked, until that edit lands (`null`: none). */
|
||||
const awaitServerInsert = StateEffect.define<number | null>();
|
||||
const serverInsertAt = StateField.define<number | null>({
|
||||
/**
|
||||
* Where the caret was when an item its server inserts was picked, and the other carets to
|
||||
* repeat the edit at, until that edit lands (`null`: none).
|
||||
*/
|
||||
interface ServerInsert {
|
||||
at: number;
|
||||
others: readonly number[];
|
||||
}
|
||||
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
|
||||
const serverInsertAt = StateField.define<ServerInsert | null>({
|
||||
create: () => null,
|
||||
update(at, tr) {
|
||||
update(value, tr) {
|
||||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||||
// The edit landed, or the caret moved on before it did.
|
||||
if (at === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return tr.changes.mapPos(at, -1);
|
||||
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
|
||||
},
|
||||
});
|
||||
|
||||
/** The server's edit repeated at other carets: applied as a local edit, so it reaches the document model. */
|
||||
const mirrorServerInsert = StateEffect.define<{
|
||||
changes: { from: number; to: number; insert: string }[];
|
||||
main: number;
|
||||
}>();
|
||||
const applyServerInsertMirror = EditorView.updateListener.of((u) => {
|
||||
for (const tr of u.transactions)
|
||||
for (const e of tr.effects) {
|
||||
if (!e.is(mirrorServerInsert)) continue;
|
||||
const { view } = u;
|
||||
const doc = u.state.doc;
|
||||
const { changes, main } = e.value;
|
||||
queueMicrotask(() => {
|
||||
if (!view.dom.isConnected || view.state.doc !== doc) return;
|
||||
const mirror = view.state.changes(changes);
|
||||
const cursors = [
|
||||
{ pos: mirror.mapPos(main, 1), main: true },
|
||||
...changes.map((c) => ({ pos: mirror.mapPos(c.from, -1) + c.insert.length, main: false })),
|
||||
].sort((a, b) => a.pos - b.pos);
|
||||
view.dispatch({
|
||||
changes: mirror,
|
||||
selection: EditorSelection.create(
|
||||
cursors.map((c) => EditorSelection.cursor(c.pos)),
|
||||
cursors.findIndex((c) => c.main),
|
||||
),
|
||||
userEvent: "input.complete",
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
|
||||
* completion (a remote insertion at the caret would otherwise leave it in front).
|
||||
*/
|
||||
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
const at = tr.startState.field(serverInsertAt, false);
|
||||
const pending = tr.startState.field(serverInsertAt, false);
|
||||
const at = pending?.at;
|
||||
const caret = tr.startState.selection.main;
|
||||
if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr;
|
||||
if (
|
||||
pending == null ||
|
||||
at == null ||
|
||||
!tr.docChanged ||
|
||||
!tr.annotation(remoteChange) ||
|
||||
!caret.empty ||
|
||||
caret.head !== at
|
||||
)
|
||||
return tr;
|
||||
let edit: { from: number; to: number; insert: string } | null = null;
|
||||
tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
|
||||
if (!edit && fromA <= at && toA >= at) edit = { from: fromA, to: toA, insert: inserted.toString() };
|
||||
@@ -465,34 +523,20 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
const before = at - landed.from;
|
||||
const after = landed.to - at;
|
||||
const others: { from: number; to: number }[] = [];
|
||||
for (const r of tr.startState.selection.ranges) {
|
||||
if (r === caret || !r.empty) continue;
|
||||
const from = r.head - before;
|
||||
const to = r.head + after;
|
||||
for (const head of pending.others) {
|
||||
const from = head - before;
|
||||
const to = head + after;
|
||||
if (from < 0 || to > tr.startState.doc.length || tr.startState.sliceDoc(from, to) !== replaced) continue;
|
||||
if (tr.changes.touchesRange(from, to)) continue;
|
||||
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
|
||||
}
|
||||
if (!others.length) return [tr, { selection: EditorSelection.cursor(mainAfter), sequential: true }];
|
||||
const mirror = ChangeSet.of(
|
||||
others.map((o) => ({ from: o.from, to: o.to, insert: landed.insert })),
|
||||
tr.newDoc.length,
|
||||
);
|
||||
const cursors = [
|
||||
{ pos: mirror.mapPos(mainAfter, 1), main: true },
|
||||
...others.map((o) => ({ pos: mirror.mapPos(o.from, -1) + landed.insert.length, main: false })),
|
||||
].sort((a, b) => a.pos - b.pos);
|
||||
return [
|
||||
tr,
|
||||
{
|
||||
changes: mirror,
|
||||
selection: EditorSelection.create(
|
||||
cursors.map((c) => EditorSelection.cursor(c.pos)),
|
||||
cursors.findIndex((c) => c.main),
|
||||
),
|
||||
sequential: true,
|
||||
},
|
||||
];
|
||||
const selection = EditorSelection.cursor(mainAfter);
|
||||
if (!others.length) return [tr, { selection, sequential: true }];
|
||||
// Not part of this transaction: a remote one is not sent back to the document model.
|
||||
const changes = others
|
||||
.sort((a, b) => a.from - b.from)
|
||||
.map((o) => ({ from: o.from, to: o.to, insert: landed.insert }));
|
||||
return [tr, { selection, effects: mirrorServerInsert.of({ changes, main: mainAfter }), sequential: true }];
|
||||
});
|
||||
|
||||
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
|
||||
@@ -504,12 +548,12 @@ function serverInserts(item: CompletionItem): boolean {
|
||||
return !!cmd && !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.");
|
||||
}
|
||||
|
||||
function runCommand(view: EditorView, item: CompletionItem) {
|
||||
function runCommand(view: EditorView, item: CompletionItem, others: readonly number[] = []) {
|
||||
const command = item.command;
|
||||
if (!command?.command) return;
|
||||
const cmd = command.command;
|
||||
const serverInserted = serverInserts(item);
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) });
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
|
||||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||||
@@ -1021,6 +1065,7 @@ export function completionExtension() {
|
||||
lookupTracker,
|
||||
serverInsertAt,
|
||||
caretAfterServerInsert,
|
||||
applyServerInsertMirror,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* path through `@codemirror/lint` (wavy underlines, no gutter, no lint
|
||||
* tooltip — `hover.ts` renders diagnostics together with documentation).
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorSelection, StateEffect, StateField } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint";
|
||||
@@ -165,32 +165,52 @@ const MARK_COLOR: Partial<Record<Severity, string>> = {
|
||||
info: "var(--info)",
|
||||
};
|
||||
|
||||
/** A diagnostic's mark on the overview lane (the marker bar). */
|
||||
export interface ProblemMark extends ScrollbarMark {
|
||||
to: number;
|
||||
severity: Severity;
|
||||
}
|
||||
|
||||
/** Overview-lane (scrollbar) marks for diagnostics, errors on top. */
|
||||
export function diagnosticMarks(diags: readonly LintDiagnostic[]): ScrollbarMark[] {
|
||||
const out: ScrollbarMark[] = [];
|
||||
export function diagnosticMarks(diags: readonly LintDiagnostic[]): ProblemMark[] {
|
||||
const out: ProblemMark[] = [];
|
||||
for (const d of diags) {
|
||||
const color = MARK_COLOR[d.severity];
|
||||
if (!color || d.markClass?.includes("cm-lsp-unnecessary") || d.markClass?.includes("cm-lsp-typo")) continue;
|
||||
out.push({ from: d.from, to: d.to, color, tooltip: d.message, priority: 3 - SEVERITY_RANK[d.severity] });
|
||||
out.push({
|
||||
from: d.from,
|
||||
to: d.to,
|
||||
color,
|
||||
tooltip: d.message,
|
||||
priority: 3 - SEVERITY_RANK[d.severity],
|
||||
severity: d.severity,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const setMarks = StateEffect.define<readonly ScrollbarMark[]>();
|
||||
const setMarks = StateEffect.define<readonly ProblemMark[]>();
|
||||
|
||||
const marksField = StateField.define<readonly ScrollbarMark[]>({
|
||||
const marksField = StateField.define<readonly ProblemMark[]>({
|
||||
create: () => [],
|
||||
update(marks, tr) {
|
||||
for (const e of tr.effects) if (e.is(setMarks)) return e.value;
|
||||
if (!tr.docChanged || !marks.length) return marks;
|
||||
return marks.map((m) => {
|
||||
const from = tr.changes.mapPos(m.from);
|
||||
return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to ?? m.from)) };
|
||||
return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to)) };
|
||||
});
|
||||
},
|
||||
provide: (f) => scrollbarMarks.from(f),
|
||||
});
|
||||
|
||||
const NO_MARKS: readonly ProblemMark[] = [];
|
||||
|
||||
/** The problems the marker bar shows for `state`'s document, in document order; positions follow edits. */
|
||||
export function markerBarProblems(state: EditorState): readonly ProblemMark[] {
|
||||
return state.field(marksField, false) ?? NO_MARKS;
|
||||
}
|
||||
|
||||
const diagnosticsSync = ViewPlugin.fromClass(
|
||||
class {
|
||||
private unsubscribe: () => void;
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
*/
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { Prec, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
|
||||
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { commands, type SemanticTokens } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
@@ -207,6 +207,11 @@ const semanticField = StateField.define<DecorationSet>({
|
||||
},
|
||||
});
|
||||
|
||||
/** The semantic marks the editor shows over the syntax colours (empty without semantic highlighting). */
|
||||
export function semanticHighlights(state: EditorState): DecorationSet {
|
||||
return state.field(semanticField, false) ?? Decoration.none;
|
||||
}
|
||||
|
||||
const semanticPlugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
private refresh = debounce(() => void this.run(), 600);
|
||||
|
||||
@@ -574,17 +574,33 @@
|
||||
.markdown :global([data-mermaid-state="ok"] > pre) {
|
||||
display: none;
|
||||
}
|
||||
.markdown :global([align="left" i]) {
|
||||
--mermaid-align: left;
|
||||
--mermaid-margin-left: 0;
|
||||
--mermaid-margin-right: auto;
|
||||
}
|
||||
.markdown :global([align="right" i]) {
|
||||
--mermaid-align: right;
|
||||
--mermaid-margin-left: auto;
|
||||
--mermaid-margin-right: 0;
|
||||
}
|
||||
.markdown :global([align="center" i]),
|
||||
.markdown :global(center) {
|
||||
--mermaid-align: center;
|
||||
--mermaid-margin-left: auto;
|
||||
--mermaid-margin-right: auto;
|
||||
}
|
||||
.markdown :global(.mermaid-output) {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
text-align: center;
|
||||
text-align: var(--mermaid-align, center);
|
||||
/* Node labels are drawing, not text: selecting across a reply skips them. */
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
.markdown :global(.mermaid-output svg[data-natural-width]) {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
margin: 0 var(--mermaid-margin-right, auto) 0 var(--mermaid-margin-left, auto);
|
||||
width: calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ const backend = vi.hoisted(() => ({
|
||||
notify: vi.fn(),
|
||||
changes: vi.fn(),
|
||||
setMessage: vi.fn(),
|
||||
revision: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
@@ -35,7 +36,12 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: backend.notify }),
|
||||
maybeCommitService: () => ({ changes: backend.changes, setMessage: backend.setMessage, selection: vi.fn() }),
|
||||
maybeCommitService: () => ({
|
||||
changes: backend.changes,
|
||||
setMessage: backend.setMessage,
|
||||
revision: backend.revision,
|
||||
selection: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
@@ -183,6 +189,11 @@ describe("askingChoices", () => {
|
||||
expect(askingChoices([codex])).toEqual([{ id: "mode", value: "read-only" }]);
|
||||
});
|
||||
|
||||
it("prefers read-only over a mode that asks before it writes", () => {
|
||||
const codex = option("mode", "mode", ["read-only", "ask", "auto", "full-access"], "auto");
|
||||
expect(askingChoices([codex])).toEqual([{ id: "mode", value: "read-only" }]);
|
||||
});
|
||||
|
||||
it("turns allow-all permissions and bypassed approvals off", () => {
|
||||
const options = [
|
||||
option("permissions", "perm", ["on", "off"], "on"),
|
||||
@@ -278,6 +289,7 @@ describe("generateCommitMessage", () => {
|
||||
vi.clearAllMocks();
|
||||
backend.changes.mockResolvedValue(changes);
|
||||
backend.setMessage.mockReturnValue(true);
|
||||
backend.revision.mockReturnValue(changes.revision);
|
||||
backend.log.mockImplementation(() => ok([{ summary: "feat: earlier" }]));
|
||||
backend.cancel.mockImplementation(() => ok(null));
|
||||
backend.remove.mockImplementation(() => ok(null));
|
||||
@@ -377,6 +389,14 @@ describe("generateCommitMessage", () => {
|
||||
expect(backend.remove).toHaveBeenCalledWith("new", false);
|
||||
});
|
||||
|
||||
it("does not fill in a message for changes edited in the files while the agent worked", async () => {
|
||||
createdTask("ready");
|
||||
backend.changes.mockResolvedValueOnce(changes).mockResolvedValue({ ...changes, patch: changes.patch + "+more\n" });
|
||||
await generateCommitMessage();
|
||||
expect(backend.setMessage).not.toHaveBeenCalled();
|
||||
expect(notified()).toEqual([expect.objectContaining({ level: "info", title: "Commit message not replaced" })]);
|
||||
});
|
||||
|
||||
it("runs once at a time", async () => {
|
||||
createdTask("ready");
|
||||
await Promise.all([generateCommitMessage(), generateCommitMessage()]);
|
||||
|
||||
@@ -107,7 +107,7 @@ function modelChoice(options: readonly AgentConfigOption[]): AgentConfigChoice[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings that make the agent ask before it edits or runs anything. New tasks start
|
||||
* The settings that keep the agent read-only, or else make it ask before it edits or runs anything. New tasks start
|
||||
* in the mode that approves everything unless the user chose otherwise, and the changes
|
||||
* the agent reads here are text from the repository: they must not be able to run commands.
|
||||
*/
|
||||
@@ -116,7 +116,10 @@ export function askingChoices(options: readonly AgentConfigOption[]): AgentConfi
|
||||
const mode = modeOption(options);
|
||||
if (mode) {
|
||||
const asking = mode.values.filter((v) => ["lock", "eye"].includes(modeIcon(v.value)));
|
||||
const value = ["default", "ask"].map((p) => asking.find((v) => v.value === p)).find(Boolean) ?? asking[0];
|
||||
const value =
|
||||
asking.find((v) => /read-?only/i.test(v.value)) ??
|
||||
["default", "ask"].map((p) => asking.find((v) => v.value === p)).find(Boolean) ??
|
||||
asking[0];
|
||||
if (value) out.push({ id: mode.id, value: value.value });
|
||||
}
|
||||
const permissions = options.find((o) => o.category === "permissions");
|
||||
@@ -270,7 +273,15 @@ async function generate(): Promise<void> {
|
||||
await turnEnd(created.id);
|
||||
const message = commitMessageOf(replyOf(await call(commands.agentEntries(created.id, null))));
|
||||
if (!message) throw new Error(tx("The agent did not reply with a commit message"));
|
||||
if (!service.setMessage(changes.revision, message)) {
|
||||
// The files may have been edited since without touching the draft: the message must
|
||||
// still describe what would be committed.
|
||||
const unchanged = async () => {
|
||||
if (service.revision() !== changes.revision) return null;
|
||||
const now = await service.changes().catch(() => null);
|
||||
return now && now.patch === changes.patch ? now.revision : null;
|
||||
};
|
||||
const at = await unchanged();
|
||||
if (at === null || !service.setMessage(at, message)) {
|
||||
notify({
|
||||
level: "info",
|
||||
title: "Commit message not replaced",
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* after another (opened, cleaned, saved; tabs opened only for the run are closed
|
||||
* again). Cancellable from the Background Tasks popup.
|
||||
*/
|
||||
import { attachDocument } from "@/editor/api";
|
||||
import { cleanupFile, type CleanupOptions as FileCleanupOptions } from "@/editor/lsp/actions";
|
||||
import { call, commands, isTauri, type FileEntry } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -90,6 +91,20 @@ export async function cleanupFiles(choice: ScopeChoice): Promise<string[] | stri
|
||||
|
||||
let running: { cancelled: boolean } | null = null;
|
||||
|
||||
/**
|
||||
* Saves the file just cleaned up, as it is: save actions (format on save) would redo the
|
||||
* whole file after a reformat of only its changed text. Other unsaved files are left alone.
|
||||
*/
|
||||
async function saveCleaned(path: string): Promise<void> {
|
||||
const document = await attachDocument(path).catch(() => null);
|
||||
if (!document) return;
|
||||
try {
|
||||
await document.save({ exact: true });
|
||||
} finally {
|
||||
document.release();
|
||||
}
|
||||
}
|
||||
|
||||
interface RunSummary {
|
||||
/** Files processed before the end or a cancel. */
|
||||
done: number;
|
||||
@@ -131,7 +146,7 @@ async function runOverFiles(
|
||||
const result = await cleanupFile(path, options);
|
||||
if (result?.applied) summary.formatted++;
|
||||
if (result?.noFormatter) summary.noFormatter.push(path);
|
||||
await editors?.saveAll();
|
||||
await saveCleaned(path);
|
||||
if (!wasOpen.has(path) && (await editors?.closePath?.(path)) === false) {
|
||||
run.cancelled = true;
|
||||
break;
|
||||
|
||||
@@ -20,6 +20,17 @@ import {
|
||||
const pg = { id: "s1", name: "Shop / dev", driver: "postgres", host: "localhost", user: "app" } as DataSource;
|
||||
|
||||
describe("forms", () => {
|
||||
it("keep quoted names whole", () => {
|
||||
const options = dumpOptions({
|
||||
...DEFAULT_DUMP,
|
||||
schemas: '"My Schema", audit',
|
||||
tables: 'public."Order Items" "a,""b"".c"',
|
||||
excludeTables: "",
|
||||
});
|
||||
expect(options.schemas).toEqual(['"My Schema"', "audit"]);
|
||||
expect(options.tables).toEqual(['public."Order Items"', '"a,""b"".c"']);
|
||||
});
|
||||
|
||||
it("send the typed name lists as lists", () => {
|
||||
const options = dumpOptions({
|
||||
...DEFAULT_DUMP,
|
||||
|
||||
@@ -54,9 +54,9 @@ export const DEFAULT_RESTORE: RestoreForm = {
|
||||
|
||||
export const DEFAULT_PSQL: DbPsqlOptions = { singleTransaction: true, stopOnError: true };
|
||||
|
||||
/** `a, b c` → `["a", "b", "c"]`. */
|
||||
/** `a, b c` → `["a", "b", "c"]`; a double-quoted part keeps its spaces and commas: `public."Order Items"`. */
|
||||
export function nameList(text: string): string[] {
|
||||
return text.split(/[\s,]+/).filter(Boolean);
|
||||
return text.match(/(?:"(?:[^"]|"")*"|[^\s,"]|")+/g) ?? [];
|
||||
}
|
||||
|
||||
export function dumpOptions(f: DumpForm): DbPgDumpOptions {
|
||||
|
||||
@@ -267,12 +267,12 @@ function InstalledRow({ plugin, selected, onSelect }: { plugin: PluginInfo; sele
|
||||
{update && <Badge tone="accent">{tx("Update")}</Badge>}
|
||||
{plugin.status === "failed" && (
|
||||
<Badge dot tone="danger">
|
||||
<T>Failed</T>
|
||||
{tx("Failed")}
|
||||
</Badge>
|
||||
)}
|
||||
{plugin.status === "needsConsent" && (
|
||||
<Badge dot tone="warning">
|
||||
<T>Needs permission</T>
|
||||
{tx("Needs permission")}
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача