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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 4eb48de1e4 fix(terminal): keep Windows shell paths intact
The Shell path setting was split with POSIX rules, where a backslash
escapes the next character, so C:\Windows\system32\cmd.exe reached the
backend as C:Windowssystem32cmd.exe and every new terminal failed to
start. On Windows a backslash is now a path separator, and an unquoted
path up to its .exe/.cmd/.bat/.com is the program even with spaces, as
the Installed Shells menu and Browse set it. Paths picked there are
quoted when they contain whitespace.

Fixes #1327
2026-11-06 14:24:42 +08:00
238 змінених файлів з 1694 додано та 9471 видалено

No files matched your search

Створено
+37 -37
Переглянути файл
@@ -4106,7 +4106,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dunce",
"encoding_rs",
@@ -4129,7 +4129,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4143,7 +4143,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"serde",
@@ -4154,7 +4154,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"dirs 6.0.0",
@@ -4170,7 +4170,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
@@ -4179,7 +4179,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dunce",
"encoding_rs",
@@ -4196,7 +4196,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"ide-run",
@@ -4210,7 +4210,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"futures",
"ide-core",
@@ -4230,7 +4230,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"bb8",
"dirs 6.0.0",
@@ -4257,7 +4257,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"serde",
@@ -4270,7 +4270,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4290,7 +4290,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4302,7 +4302,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4315,7 +4315,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"base64 0.22.1",
"criterion",
@@ -4376,7 +4376,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"parking_lot",
@@ -4394,7 +4394,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"criterion",
@@ -4416,7 +4416,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"encoding_rs",
"futures",
@@ -4433,7 +4433,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"criterion",
@@ -4489,7 +4489,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dunce",
"futures",
@@ -4515,7 +4515,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"futures",
"ide-core",
@@ -4538,7 +4538,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"ide-core",
@@ -4559,7 +4559,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"ide-run",
@@ -4572,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"globset",
"ide-core",
@@ -4590,7 +4590,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dunce",
"encoding_rs",
@@ -4613,7 +4613,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dunce",
"ide-core",
@@ -4632,7 +4632,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"criterion",
"globset",
@@ -4652,7 +4652,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"parking_lot",
@@ -4665,7 +4665,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4687,7 +4687,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"ide-language",
@@ -4702,7 +4702,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"libc",
@@ -4715,7 +4715,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"criterion",
"ide-core",
@@ -4728,7 +4728,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"flate2",
"hex",
@@ -4749,7 +4749,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"dunce",
@@ -4770,7 +4770,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"chardetng",
"dunce",
@@ -4792,7 +4792,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"ide-core",
"open",
@@ -4808,7 +4808,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"blake3",
"dunce",
@@ -6357,7 +6357,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.38"
version = "0.1.37"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.38"
version = "0.1.37"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
-6
Переглянути файл
@@ -64,12 +64,6 @@ the [official plugins](plugins/official). The plugin API is still a preview.
<img src="docs/assets/wechat-group.png" alt="WeChat group QR code" width="200">
### Contributors
<a href="https://github.com/l0ng-ai/openidea/graphs/contributors">
<img src="https://contrib.rocks/image?repo=l0ng-ai/openidea&max=100" alt="OpenIDEA contributors">
</a>
## License
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
-5
Переглянути файл
@@ -125,11 +125,6 @@ impl Shared {
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
// A thinking level's values depend on the model (low/medium/high on one, none or a
// different set on another), but what ran last is remembered wholesale — after a
// model switch the New Task page would offer the previous model's levels. Until the
// session reports the new model's own, don't show the option at all.
config.retain(|o| o.category.as_deref() != Some("thought_level"));
config::add_client_options(provider, &mut config);
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
+3 -39
Переглянути файл
@@ -11,8 +11,6 @@ struct FakeAgent {
calls: Mutex<Vec<String>>,
/// Without `loadSession` (a session lives only as long as its process).
no_load: bool,
/// Config options `session/new` reports after the model one (per-model efforts, say).
extra_options: Mutex<Vec<Value>>,
}
impl FakeAgent {
@@ -96,15 +94,10 @@ impl Handler for FakeAgent {
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": !self.no_load,
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true}}}}))
}
"session/new" => {
let mut options = vec![json!({"id": "model", "category": "model", "type": "select",
"currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]})];
options.extend(self.extra_options.lock().iter().cloned());
Ok(json!({"sessionId": "s1",
"session/new" => Ok(json!({"sessionId": "s1",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": options}))
}
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]}]})),
"session/fork" => Ok(json!({"sessionId": "s2"})),
"_openidea/rollback" | "_openidea/steer" => {
let detail = params.get("turns").cloned().unwrap_or_else(|| params["prompt"][0]["text"].clone());
@@ -795,35 +788,6 @@ async fn usage_limits_and_late_settings() {
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
}
#[tokio::test(flavor = "multi_thread")]
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
// The effort list depends on the model: what the last session ran means nothing once
// the user picks another model, so the New Task page shows the option without a choice.
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
"type": "select", "currentValue": "high",
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
}
#[test]
fn retry_updates_become_a_countdown() {
let update =
+13 -7
Переглянути файл
@@ -234,12 +234,7 @@ pub fn plan(
Ok(BuildPlan { system, title, steps })
}
pub(super) fn maven_steps(
root: &Path,
model: &BuildModel,
kind: BuildKind,
module: Option<&Path>,
) -> IdeResult<Vec<BuildStep>> {
fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
let fallback;
let m = match &model.maven {
Some(m) => m,
@@ -388,7 +383,18 @@ fn go_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
fn package_manager(dir: &Path) -> &'static str {
ide_core::project_roots::package_manager(dir)
for d in dir.ancestors() {
if d.join("pnpm-lock.yaml").is_file() {
return "pnpm";
} else if d.join("yarn.lock").is_file() {
return "yarn";
} else if d.join("bun.lockb").is_file() || d.join("bun.lock").is_file() {
return "bun";
} else if d.join("package-lock.json").is_file() {
return "npm";
}
}
"npm"
}
fn has_build_script(dir: &Path) -> bool {
+16 -61
Переглянути файл
@@ -218,14 +218,21 @@ fn normalize(p: &Path) -> PathBuf {
out
}
/// The first automatically discovered build, for callers operating on one build.
/// The directory of the Gradle build under `root`: the root itself, or a direct
/// subfolder, holding a settings or build script.
pub fn build_dir(root: &Path) -> Option<PathBuf> {
build_dirs(root).into_iter().next()
}
fn build_dirs(root: &Path) -> Vec<PathBuf> {
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
ide_core::project_roots::discover(root, &markers)
let has = |d: &Path| SETTINGS_FILES.iter().chain(BUILD_FILES).any(|f| d.join(f).is_file());
if has(root) {
return Some(root.to_path_buf());
}
let mut dirs: Vec<PathBuf> = std::fs::read_dir(root)
.ok()?
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path())
.collect();
dirs.sort();
dirs.into_iter().find(|d| SETTINGS_FILES.iter().any(|f| d.join(f).is_file()))
}
fn wrapper(dir: &Path) -> String {
@@ -488,7 +495,7 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
/// Linked build identities without reading their scripts (also used by index hot paths).
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
match &settings.linked_projects {
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
None => build_dir(root).map(|dir| rel(root, &dir)).into_iter().collect(),
Some(dirs) => {
let mut out = Vec::new();
for dir in dirs {
@@ -679,55 +686,6 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn default_linkage_discovers_all_shallow_builds() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
for file in [
"Cargo.toml",
"package.json",
"fixtures/kotlin-gradle/settings.gradle.kts",
"fixtures/kotlin-gradle/build.gradle.kts",
"fixtures/kotlin-gradle/tools/settings.gradle",
"services/backend/api/settings.gradle",
"standalone/build.gradle",
"ignored/src/settings.gradle",
"ignored/out/build.gradle",
"node_modules/example/settings.gradle",
"target/example/build.gradle",
"build/example/settings.gradle",
"dist/example/build.gradle",
"vendor/example/settings.gradle",
".hidden/settings.gradle",
"too/deep/to/find/settings.gradle",
] {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let models = super::load_linked(root, &Default::default());
assert_eq!(
models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
["fixtures/kotlin-gradle", "ignored/src", "services/backend/api", "standalone"]
);
std::fs::write(root.join("build.gradle.kts"), "").unwrap();
let models = super::load_linked(root, &Default::default());
assert_eq!(models.len(), 1);
assert!(models[0].dir.is_empty());
}
#[cfg(unix)]
#[test]
fn default_linkage_does_not_follow_symlinks() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir(root.join("real")).unwrap();
std::fs::write(root.join("real/build.gradle"), "").unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("alias")).unwrap();
let models = super::load_linked(root, &Default::default());
assert_eq!(models.iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(), ["real"]);
}
#[test]
fn a_path_from_the_ui_finds_the_saved_link() {
let temp = tempfile::tempdir().unwrap();
@@ -760,10 +718,7 @@ mod tests {
std::fs::create_dir(root.join(dir)).unwrap();
std::fs::write(root.join(dir).join("settings.gradle"), format!("rootProject.name = '{dir}'")).unwrap();
}
assert_eq!(
super::load_linked(root, &Default::default()).iter().map(|m| m.dir.as_str()).collect::<Vec<_>>(),
["a", "b"]
);
assert_eq!(super::load_linked(root, &Default::default())[0].dir, "a");
let mut settings = ide_core::settings::GradleSettings {
linked_projects: Some(vec!["b".into(), "./b".into(), "a".into()]),
..Default::default()
+9 -116
Переглянути файл
@@ -53,12 +53,8 @@ pub struct Outcome {
pub success: bool,
}
/// Only linked Maven modules contribute sources to the bridge.
pub fn has_kotlin(root: &Path, model: &BuildModel) -> bool {
model.maven.iter().flat_map(|m| &m.projects).any(|p| has_kotlin_sources(&root.join(&p.dir)))
}
fn has_kotlin_sources(root: &Path) -> bool {
/// Inspect sources, excluding generated/build/VCS trees and never following symlinks.
pub fn has_kotlin(root: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(root) else { return false };
entries.flatten().any(|entry| {
let Ok(kind) = entry.file_type() else { return false };
@@ -70,25 +66,11 @@ fn has_kotlin_sources(root: &Path) -> bool {
entry.file_name().to_str(),
Some("target" | "build" | "out" | "bin" | "node_modules" | ".git" | ".openidea")
)
&& !["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]
.iter()
.any(|marker| entry.path().join(marker).is_file())
&& has_kotlin_sources(&entry.path())
&& has_kotlin(&entry.path())
}
})
}
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
}
Ok(compile::BuildPlan {
system: compile::BuildSystem::Maven,
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
})
}
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
pub fn build(
@@ -99,7 +81,10 @@ pub fn build(
cancel: &CancellationToken,
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model)?;
let mut plan = compile::plan(root, model, BuildKind::Build, None, None)?;
if plan.system != compile::BuildSystem::Maven {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
}
let mut manifests = Vec::new();
for (index, step) in plan.steps.iter_mut().enumerate() {
step.args.push("--fail-at-end".into());
@@ -462,106 +447,14 @@ mod tests {
assert_eq!(error.message, "Kotlin bridge requires a Maven build root");
}
#[test]
fn kotlin_sources_belong_to_linked_maven_modules() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for file in [
"java/pom.xml",
"gradle/build.gradle.kts",
"gradle/src/main/kotlin/App.kt",
"java/unlinked/pom.xml",
"java/unlinked/src/main/kotlin/App.kt",
"java/gradle/settings.gradle.kts",
"java/gradle/src/main/kotlin/App.kt",
"java/target/generated/Old.kt",
"java/node_modules/dependency/App.kt",
"java/linked/pom.xml",
"java/linked/src/test/kotlin/Test.kt",
] {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let mut model = BuildModel {
maven: Some(crate::MavenModel {
projects: vec![crate::MavenProject { dir: "java".into(), ..Default::default() }],
..Default::default()
}),
..Default::default()
};
assert!(!has_kotlin(root, &model));
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
dir: "java/linked".into(),
aggregated: true,
..Default::default()
});
assert!(has_kotlin(root, &model));
model.maven.as_mut().unwrap().projects.clear();
assert!(!has_kotlin(root, &model));
assert!(!has_kotlin(root, &BuildModel::default()));
}
#[test]
fn maven_bridge_ignores_the_workspace_build_system() {
for marker in ["Cargo.toml", "package.json", "build.gradle.kts", "go.mod", "CMakeLists.txt"] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join(marker), "").unwrap();
let mut model = BuildModel { maven: Some(crate::MavenModel::default()), ..Default::default() };
for name in ["java", "kotlin"] {
let module = root.join(name);
std::fs::create_dir_all(&module).unwrap();
model.maven.as_mut().unwrap().projects.push(crate::MavenProject {
dir: name.into(),
command: format!("{name}-mvnw"),
options: vec!["-o".into(), "-Peditor".into()],
env: BTreeMap::from([("JAVA_HOME".into(), "/jdk".into())]),
..Default::default()
});
}
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
assert!(has_kotlin(root, &model), "{marker}");
let plan = plan(root, &model).unwrap();
assert_eq!(plan.system, compile::BuildSystem::Maven);
assert_eq!(plan.steps.len(), 2);
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
assert_eq!(step.cwd, root.join(name));
assert_eq!(step.program, format!("{name}-mvnw"));
assert_eq!(step.args, ["-B", "-Dstyle.color=never", "-o", "-Peditor", "test-compile"]);
assert_eq!(step.env.get("JAVA_HOME").map(String::as_str), Some("/jdk"));
}
}
}
#[test]
fn external_linked_maven_sources_are_included() {
let workspace = tempfile::tempdir().unwrap();
let external = tempfile::tempdir().unwrap();
std::fs::write(external.path().join("App.kt"), "class App").unwrap();
let model = BuildModel {
maven: Some(crate::MavenModel {
projects: vec![crate::MavenProject {
dir: external.path().to_string_lossy().into_owned(),
command: "mvn".into(),
..Default::default()
}],
..Default::default()
}),
..Default::default()
};
assert!(has_kotlin(workspace.path(), &model));
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
}
#[test]
fn does_not_find_deleted_sources_in_build_outputs() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("target/generated")).unwrap();
std::fs::write(dir.path().join("target/generated/Old.kt"), "").unwrap();
assert!(!has_kotlin_sources(dir.path()));
assert!(!has_kotlin(dir.path()));
std::fs::write(dir.path().join("New.kt"), "").unwrap();
assert!(has_kotlin_sources(dir.path()));
assert!(has_kotlin(dir.path()));
}
#[test]
+41 -1
Переглянути файл
@@ -1013,7 +1013,10 @@ pub(crate) fn plugin(
// ---------------------------------------------------------------- loading
/// Directories never searched for POMs.
const SKIP_DIRS: &[&str] = &["node_modules", "target", "build", "out", "dist", "src", "vendor"];
const MAX_PROJECTS: usize = 1000;
const POM_SEARCH_DEPTH: usize = 3;
fn rel_path(root: &Path, p: &Path) -> String {
p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/")
@@ -1024,7 +1027,44 @@ fn rel_path(root: &Path, p: &Path) -> String {
/// aggregate POM directly inside `src/` counts too (issue #1001: `src/pom.xml`
/// with its modules beside it, `src/app/pom.xml` and so on).
fn top_level_poms(root: &Path) -> Vec<PathBuf> {
ide_core::project_roots::discover(root, &["pom.xml"]).into_iter().map(|dir| dir.join("pom.xml")).collect()
let top = root.join("pom.xml");
if top.is_file() {
return vec![top];
}
let mut out = Vec::new();
let src_pom = root.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
let mut queue: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = queue.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
let mut dirs: Vec<PathBuf> = Vec::new();
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if e.file_type().is_ok_and(|t| t.is_dir()) && !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_str())
{
dirs.push(e.path());
}
}
dirs.sort();
for d in dirs.into_iter().rev() {
let pom = d.join("pom.xml");
if pom.is_file() {
out.push(pom);
continue;
}
let src_pom = d.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
if depth + 1 < POM_SEARCH_DEPTH {
queue.push((d, depth + 1));
}
}
}
out.sort();
out
}
/// Whether `root` holds a Maven build (cheap: the same search as [`load`] without parsing).
-1
Переглянути файл
@@ -16,7 +16,6 @@ pub mod jsonc;
pub mod output_encoding;
pub mod process;
pub mod project_dir;
pub mod project_roots;
pub mod proxy_settings;
pub mod remote_settings;
pub mod settings;
-197
Переглянути файл
@@ -1,197 +0,0 @@
//! Shared filesystem rules for discovering builds and resolving their owners.
use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
.flatten()
.filter(|entry| {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
})
.map(|entry| entry.path())
.collect();
dirs.sort();
dirs
}
pub fn discover(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
discover_matching(root, SEARCH_DEPTH, true, |dir| markers.iter().any(|marker| dir.join(marker).is_file()))
}
pub fn discover_matching(
root: &Path,
max_depth: usize,
stop_at_match: bool,
marked: impl Fn(&Path) -> bool,
) -> Vec<PathBuf> {
let mut found = Vec::new();
let mut pending = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = pending.pop() {
if marked(&dir) {
found.push(dir.clone());
if stop_at_match {
continue;
}
}
// A source folder may itself be a build root (e.g. src/pom.xml), but
// source trees without their own build marker are never searched.
let source = dir.join("src");
if source.is_dir() && !source.is_symlink() && marked(&source) {
found.push(source);
}
if depth < max_depth {
pending.extend(
children(&dir)
.into_iter()
.rev()
.filter(|child| !child.ends_with("src"))
.map(|child| (child, depth + 1)),
);
}
}
found.sort();
found.dedup();
found
}
/// The closest package manager declaration or lockfile, shared by build and run.
pub fn package_manager(root: &Path) -> &'static str {
for dir in root.ancestors() {
let package = std::fs::read(dir.join("package.json"))
.ok()
.and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
if let Some(pm) = package.as_ref().and_then(|p| p.get("packageManager")).and_then(|p| p.as_str()) {
match pm.split('@').next().unwrap_or_default() {
"pnpm" => return "pnpm",
"yarn" => return "yarn",
"bun" => return "bun",
"npm" => return "npm",
_ => {}
}
}
for (marker, pm) in [
("pnpm-lock.yaml", "pnpm"),
("yarn.lock", "yarn"),
("bun.lock", "bun"),
("bun.lockb", "bun"),
("package-lock.json", "npm"),
] {
if dir.join(marker).is_file() {
return pm;
}
}
}
"npm"
}
pub fn resolve(root: &Path, path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in root.join(path).components() {
match component {
Component::CurDir => {}
Component::ParentDir if out.file_name().is_some() => {
out.pop();
}
component => out.push(component),
}
}
out
}
pub fn relative(root: &Path, path: &Path) -> PathBuf {
let path = resolve(root, path);
path.strip_prefix(resolve(root, Path::new(""))).unwrap_or(&path).to_path_buf()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn package_manager_declarations_are_shared_by_build_and_run() {
let temp = tempfile::tempdir().unwrap();
std::fs::write(temp.path().join("pnpm-lock.yaml"), "").unwrap();
let child = temp.path().join("packages/web");
std::fs::create_dir_all(&child).unwrap();
assert_eq!(package_manager(&child), "pnpm");
std::fs::write(child.join("package.json"), r#"{"packageManager":"[email protected]"}"#).unwrap();
assert_eq!(package_manager(&child), "yarn");
}
#[test]
fn discovery_has_one_depth_boundary_and_exclusion_policy_for_all_families() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let markers = [
"package.json",
"Cargo.toml",
"go.mod",
"pom.xml",
"build.gradle.kts",
"pyproject.toml",
"composer.json",
"Gemfile",
"CMakeLists.txt",
"project.godot",
"deno.json",
"Makefile",
"justfile",
];
for marker in markers {
for dir in [
"apps/one",
"services/backend/two",
"src",
"a/b/c/src",
"too/deep/to/find",
"node_modules/ignored",
"target/ignored",
"build/ignored",
"vendor/ignored",
".hidden",
"src/ignored",
] {
let path = root.join(dir).join(marker);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
assert_eq!(
discover(root, &[marker]),
["a/b/c/src", "apps/one", "services/backend/two", "src"].map(|dir| root.join(dir))
);
}
std::fs::write(root.join("Cargo.toml"), "").unwrap();
assert_eq!(discover(root, &["Cargo.toml"]), [root]);
}
#[cfg(unix)]
#[test]
fn discovery_never_follows_directory_symlinks() {
let temp = tempfile::tempdir().unwrap();
std::fs::create_dir(temp.path().join("real")).unwrap();
std::fs::write(temp.path().join("real/go.mod"), "").unwrap();
std::os::unix::fs::symlink(temp.path().join("real"), temp.path().join("alias")).unwrap();
assert_eq!(discover(temp.path(), &["go.mod"]), [temp.path().join("real")]);
}
#[test]
fn paths_keep_component_boundaries_and_external_roots() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("workspace");
assert_eq!(relative(&root, &root.join("apps/../api")), Path::new("api"));
assert_eq!(relative(&root, &temp.path().join("workspace-other")), temp.path().join("workspace-other"));
assert_eq!(resolve(&root, Path::new("./api/../web")), root.join("web"));
}
}
+1 -27
Переглянути файл
@@ -196,18 +196,10 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
dirs
}
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
fn adapter_path(env: &[(String, String)]) -> Option<std::ffi::OsString> {
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
(!own).then(ide_core::tool_path::search_path)
}
/// Directories searched for adapter binaries: managed tools first, then `PATH` and the usual install spots.
fn search_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = tools_root().map(|r| managed_dirs(&r)).unwrap_or_default();
dirs.extend(std::env::split_paths(&ide_core::tool_path::search_path()));
dirs.extend(std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default());
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
for rel in [".cargo/bin", ".local/bin", "go/bin", ".dotnet/tools", ".bun/bin", ".npm-global/bin", ".volta/bin"]
{
@@ -472,9 +464,6 @@ impl AdapterLauncher for ProcessLauncher {
None => args,
};
let mut cmd = Command::new(&binary);
if let Some(path) = adapter_path(&spec.env) {
cmd.env("PATH", path);
}
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
@@ -603,21 +592,6 @@ async fn connect_with_retries(
mod tests {
use super::*;
#[test]
fn adapters_run_on_the_tool_search_path() {
let search = ide_core::tool_path::search_path();
assert_eq!(adapter_path(&[]), Some(search.clone()));
assert_eq!(adapter_path(&[("GOFLAGS".into(), "-mod=mod".into())]), Some(search));
// A launch that sets its own (a selected Go SDK's bin first) keeps it.
assert_eq!(adapter_path(&[("PATH".into(), "/sdk/go/bin:/usr/bin".into())]), None);
// The search path reaches the usual install spots even when this process's `PATH` doesn't.
#[cfg(unix)]
{
let dirs: Vec<PathBuf> = std::env::split_paths(&ide_core::tool_path::search_path()).collect();
assert!(dirs.contains(&PathBuf::from("/usr/local/bin")), "{dirs:?}");
}
}
#[tokio::test]
async fn program_output_is_forwarded_without_the_adapter_banner() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
-32
Переглянути файл
@@ -530,34 +530,6 @@ fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
.collect()
}
/// Delve compiles the debuggee to `__debug_bin` in the session's cwd (on Windows
/// `__debug_bin.exe` plus `__debug_bin.exe<digits>` in DAP mode) and removes it on a
/// graceful exit — a shutdown it doesn't always reach, so the files pile up. Sweep
/// the leftovers once the session is down. Runs after `session_closed`, so Delve
/// has already exited or been killed and holds no file locks; a leftover of a
/// still-building run is removed on that run's own shutdown.
fn remove_delve_binaries(cwd: &Path) {
let Ok(entries) = std::fs::read_dir(cwd) else { return };
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
// Windows writes `__debug_bin.exe` (and `.exe<digits>` in DAP mode); other
// platforms keep the bare name. Suffixes like `.go` are user files.
let suffix = name.strip_prefix("__debug_bin");
let leftover = suffix.is_some_and(|s| {
s.is_empty()
|| s == ".exe"
|| (s.starts_with(".exe") && s[".exe".len()..].chars().all(|c| c.is_ascii_digit()))
});
if leftover
&& entry.file_type().is_ok_and(|t| t.is_file())
&& let Err(e) = std::fs::remove_file(entry.path())
{
tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display());
}
}
}
pub(crate) fn variable_from(v: &Value) -> Variable {
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
Variable {
@@ -1009,10 +981,6 @@ impl DebugManager {
}
s.conn.close();
self.session_closed(s);
if s.adapter == "delve" && s.spec.server_host.is_none() {
let cwd = s.spec.cwd.clone();
tokio::task::spawn_blocking(move || remove_delve_binaries(&cwd));
}
}
/// Breakpoints are kept per file even without a session and sent on start.
-23
Переглянути файл
@@ -1347,26 +1347,3 @@ fn flutter_projects_are_found_from_the_program_or_the_working_directory() {
assert!(!is_flutter_project(&root, None));
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn delve_leftovers_are_removed_without_touching_other_files() {
let dir = std::env::temp_dir().join(format!("openidea-delve-bin-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
std::fs::write(dir.join(name), b"bin").unwrap();
}
// Lookalikes that are not Delve's own binaries stay: sources, a future
// in-progress build, and a directory that happens to share the name.
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go"] {
std::fs::write(dir.join(name), b"keep").unwrap();
}
std::fs::create_dir(dir.join("__debug_bin.dir")).unwrap();
remove_delve_binaries(&dir);
for name in ["__debug_bin", "__debug_bin.exe", "__debug_bin.exe3323301925"] {
assert!(!dir.join(name).exists(), "{name} should be gone");
}
for name in ["__debug_bin.go", "__debug_bin.go.exe", "main.go", "__debug_bin.dir"] {
assert!(dir.join(name).exists(), "{name} should stay");
}
std::fs::remove_dir_all(&dir).unwrap();
}
+3 -57
Переглянути файл
@@ -54,10 +54,6 @@ pub struct Manifest {
pub change_notes: Option<String>,
/// Marketplace categories as declared (see [`Manifest::categories`]).
pub declared_categories: Vec<String>,
/// SVG shown in Settings › Plugins and the marketplace.
pub icon: Option<PathBuf>,
/// Its variant for dark themes.
pub icon_dark: Option<PathBuf>,
/// `engines.openidea` (a semver requirement), or the legacy `openidea-api`.
pub engine: String,
/// Written in the 0.1 format.
@@ -179,10 +175,6 @@ struct Raw {
#[serde(default)]
categories: Vec<String>,
#[serde(default)]
icon: Option<PathBuf>,
#[serde(default)]
icon_dark: Option<PathBuf>,
#[serde(default)]
engines: Option<Engines>,
/// 0.1 format.
#[serde(default)]
@@ -261,8 +253,6 @@ impl Manifest {
license: raw.license,
change_notes: raw.change_notes,
declared_categories: raw.categories,
icon: raw.icon,
icon_dark: raw.icon_dark,
engine,
legacy,
wasm: raw.wasm,
@@ -280,16 +270,6 @@ impl Manifest {
Self::parse(&src).map_err(|e| format!("{}: {e}", path.display()))
}
/// Refuses `what`, new in plugin API 1.`minor`, while `engines.openidea`
/// still admits an older 1.x: those IDEs reject the manifest at install.
pub fn needs_api(&self, what: &str, minor: u64) -> Result<(), String> {
let older = |m| engine_compatible_with(&self.engine, &semver::Version::new(1, m, u64::MAX));
if self.legacy || (0..minor).any(older) {
return Err(format!("{what} is new in plugin API 1.{minor}: set engines.openidea to \"^1.{minor}\""));
}
Ok(())
}
fn validate(&self) -> Result<(), String> {
validate_plugin_id(&self.id)?;
if self.name.trim().is_empty() {
@@ -311,16 +291,6 @@ impl Manifest {
if let Some(wasm) = &self.wasm {
check_relative(wasm, "wasm")?;
}
if let Some(icon) = &self.icon {
self.needs_api("`icon`", 2)?;
check_relative(icon, "icon")?;
}
if let Some(dark) = &self.icon_dark {
if self.icon.is_none() {
return Err("`icon-dark` needs `icon`".into());
}
check_relative(dark, "icon-dark")?;
}
if self.wasm.is_none() && !self.activation.is_empty() {
return Err("`activation` needs `wasm`: there is no code to activate".into());
}
@@ -406,11 +376,9 @@ pub fn engine_compatible(engine: &str, legacy: bool) -> bool {
if legacy {
return engine == LEGACY_API || engine.strip_prefix(LEGACY_API).is_some_and(|rest| rest.starts_with('.'));
}
engine_compatible_with(engine, &semver::Version::parse(ENGINE_VERSION).expect("valid engine version"))
}
fn engine_compatible_with(engine: &str, api: &semver::Version) -> bool {
semver::VersionReq::parse(engine).is_ok_and(|req| req.matches(api))
let Ok(req) = semver::VersionReq::parse(engine) else { return false };
let host = semver::Version::parse(ENGINE_VERSION).expect("valid engine version");
req.matches(&host)
}
/// Segments of `[a-z0-9][a-z0-9_-]*` joined by `.` (an optional publisher
@@ -581,28 +549,6 @@ mod tests {
assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nengines.openidea = \"^1.0\"").contains("version"));
}
const BASE: &str = "id = \"ok\"\nname = \"N\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.2\"\n";
#[test]
fn parses_icons() {
let m = Manifest::parse(&format!("{BASE}icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n")).unwrap();
assert_eq!(m.icon.as_deref(), Some(Path::new("icon.svg")));
assert_eq!(m.icon_dark.as_deref(), Some(Path::new("icon_dark.svg")));
assert_eq!(Manifest::parse(BASE).unwrap().icon, None);
}
#[test]
fn rejects_invalid_icons() {
assert!(err(&format!("{BASE}icon-dark = \"d.svg\"\n")).contains("`icon-dark` needs `icon`"));
assert!(err(&format!("{BASE}icon = \"../x.svg\"\n")).contains("icon"));
assert!(err(&format!("{BASE}icon = \"/abs.svg\"\n")).contains("icon"));
assert!(err(&format!("{BASE}icon = \"i.svg\"\nicon-dark = \"../d.svg\"\n")).contains("icon-dark"));
for engine in ["^1.0", ">=1.1, <2"] {
let old = BASE.replace("^1.2", engine);
assert!(err(&format!("{old}icon = \"i.svg\"\n")).contains("new in plugin API 1.2"), "{engine}");
}
}
#[test]
fn ids() {
assert!(validate_plugin_id("openidea.material-icons").is_ok());
-13
Переглянути файл
@@ -314,14 +314,6 @@ pub struct Endorsement {
pub signature: String,
}
/// A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginIcon {
pub light: String,
pub dark: Option<String>,
}
/// A published plugin version.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
@@ -348,10 +340,6 @@ pub struct IndexEntry {
/// Marketplace categories (`CATEGORIES`); an IDE ignores those it doesn't know.
#[serde(default)]
pub categories: Vec<String>,
/// The manifest's icon, sanitised by whoever wrote the index and again by
/// the IDE before showing it.
#[serde(default)]
pub icon: Option<PluginIcon>,
}
impl IndexEntry {
@@ -684,7 +672,6 @@ mod tests {
capabilities: Vec::new(),
engine: "^1.0".into(),
categories: Vec::new(),
icon: None,
}
}
+3 -41
Переглянути файл
@@ -22,7 +22,7 @@
mod templates;
use ide_extension::{Manifest, validate_plugin_id};
use ide_host::plugins::{PluginHost, plugin_icon, read_market_url, resolve_market_href};
use ide_host::plugins::{PluginHost, read_market_url, resolve_market_href};
use ide_plugin::{Limits, PluginEngine};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
@@ -650,7 +650,6 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
categories: m.categories(),
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
})
})();
let entry = entry.map_err(|e| format!("{}: {e}", path.display()))?;
@@ -813,24 +812,20 @@ mod tests {
/// A theme package `id` signed by `publisher` with `key`, packed into `out`.
fn signed_theme(tmp: &Path, id: &str, publisher: &str, key: &str, out: &Path) {
signed_theme_version(tmp, id, "0.1.0", "^1.2", publisher, key, out);
signed_theme_version(tmp, id, "0.1.0", "^1.0", publisher, key, out);
}
fn signed_theme_version(tmp: &Path, id: &str, version: &str, engine: &str, publisher: &str, key: &str, out: &Path) {
let src = tmp.join("src").join(format!("{id}-{version}"));
let vars = templates::Vars { id, name: id, sdk: None };
// A manifest icon needs API 1.2.
let icon = if engine == "^1.2" { "\nicon = \"icon.svg\"" } else { "" };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let content = content
.replace("version = \"0.1.0\"", &format!("version = \"{version}\""))
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\"{icon}"));
.replace("engines.openidea = \"^1.0\"", &format!("engines.openidea = \"{engine}\""));
std::fs::write(path, content).unwrap();
}
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
.unwrap();
std::fs::create_dir_all(out).unwrap();
let args = [src.to_str().unwrap(), "--key", key, "--publisher", publisher, "--out"]
.into_iter()
@@ -926,11 +921,6 @@ mod tests {
let listed: Vec<_> = index.plugins.iter().map(|e| (e.id.as_str(), e.publisher.as_str())).collect();
assert_eq!(listed, [("alice.dawn", "alice"), ("openidea.night", "openidea")]);
assert_eq!(index.plugins[1].categories, ["themes"], "implied by the theme");
assert!(
index.plugins[1].icon.as_ref().is_some_and(|i| i.light.contains("<rect")),
"{:?}",
index.plugins[1].icon
);
assert_eq!(index.plugins[1].download, "openidea.night-0.1.0.oiplugin");
assert!(Path::new(&index.plugins[0].download).is_absolute(), "{}", index.plugins[0].download);
@@ -940,34 +930,6 @@ mod tests {
assert!(err.contains("unknown publisher"), "{err}");
}
#[test]
fn the_index_carries_plugin_icons() {
let tmp = tempfile::tempdir().unwrap();
let t = tmp.path();
let key = t.join("acme.key");
std::fs::write(&key, PublisherKey::from_seed([6; 32]).seed_base64()).unwrap();
let src = t.join("src");
let vars = templates::Vars { id: "acme.iconic", name: "Iconic", sdk: None };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, content).unwrap();
}
let manifest = std::fs::read_to_string(src.join("plugin.toml")).unwrap();
let manifest = manifest.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.2\"");
std::fs::write(src.join("plugin.toml"), format!("icon = \"icon.svg\"\n{manifest}")).unwrap();
std::fs::write(src.join("icon.svg"), r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#)
.unwrap();
let out = t.join("out");
std::fs::create_dir_all(&out).unwrap();
let (src, key) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
let package = out.join("acme.iconic-0.1.0.oiplugin").to_string_lossy().into_owned();
cmd_pack(&strings(&[&src, "--key", &key, "--publisher", "acme", "--out", &package])).unwrap();
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key])).unwrap();
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
}
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
#[test]
fn the_command_template_builds_against_the_sdk() {
+2 -1
Переглянути файл
@@ -170,7 +170,8 @@ impl KotlinBridge {
let settings = self.settings.effective();
let has_sources = tokio::task::spawn_blocking(move || {
let model = crate::ops::build::load(&root, &cache, &settings);
let enabled = kotlin_bridge::has_kotlin(&root, &model);
let enabled =
model.maven.as_ref().is_some_and(|m| !m.projects.is_empty()) && kotlin_bridge::has_kotlin(&root);
(model, enabled)
})
.await;
-8
Переглянути файл
@@ -349,14 +349,6 @@ impl Host {
}
}
/// Called on desktop exit: kills the runs and terminal shells still alive. Closing a
/// window stops what it started, but a quit from the Dock, the app menu or a logout
/// exits without closing the windows, and the process trees would outlive the app.
pub fn stop_processes_on_exit(&self) {
self.processes.kill_all();
self.terminals.kill_all();
}
/// Called before desktop exit, which may bypass document destructors.
pub fn clear_workspace_edit_history_on_exit(&self) {
for project in self.projects() {
+8 -92
Переглянути файл
@@ -47,8 +47,8 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
}
}
for g in &mut model.gradle {
g.env = ide_sdk::apply::gradle_env(root, settings, java_env(jdk.as_ref(), g.java_version));
g.command = ide_sdk::apply::gradle_command(root, &root.join(&g.dir), settings).to_string_lossy().into_owned();
g.env = ide_sdk::apply::gradle_build_env(root, &root.join(&g.dir), &g.command, settings, g.java_version);
}
// A failed sync of a project no installed JDK can build says so first (with a Download JDK action).
let missing = |release: Option<u32>| match jdk {
@@ -76,42 +76,6 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// Build and Run use the same selected toolchain and module-local runtime discovery.
fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings) -> compile::BuildPlan {
let kind = match plan.system {
compile::BuildSystem::Cargo => "cargo",
compile::BuildSystem::Go => "go",
compile::BuildSystem::TypeScript => "npm",
_ => return plan,
};
for step in &mut plan.steps {
let mut config = ide_run::RunConfig {
id: String::new(),
name: String::new(),
kind: kind.into(),
command: step.program.clone(),
args: step.args.clone(),
cwd: Some(step.cwd.clone().into()),
env: step.env.clone(),
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.module = Some(ide_core::ipc_path::to_ipc(&step.cwd));
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, settings);
if kind == "go" {
config.extras.params.insert("useTags".into(), "true".into());
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
step.program = config.command;
step.args = config.args;
step.env = config.env;
}
plan
}
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
@@ -503,11 +467,7 @@ pub async fn build_run(
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = cache.join(crate::project::project_key(member));
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = prepare_plan(
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
member,
&settings,
);
let plan = compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?;
match &mut combined {
Some(combined) => combined.steps.extend(plan.steps),
None => combined = Some(plan),
@@ -517,17 +477,13 @@ pub async fn build_run(
plan.title = workspace.name;
plan
} else {
prepare_plan(
compile::plan(
&root,
&with_profiles(load(&root, &cache, &settings), &cache),
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
)?,
compile::plan(
&root,
&settings,
)
&with_profiles(load(&root, &cache, &settings), &cache),
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
)?
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
@@ -603,46 +559,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
mod gradle_settings_tests {
use super::*;
#[test]
fn builds_apply_the_same_explicit_toolchains_as_runs() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let tool = |name: &str| format!("{name}{}", std::env::consts::EXE_SUFFIX);
for name in ["cargo", "go"] {
let path = root.join("sdk").join("bin").join(tool(name));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let mut settings = Settings::default();
settings.languages.rust.toolchain = "sdk".into();
settings.languages.go.goroot = "sdk".into();
settings.languages.go.build_tags.custom = "integration".into();
settings.languages.node.package_manager = "yarn".into();
for (marker, source, program) in [
(
"Cargo.toml",
"[package]\nname='demo'\nversion='0.1.0'",
root.join("sdk").join("bin").join(tool("cargo")).to_string_lossy().into_owned(),
),
("go.mod", "module demo", root.join("sdk").join("bin").join(tool("go")).to_string_lossy().into_owned()),
("package.json", r#"{"scripts":{"build":"echo built"},"packageManager":"pnpm@10"}"#, "yarn".into()),
] {
let dir = root.join(marker.replace('.', "-"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(marker), source).unwrap();
let plan = prepare_plan(
compile::plan(&dir, &Default::default(), BuildKind::Artifacts, None, None).unwrap(),
root,
&settings,
);
assert_eq!(plan.steps[0].program, program);
assert_eq!(plan.steps[0].cwd, dir);
if marker == "go.mod" {
assert!(plan.steps[0].args.contains(&"-tags=integration".into()));
}
}
}
#[test]
fn linking_retains_the_implicit_build_and_unlinking_all_stays_empty() {
let tmp = tempfile::tempdir().unwrap();
+2 -23
Переглянути файл
@@ -307,11 +307,7 @@ pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Java, `project_wide`: without `libraries`, the dependencies and the JDK
/// are not searched; with it, those found in the sources arrive on `on_partial` before
/// the slower search for the rest, and the result has them all. Cancel with
/// `cancel_request(request)`.
#[allow(clippy::too_many_arguments)]
/// leave it off. Cancel with `cancel_request(request)`.
pub async fn lsp_references(
host: &Host,
window: &str,
@@ -320,24 +316,10 @@ pub async fn lsp_references(
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
on_partial: super::Channel<References>,
) -> IdeResult<References> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = lsp
.references_streaming(
doc,
pos,
include_declaration,
project_wide,
libraries,
cancel,
Some(&|refs| {
let _ = on_partial.send(refs);
}),
)
.await;
let result = lsp.references(doc, pos, include_declaration, project_wide, cancel).await;
host.end_request(request);
result
}
@@ -807,7 +789,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
);
d.add("lsp_virtual_document", |c| async move { lsp_virtual_document(&c.host, &c.window, c.arg("uri")?).await });
d.add("lsp_references", |c| async move {
let on_partial = c.sender("onPartial")?;
lsp_references(
&c.host,
&c.window,
@@ -816,8 +797,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
c.arg("pos")?,
c.arg("includeDeclaration")?,
c.arg("projectWide")?,
c.arg("libraries")?,
on_partial,
)
.await
});
+10 -95
Переглянути файл
@@ -28,12 +28,9 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
task.target = format!("workspace:{}:{}", key, task.target);
}
}
for id in &mut config.extras.compound {
*id = format!("workspace:{key}:{id}");
}
config.id = format!("workspace:{}:{}", key, config.id);
config.name = format!("{name} / {}", config.name);
ide_run::scope::rebase(&mut config, &member, None);
config.cwd = Some(config.cwd.map(|p| member.join(&*p)).unwrap_or_else(|| member.clone()).into());
config.detected = true;
if !user.iter().any(|u| u.id == config.id) && !root_suppressed.contains(&config.id) {
all.push(config);
@@ -54,18 +51,10 @@ fn detected_and_saved(
suppressed: &[String],
) -> Vec<RunConfig> {
let excluded_poms = crate::project::unlinked_maven_poms(root, settings);
let gradle = settings
.languages
.java
.gradle
.linked_projects
.as_ref()
.map(|_| ide_build::gradle::load_linked(root, &settings.languages.java.gradle));
let mut all: Vec<RunConfig> =
ide_run::detect_with_profiles(root, &excluded_poms, settings.cmake.profiles.as_deref())
.into_iter()
.filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id))
.filter(|d| linked_config(root, gradle.as_deref(), &excluded_poms, d))
.collect();
all.extend(saved.iter().cloned());
for config in all.iter_mut().filter(|c| !matches!(c.kind.as_str(), "gradle" | "maven")) {
@@ -74,41 +63,6 @@ fn detected_and_saved(
all
}
fn linked_config(
root: &std::path::Path,
gradle: Option<&[ide_build::GradleModel]>,
excluded_poms: &[std::path::PathBuf],
config: &RunConfig,
) -> bool {
let module = config
.extras
.module
.as_deref()
.map(std::path::Path::new)
.or(config.cwd.as_deref())
.unwrap_or(std::path::Path::new(""));
let owner = ide_core::project_roots::resolve(root, module);
if matches!(config.kind.as_str(), "maven" | "application" | "spring-boot")
&& excluded_poms.iter().any(|pom| ide_core::project_roots::resolve(root, pom).parent() == Some(owner.as_path()))
{
return false;
}
if gradle.is_some()
&& (config.kind == "gradle"
|| (matches!(config.kind.as_str(), "application" | "spring-boot")
&& ["build.gradle", "build.gradle.kts"].iter().any(|name| owner.join(name).is_file())))
{
return gradle.unwrap_or_default().iter().any(|build| {
if config.kind == "gradle" {
root.join(&build.dir) == owner
} else {
build.projects.iter().any(|p| root.join(&p.dir) == owner)
}
});
}
true
}
/// Saves the user configurations. They come from [`configs`], toolchains applied, so what
/// settings derived is dropped again: only the user's own choices reach `run.toml`.
pub fn save_configs(
@@ -133,22 +87,11 @@ pub fn save_configs(
fn settings_for(
host: &Host,
project: &crate::project::Project,
config: &mut RunConfig,
config: &RunConfig,
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings)> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
if workspace.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
}
let member = workspace.and_then(|workspace| {
let owner = ide_run::scope::owner(&project.root, config);
workspace
.projects
.into_iter()
.filter(|root| owner.starts_with(root))
.max_by_key(|root| root.components().count())
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|workspace| {
let cwd = config.cwd.as_deref()?;
workspace.projects.into_iter().filter(|root| cwd.starts_with(root)).max_by_key(|root| root.components().count())
});
Ok(match member {
Some(root) => {
@@ -166,11 +109,11 @@ pub fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> Id
let project = host.project(window)?;
configs
.into_iter()
.map(|mut c| {
.map(|c| {
if c.kind == "gradle" {
return Ok(c);
}
let (root, settings) = settings_for(host, &project, &mut c)?;
let (root, settings) = settings_for(host, &project, &c)?;
Ok(ide_sdk::apply::without_derived(&c, &root, &settings))
})
.collect()
@@ -184,7 +127,7 @@ pub fn apply_settings(host: &Host, window: &str, configs: Vec<RunConfig>) -> Ide
.into_iter()
.map(|mut c| {
if c.kind != "gradle" {
let (root, settings) = settings_for(host, &project, &mut c)?;
let (root, settings) = settings_for(host, &project, &c)?;
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut c), &root, &settings);
}
Ok(c)
@@ -231,13 +174,13 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
.run(&settings, &project.root, &config, project.sink.clone(), Box::new(move |c| out(c)))
.await;
}
let mut config = config;
let (root, settings) = settings_for(host, &project, &mut config)?;
let (root, settings) = settings_for(host, &project, &config)?;
let root = &root;
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
// Maven re-applies too: a config listed before a settings change (daemon toggle,
// Maven home) keeps the launcher that was current then; re-resolving at launch is
// what makes the setting take effect without reopening the project.
let mut config = config;
if config.kind == "maven" {
ide_sdk::apply::prepare_maven_run(&mut config, root, &settings);
} else if matches!(config.kind.as_str(), "gradle" | "tomcat") {
@@ -352,31 +295,3 @@ pub fn list(host: &Host) -> Vec<RunInfo> {
mod commands;
mod container;
pub use commands::*;
#[cfg(test)]
mod ownership_tests {
use super::*;
#[test]
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
for name in ["maven", "gradle"] {
let dir = root.join(name);
std::fs::create_dir_all(dir.join("src/main/java")).unwrap();
std::fs::write(
dir.join("src/main/java/App.java"),
"@SpringBootApplication class App { public static void main(String[] a) {} }",
)
.unwrap();
}
std::fs::write(root.join("maven/pom.xml"), "<project><build><plugins><plugin><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>").unwrap();
std::fs::write(root.join("gradle/build.gradle.kts"), "plugins { id(\"org.springframework.boot\") }").unwrap();
let defaults = detected_and_saved(root, &Default::default(), &[], &[]);
assert!(defaults.iter().any(|c| c.kind == "spring-boot"));
let mut settings = ide_core::settings::Settings::default();
settings.languages.java.maven.unlinked_projects = vec!["maven/pom.xml".into()];
settings.languages.java.gradle.linked_projects = Some(vec![]);
let configs = detected_and_saved(root, &settings, &[], &[]);
assert!(configs.is_empty(), "{configs:?}");
}
}
+3 -14
Переглянути файл
@@ -46,21 +46,10 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
}
/// The interpreter the project uses: the configured one, else its virtualenv.
pub fn sdk_python_effective(host: &Host, window: &str, near: Option<PathBuf>) -> IdeResult<Option<ide_core::IpcPath>> {
pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
host.require_trust(window)?;
let project = host.project(window)?;
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|w| {
let near = near.as_deref()?;
w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count())
});
let (root, settings) = match member {
Some(root) => {
let settings = ide_workspace::SettingsStore::load(&host.config_dir, Some(&root)).effective();
(root, settings)
}
None => (project.root.clone(), project.settings.effective()),
};
Ok(ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).map(Into::into))
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
@@ -243,7 +232,7 @@ pub async fn sdk_python_pip(
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window, c.arg("near")?) });
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
d.add(
"sdk_php_language_level",
+9 -197
Переглянути файл
@@ -1,14 +1,14 @@
//! [`HostApi`] for one plugin's code: what its imports reach in the IDE.
//! Capabilities were checked by the runtime before any of this runs.
use super::{PluginContextKey, PluginEvent, PluginEventSink};
use super::{PluginEvent, PluginEventSink};
use ide_core::ipc_path::to_ipc;
use ide_core::{CancellationToken, TextEdit};
use ide_extension::Package;
use ide_language::ProgramPin;
use ide_plugin::{
EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel, ProcessOutput, Prompt,
RepositoryStatus, StatusItem,
EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel, ProcessOutput, RepositoryStatus,
StatusItem,
};
use parking_lot::{Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -22,10 +22,6 @@ const MAX_STORAGE: usize = 1 << 20;
const MAX_KEY: usize = 256;
/// Most status bar items per plugin.
const MAX_STATUS_ITEMS: usize = 8;
const MAX_CONTEXT_KEYS: usize = 100;
/// (window or `None` for every window, plugin, key).
type ContextKey = (Option<String>, String, String);
/// What plugins see of the open projects; provided by the app
/// ([`super::PluginHost::set_workspace`]), over [`crate::Host`] on the desktop.
@@ -150,12 +146,6 @@ struct TaskEntry {
cancelled: bool,
}
/// A question a plugin's call waits on.
struct PromptEntry {
plugin: String,
answer: std::sync::mpsc::SyncSender<Option<Vec<String>>>,
}
/// State shared by the host and every plugin's [`PluginApi`].
pub(super) struct Shared {
pub sink: Arc<dyn PluginEventSink>,
@@ -164,15 +154,8 @@ pub(super) struct Shared {
pub data_dir: PathBuf,
tasks: Mutex<HashMap<u64, TaskEntry>>,
next_task: AtomicU64,
prompts: Mutex<HashMap<u64, PromptEntry>>,
/// Plugins being stopped: their calls may not open new prompts (taken before `prompts`).
prompts_blocked: Mutex<BTreeSet<String>>,
next_prompt: AtomicU64,
/// (plugin, item id) → item, for windows opened later.
status: Mutex<BTreeMap<(String, String), StatusItem>>,
/// (scope, plugin, key) → JSON value.
contexts: Mutex<BTreeMap<ContextKey, String>>,
closed_clients: Mutex<BTreeSet<String>>,
/// plugin → kinds subscribed at run time (kept across idle reclaim).
pub subscriptions: Mutex<HashMap<String, BTreeSet<EventKind>>>,
/// plugin → files it shows problems for, withdrawn when it stops.
@@ -200,12 +183,7 @@ impl Shared {
data_dir,
tasks: Mutex::default(),
next_task: AtomicU64::new(1),
prompts: Mutex::default(),
prompts_blocked: Mutex::default(),
next_prompt: AtomicU64::new(1),
status: Mutex::default(),
contexts: Mutex::default(),
closed_clients: Mutex::default(),
subscriptions: Mutex::default(),
diagnostics: Mutex::default(),
})
@@ -248,34 +226,6 @@ impl Shared {
self.status.lock().iter().map(|((p, id), item)| (p.clone(), id.clone(), item.clone())).collect()
}
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
let contexts = self.contexts.lock();
let mut keys: BTreeMap<(&str, &str), &str> = BTreeMap::new();
for ((_, plugin, key), value) in contexts.iter().filter(|((s, ..), _)| s.is_none()) {
keys.insert((plugin, key), value);
}
if let Some(client) = client {
for ((_, plugin, key), value) in contexts.iter().filter(|((s, ..), _)| s.as_deref() == Some(client)) {
keys.insert((plugin, key), value);
}
}
keys.into_iter()
.map(|((p, k), v)| PluginContextKey { plugin_id: p.to_owned(), key: k.to_owned(), value: v.to_owned() })
.collect()
}
/// Drops the context keys scoped to window `client` (it closed), without events, and
/// refuses further writes for it (late commands) until [`Self::reopen_client`].
pub fn forget_client(&self, client: &str) {
self.closed_clients.lock().insert(client.to_owned());
self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client));
}
/// A window labelled `client` is being created (labels are reused after a close).
pub fn reopen_client(&self, client: &str) {
self.closed_clients.lock().remove(client);
}
/// Withdraws a plugin's run-time state (it stopped or failed). Its
/// subscriptions go only with `subscriptions`, as they survive restarts.
pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) {
@@ -290,19 +240,6 @@ impl Shared {
for id in removed {
self.sink.emit(None, PluginEvent::StatusItemChanged { plugin_id: plugin.to_owned(), id, item: None });
}
self.withdraw_prompts(plugin);
let removed: Vec<(Option<String>, String)> = {
let mut contexts = self.contexts.lock();
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
for key in &keys {
contexts.remove(key);
}
keys.into_iter().map(|(scope, _, key)| (scope, key)).collect()
};
for (scope, key) in removed {
self.sink
.emit(scope.as_deref(), PluginEvent::ContextChanged { plugin_id: plugin.to_owned(), key, value: None });
}
let tasks: Vec<u64> = self.tasks.lock().iter().filter(|(_, t)| t.plugin == plugin).map(|(id, _)| *id).collect();
for id in tasks {
self.end_task(id);
@@ -328,40 +265,6 @@ impl Shared {
true
}
/// Closes the prompts `plugin` waits on: the calls waiting for the user
/// wake up cancelled (dropping the senders).
fn withdraw_prompts(&self, plugin: &str) {
let ids: Vec<u64> = {
let mut prompts = self.prompts.lock();
let ids: Vec<u64> = prompts.iter().filter(|(_, p)| p.plugin == plugin).map(|(id, _)| *id).collect();
for id in &ids {
prompts.remove(id);
}
ids
};
for id in ids {
self.sink.emit(None, PluginEvent::PromptClosed { prompt_id: id.to_string() });
}
}
/// `plugin` is about to be stopped: withdraws its prompts, and its queued
/// calls can't open new ones (they'd keep the stop waiting) until
/// [`allow_prompts`](Self::allow_prompts).
pub fn block_prompts(&self, plugin: &str) {
self.prompts_blocked.lock().insert(plugin.to_owned());
self.withdraw_prompts(plugin);
}
pub fn allow_prompts(&self, plugin: &str) {
self.prompts_blocked.lock().remove(plugin);
}
/// The user answered (`Some`) or dismissed (`None`) a prompt.
pub fn answer_prompt(&self, id: u64, answer: Option<Vec<String>>) -> bool {
let Some(prompt) = self.prompts.lock().remove(&id) else { return false };
prompt.answer.send(answer).is_ok()
}
fn end_task(&self, id: u64) {
if let Some(t) = self.tasks.lock().remove(&id) {
self.sink.emit(None, PluginEvent::TaskEnded { plugin_id: t.plugin, task_id: id.to_string() });
@@ -440,52 +343,6 @@ impl HostApi for PluginApi {
Ok(())
}
fn ask(
&self,
client: Option<&str>,
prompt: Prompt,
cancel: &CancellationToken,
) -> Result<Option<Vec<String>>, HostError> {
let client = from_window(client, "ask the user")?;
let id = self.shared.next_prompt.fetch_add(1, Ordering::Relaxed);
let (answer, answers) = std::sync::mpsc::sync_channel(1);
{
let blocked = self.shared.prompts_blocked.lock();
if blocked.contains(self.id()) {
return Err(HostError::Cancelled);
}
self.shared.prompts.lock().insert(id, PromptEntry { plugin: self.id().to_owned(), answer });
}
let prompt_id = id.to_string();
self.shared.sink.emit(
Some(client),
PluginEvent::PromptRequested { plugin_id: self.id().to_owned(), prompt_id: prompt_id.clone(), prompt },
);
loop {
match answers.recv_timeout(Duration::from_millis(100)) {
Ok(answer) => return Ok(answer),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) if !cancel.is_cancelled() => {}
Err(_) => {
self.shared.prompts.lock().remove(&id);
self.shared.sink.emit(Some(client), PluginEvent::PromptClosed { prompt_id });
return Err(HostError::Cancelled);
}
}
}
}
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
let client = from_window(client, "reveal a view")?;
let declared = self.shared.ui.items(super::ui_points::VIEWS, Some(self.id())).iter().any(|i| i.key == view);
if !declared {
return Err(HostError::NotFound(format!("the plugin declares no view {view:?}")));
}
self.shared
.sink
.emit(Some(client), PluginEvent::RevealView { plugin_id: self.id().to_owned(), view: view.to_owned() });
Ok(())
}
fn status_item(&self, id: &str, item: Option<StatusItem>) {
let key = (self.id().to_owned(), id.to_owned());
{
@@ -514,37 +371,6 @@ impl HostApi for PluginApi {
.emit(None, PluginEvent::StatusItemChanged { plugin_id: self.id().to_owned(), id: id.to_owned(), item });
}
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
let map_key = (client.map(str::to_owned), self.id().to_owned(), key.to_owned());
{
let mut contexts = self.shared.contexts.lock();
if client.is_some_and(|c| self.shared.closed_clients.lock().contains(c)) {
return Ok(());
}
match &value {
Some(value) => {
if contexts.get(&map_key) == Some(value) {
return Ok(());
}
let count = contexts.keys().filter(|(_, p, _)| p == self.id()).count();
if !contexts.contains_key(&map_key) && count >= MAX_CONTEXT_KEYS {
return Err(HostError::Invalid(format!("more than {MAX_CONTEXT_KEYS} context keys")));
}
contexts.insert(map_key, value.clone());
}
None => {
if contexts.remove(&map_key).is_none() {
return Ok(());
}
}
}
}
self.shared
.sink
.emit(client, PluginEvent::ContextChanged { plugin_id: self.id().to_owned(), key: key.to_owned(), value });
Ok(())
}
fn projects(&self) -> Vec<PathBuf> {
self.shared.workspace().map(|w| w.projects()).unwrap_or_default()
}
@@ -638,9 +464,8 @@ impl HostApi for PluginApi {
.build()
.map_err(|e| HostError::Invalid(format!("{glob:?}: {e}")))?
.compile_matcher();
// Project scope visits hidden files and folders (`.github`, `.config`):
// only `.git` internals stay out, as in the walk below.
let visible = |rel: &Path| !rel.iter().any(|c| c == ".git");
// Hidden files and folders are left out, as in the walk below.
let visible = |rel: &Path| !rel.iter().any(|c| c.to_str().is_some_and(|c| c.starts_with('.')));
// The project index already lists the files: walking a large tree on every call can take
// longer than an editor provider's deadline (the plugin is then stopped as crashed).
if let Some(files) = self
@@ -653,13 +478,7 @@ impl HostApi for PluginApi {
return Ok(out);
}
let mut out = Vec::new();
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
for (n, entry) in ignore::WalkBuilder::new(root).hidden(true).build().flatten().enumerate() {
if n >= MAX_WALK || out.len() >= limit {
break;
}
@@ -1064,27 +883,20 @@ mod tests {
let api = api(&root, Arc::default());
*api.shared.workspace.write() = Some(Arc::new(Indexed(
root.clone(),
vec!["src/b/UserMapper.xml", "src/a/OrderMapper.xml", ".idea/workspace.xml", ".git/index.xml", "pom.xml"],
vec!["src/b/UserMapper.xml", "src/a/OrderMapper.xml", ".idea/workspace.xml", "pom.xml"],
)));
// Listed by the index, not walked: none of these exist on disk.
assert_eq!(
api.find_files(&root, "**/*Mapper.xml", 10).unwrap(),
[to_ipc(&root.join("src/a/OrderMapper.xml")), to_ipc(&root.join("src/b/UserMapper.xml"))]
);
// Hidden folders are visited like any project scope; `.git` internals are not.
assert_eq!(api.find_files(&root, "**/*.xml", 10).unwrap().len(), 4);
assert_eq!(api.find_files(&root, ".idea/*.xml", 10).unwrap(), [to_ipc(&root.join(".idea/workspace.xml"))]);
assert_eq!(api.find_files(&root, "**/*.xml", 10).unwrap().len(), 3, "hidden folders are left out");
assert_eq!(api.find_files(&root, "**/*.xml", 1).unwrap().len(), 1);
// Another root: no index covers it, so the disk is walked.
let other = root.join("other");
std::fs::create_dir_all(other.join(".config/tool")).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("a.xml"), "").unwrap();
std::fs::write(other.join(".config/tool/index.xml"), "").unwrap();
assert_eq!(api.find_files(&other, "*.xml", 10).unwrap(), [to_ipc(&other.join("a.xml"))]);
assert_eq!(
api.find_files(&other, ".config/tool/*.xml", 10).unwrap(),
[to_ipc(&other.join(".config/tool/index.xml"))]
);
}
#[test]
+6 -17
Переглянути файл
@@ -26,7 +26,6 @@
use super::icon_extensions::{Choice, DARK_SUFFIX, Extensions, Group, IconDefinition, Pattern, check_icon_id};
use super::icon_settings::{self, SettingsSection};
use ide_extension::package::PluginIcon;
use ide_extension::{Package, UiDecl, check_relative, decode, validate_item_id};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
@@ -34,10 +33,8 @@ use std::path::PathBuf;
pub const POINT_ID: &str = "iconThemes";
const MAX_ICONS: usize = 5000;
pub(super) const MAX_SVG: usize = 64 << 10;
const MAX_SVG: usize = 64 << 10;
const MAX_MAPPINGS: usize = 20_000;
/// A plugin's own icon is inline in every plugin listing and index entry.
pub const MAX_PLUGIN_ICON: usize = 16 << 10;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -93,24 +90,16 @@ pub fn svg_prefix(theme: &str) -> String {
format!("iconTheme/{theme}/svg/")
}
/// An SVG icon of the package, size-checked (`max` bytes) and sanitised.
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path, max: usize) -> Result<String, String> {
/// An SVG icon of the package, size-checked and sanitised.
pub(super) fn read_icon(pkg: &Package, path: &std::path::Path) -> Result<String, String> {
check_relative(path, "icon")?;
let svg = pkg.read_text(path)?;
if svg.len() > max {
return Err(format!("{}: larger than {} KiB", path.display(), max >> 10));
if svg.len() > MAX_SVG {
return Err(format!("{}: larger than {} KiB", path.display(), MAX_SVG >> 10));
}
sanitize_svg(&svg).map_err(|e| format!("{}: {e}", path.display()))
}
/// The manifest's `icon` / `icon-dark`, read and sanitised.
pub fn plugin_icon(pkg: &Package) -> Result<Option<PluginIcon>, String> {
let read = |path: &std::path::Path| read_icon(pkg, path, MAX_PLUGIN_ICON);
let Some(light) = &pkg.manifest.icon else { return Ok(None) };
let dark = pkg.manifest.icon_dark.as_deref().map(read).transpose()?;
Ok(Some(PluginIcon { light: read(light)?, dark }))
}
pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: Decl = decode(POINT_ID, decl)?;
validate_item_id(&d.id, "icon theme id")?;
@@ -177,7 +166,7 @@ pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Str
for (icon, def) in &theme.icon_definitions {
let dark = def.dark().map(|path| (path, DARK_SUFFIX));
for (path, suffix) in std::iter::once((def.light(), "")).chain(dark) {
let clean = read_icon(pkg, path, MAX_SVG)?;
let clean = read_icon(pkg, path)?;
assets.push((format!("{}{icon}{suffix}", svg_prefix(&d.id)), clean));
files.push(path.clone());
}
+1 -6
Переглянути файл
@@ -121,12 +121,7 @@ pub async fn plugin_navigation_index(
plugins.index_navigation(
&project.root,
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
Invocation {
client: Some(client.clone()),
workspace_root: Some(project.root.clone()),
editor: None,
selected_paths: Vec::new(),
},
Invocation { client: Some(client.clone()), workspace_root: Some(project.root.clone()), editor: None },
)?;
// A document edit while WASM was executing must not publish stale ranges.
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
+3 -14
Переглянути файл
@@ -6,10 +6,9 @@
//! Release builds pin the official publisher to the keys they were built
//! with, so no index can sign `openidea.*` plugins with another key.
use super::icons::{MAX_PLUGIN_ICON, sanitize_svg};
use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, PluginUpdate, install};
use ide_core::{IdeError, IdeResult};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, SIGNATURE_FILE};
use ide_extension::{MANIFEST_FILE, Manifest};
use semver::Version;
use serde::{Deserialize, Serialize};
@@ -68,14 +67,6 @@ fn pinned(mut index: Index, official_keys: &[String]) -> Index {
index
}
/// An index's icon as the UI may show it: sanitised again, as any index may
/// have written it; without a light variant that passes, none.
fn safe_icon(icon: PluginIcon) -> Option<PluginIcon> {
// Before sanitising too: an index may hold megabytes of it.
let clean = |svg: String| (svg.len() <= MAX_PLUGIN_ICON).then(|| sanitize_svg(&svg).ok()).flatten();
Some(PluginIcon { light: clean(icon.light)?, dark: icon.dark.and_then(clean) })
}
/// Reads `url`: `http(s)://…`, `file://…` or a local path.
pub fn read_url(url: &str, max: usize) -> Result<Vec<u8>, String> {
if url.starts_with("https://") || url.starts_with("http://") {
@@ -251,9 +242,7 @@ impl PluginHost {
.get(&entry.id)
.filter(|p| p.source == PluginSource::Installed)
.map(|p| p.manifest().version.clone());
let mut entry = entry.clone();
entry.icon = entry.icon.and_then(safe_icon);
MarketPlugin { entry, installed, compatible }
MarketPlugin { entry: entry.clone(), installed, compatible }
})
.collect()
}
@@ -361,7 +350,7 @@ impl PluginHost {
pub(super) fn package_files_in(&self, dir: &Path) -> IdeResult<Vec<PathBuf>> {
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
let pkg = ide_extension::Package::new(manifest, dir.to_path_buf());
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
Ok(set.files.into_iter().chain(pkg.manifest.wasm.clone()).collect())
}
+5 -57
Переглянути файл
@@ -37,9 +37,7 @@ pub mod views;
pub mod web;
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use icons::{
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
};
pub use icons::{map_asset as icon_theme_map_asset, sanitize_svg, svg_prefix as icon_theme_svg_prefix};
pub use market::{
INDEX_FILE as MARKET_INDEX_FILE, MarketPlugin, OFFICIAL_INDEX as OFFICIAL_MARKET_INDEX, OFFICIAL_PUBLISHER,
read_url as read_market_url, resolve as resolve_market_href,
@@ -186,8 +184,6 @@ const IDLE_BATCH: Duration = Duration::from_secs(2);
struct LoadedPlugin {
pkg: Package,
/// Read at load so disabled and failed plugins show it too.
icon: Option<ide_extension::package::PluginIcon>,
/// The manifest failed to parse: `pkg` is a placeholder.
invalid: bool,
source: PluginSource,
@@ -1260,34 +1256,11 @@ impl PluginHost {
self.shared.status_items()
}
/// Plugin context keys in effect for window `client`: global keys overlaid with its own.
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
self.shared.context_keys(client)
}
/// A window labelled `label` is about to exist again (labels are reused).
pub fn reopen_client(&self, label: &str) {
self.shared.reopen_client(label);
}
/// Window `label` closed: drops its context keys and queued events, and ignores
/// context writes of commands still running for it.
pub fn forget_client(&self, label: &str) {
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
self.shared.forget_client(label);
}
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
pub fn cancel_task(&self, task_id: &str) -> bool {
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
}
/// The user answered (`Some`) or dismissed (`None`) a prompt
/// (`PromptRequested`); false when it is no longer waiting.
pub fn answer_prompt(&self, prompt_id: &str, answer: Option<Vec<String>>) -> bool {
prompt_id.parse().is_ok_and(|id| self.shared.answer_prompt(id, answer))
}
/// Kinds of workbench events some running or activatable plugin wants;
/// the UI reports only these.
pub fn event_kinds(&self) -> BTreeSet<EventKind> {
@@ -1416,7 +1389,6 @@ impl PluginHost {
workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)),
client: client.clone(),
editor: None,
selected_paths: Vec::new(),
};
let kinds: BTreeSet<EventKind> = events.iter().map(WorkbenchEvent::kind).collect();
{
@@ -1556,7 +1528,7 @@ impl PluginHost {
continue;
}
let pkg = Package::new(m.clone(), dir.clone());
let problem = match self.prepare(&pkg) {
let problem = match self.registry.prepare(&pkg) {
Err(e) => Some(e),
Ok(_) => m
.wasm
@@ -1579,7 +1551,6 @@ impl PluginHost {
authors: m.authors,
homepage: m.homepage,
change_notes: m.change_notes,
icon: plugin_icon(&pkg).ok().flatten(),
path: dir.into(),
problem,
});
@@ -1591,9 +1562,6 @@ impl PluginHost {
/// Deactivates every plugin (also done on drop).
pub fn shutdown(&self) {
let actors: Vec<_> = self.plugins.read().values().filter_map(|p| p.runtime.lock().take()).collect();
for id in self.plugins.read().keys() {
self.shared.block_prompts(id);
}
for a in &actors {
a.stop(false);
}
@@ -1677,24 +1645,11 @@ impl PluginHost {
self.plugins.read().values().any(|p| p.dir() == dir)
}
/// Validates the manifest's icon and every declaration of `pkg`; the
/// icon files join the package files the declarations reference.
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
plugin_icon(pkg)?;
let mut set = self.registry.prepare(pkg)?;
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
if !set.files.contains(icon) {
set.files.push(icon.clone());
}
}
Ok(set)
}
/// Parses and validates a package directory; nothing takes effect.
fn validate_package(&self, src: &Path) -> IdeResult<(Package, ide_extension::PreparedSet)> {
let manifest = Manifest::load(src).map_err(IdeError::invalid)?;
let pkg = Package::new(manifest, src.to_path_buf());
let set = self.prepare(&pkg).map_err(IdeError::invalid)?;
let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?;
if let Some(wasm) = &pkg.manifest.wasm {
if !src.join(wasm).is_file() {
return Err(IdeError::invalid(format!(
@@ -1727,7 +1682,6 @@ impl PluginHost {
pkg = pkg.with_digest(digest.trim());
}
let plugin = Arc::new(LoadedPlugin {
icon: plugin_icon(&pkg).ok().flatten(),
pkg,
invalid,
source,
@@ -1777,7 +1731,7 @@ impl PluginHost {
let publisher = self.verified_publisher(plugin.dir());
plugin.meta.lock().publisher = publisher;
}
let set = match self.prepare(&plugin.pkg) {
let set = match self.registry.prepare(&plugin.pkg) {
Ok(set) => set,
Err(e) => return self.set_failed(plugin, e),
};
@@ -1907,7 +1861,6 @@ impl PluginHost {
Err(e) => return Err(IdeError::internal(format!("plugin {:?}: {e}", plugin.id()))),
};
*runtime = Some(actor.clone());
self.shared.allow_prompts(plugin.id());
let mut meta = plugin.meta.lock();
meta.status = PluginStatus::Active;
meta.has_syntax = has_syntax;
@@ -2005,8 +1958,6 @@ impl PluginHost {
fn stop(&self, plugin: &LoadedPlugin) {
self.clear_plugin_navigation(plugin.id());
// A call waiting on the user would keep the join below waiting.
self.shared.block_prompts(plugin.id());
if let Some(actor) = plugin.runtime.lock().take() {
actor.stop(true);
}
@@ -2135,7 +2086,7 @@ impl PluginHost {
return h.trim().to_owned();
}
// Installed before hashes were recorded: hash once and remember.
let files = self.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
let files = self.registry.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default();
let files: Vec<PathBuf> = files.into_iter().chain(plugin.manifest().wasm.clone()).collect();
let hash = ledger::package_hash(plugin.dir(), &files).unwrap_or_default();
let _ = std::fs::write(&file, &hash);
@@ -2202,7 +2153,6 @@ impl PluginHost {
authors: m.authors.clone(),
homepage: m.homepage.clone(),
change_notes: m.change_notes.clone(),
icon: p.icon.clone(),
source: p.source,
path: p.dir().to_path_buf().into(),
enabled: !self.state.lock().disabled.contains(&m.id),
@@ -2312,8 +2262,6 @@ fn placeholder_manifest(dir: &Path) -> Manifest {
license: None,
change_notes: None,
declared_categories: Vec::new(),
icon: None,
icon_dark: None,
engine: ide_extension::ENGINE_VERSION.into(),
legacy: false,
wasm: None,
+3 -19
Переглянути файл
@@ -13,8 +13,8 @@
//!
//! The commands a window needs at run time (`plugin_run_command`,
//! `plugin_post_events`, `plugin_event_kinds`, `plugin_status_items`,
//! `plugin_context_keys`, `plugin_cancel_task`, `plugin_answer_prompt`, `plugin_set_active_file`,
//! `plugin_line_markers`, `plugin_view_render`, `plugin_view_event`)
//! `plugin_cancel_task`, `plugin_set_active_file`, `plugin_line_markers`,
//! `plugin_view_render`, `plugin_view_event`)
//! carry the desktop commands' names and arguments, so a remote window's UI
//! routes them here unchanged. Plugin results come back as `plugin`
//! notifications ([`PluginEventMessage`]); secrets stay in the desktop's
@@ -107,7 +107,6 @@ pub fn forwarded(event: &PluginEvent) -> bool {
event,
PluginEvent::Notification { .. }
| PluginEvent::StatusItemChanged { .. }
| PluginEvent::ContextChanged { .. }
| PluginEvent::TaskStarted { .. }
| PluginEvent::TaskProgress { .. }
| PluginEvent::TaskEnded { .. }
@@ -118,9 +117,6 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::OpenLocation { .. }
| PluginEvent::CopyToClipboard { .. }
| PluginEvent::OpenUrl { .. }
| PluginEvent::PromptRequested { .. }
| PluginEvent::PromptClosed { .. }
| PluginEvent::RevealView { .. }
)
}
@@ -128,7 +124,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
impl PluginHost {
fn package_files(&self, plugin: &super::LoadedPlugin) -> IdeResult<Vec<PathBuf>> {
let set = self.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
let set = self.registry.prepare(&plugin.pkg).map_err(IdeError::invalid)?;
Ok(set.files.into_iter().chain(plugin.manifest().wasm.clone()).collect())
}
@@ -371,12 +367,10 @@ impl RemotePlugins {
let command_id: String = c.arg("commandId")?;
let arg: Option<String> = c.arg("arg")?;
let editor: Option<PluginEditor> = c.arg("editor")?;
let paths: Option<Vec<PathBuf>> = c.arg("paths")?;
let invocation = Invocation {
client: Some(c.window.clone()),
workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()),
editor: editor.map(PluginEditor::context),
selected_paths: paths.unwrap_or_default(),
};
blocking(move || host.run_command(&plugin_id, &command_id, arg.as_deref(), invocation)).await
}
@@ -406,21 +400,11 @@ impl RemotePlugins {
}
});
let h = host.clone();
d.add("plugin_context_keys", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.context_keys(Some(&c.window))) }
});
let h = host.clone();
d.add("plugin_cancel_task", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.cancel_task(&c.arg::<String>("taskId")?)) }
});
let h = host.clone();
d.add("plugin_answer_prompt", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.answer_prompt(&c.arg::<String>("promptId")?, c.arg("answer")?)) }
});
let h = host.clone();
d.add("plugin_set_active_file", move |c| {
let h = h.clone();
async move {
+1 -29
Переглянути файл
@@ -1,11 +1,8 @@
//! UI-facing plugin types and the event stream.
use super::theme::ThemeDef;
use ide_extension::package::PluginIcon;
use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution};
pub use ide_plugin::{
ActionPerformed, ActionSource, EventKind, NotificationLevel, PickItem, Prompt, StatusItem, WorkbenchEvent,
};
pub use ide_plugin::{ActionPerformed, ActionSource, EventKind, NotificationLevel, StatusItem, WorkbenchEvent};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -53,7 +50,6 @@ pub struct PluginInfo {
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
pub source: PluginSource,
/// Package directory.
pub path: ide_core::IpcPath,
@@ -117,7 +113,6 @@ pub struct CatalogPlugin {
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
pub icon: Option<PluginIcon>,
/// Package directory; install with `install_from_dir(path)`.
pub path: ide_core::IpcPath,
pub has_code: bool,
@@ -168,10 +163,6 @@ pub enum PluginEvent {
/// A plugin's status bar item was set (`item`) or removed.
#[serde(rename_all = "camelCase")]
StatusItemChanged { plugin_id: String, id: String, item: Option<StatusItem> },
/// A plugin's context key was set (`value`: JSON text) or removed, in the
/// emitted window (every window when the client is `None`).
#[serde(rename_all = "camelCase")]
ContextChanged { plugin_id: String, key: String, value: Option<String> },
/// A plugin began a task: show it with the background tasks.
#[serde(rename_all = "camelCase")]
TaskStarted { plugin_id: String, task_id: String, title: String, cancellable: bool },
@@ -214,16 +205,6 @@ pub enum PluginEvent {
/// Open `url` (`http(s)://`) in the system browser.
#[serde(rename_all = "camelCase")]
OpenUrl { plugin_id: String, url: String },
/// A command waits for the user's answer: show `prompt`, then report it with
/// `plugin_answer_prompt(prompt_id, …)`.
#[serde(rename_all = "camelCase")]
PromptRequested { plugin_id: String, prompt_id: String, prompt: Prompt },
/// The call that asked gave up (cancelled, or its plugin stopped): close the prompt.
#[serde(rename_all = "camelCase")]
PromptClosed { prompt_id: String },
/// Bring the tool window of the plugin's view `view` to the front.
#[serde(rename_all = "camelCase")]
RevealView { plugin_id: String, view: String },
}
/// Delivers events to the UI. `client` is the window that invoked the plugin
@@ -270,15 +251,6 @@ pub struct PluginStatusItem {
pub item: StatusItem,
}
/// A plugin's context key for `when` clauses (`value` is JSON text).
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginContextKey {
pub plugin_id: String,
pub key: String,
pub value: String,
}
/// A gutter marker from a plugin's `line-markers` provider.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+5 -30
Переглянути файл
@@ -5,10 +5,9 @@
//!
//! ```toml
//! [[contributes.menus]]
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context
//! menu = "editor.context" # projectView.context, editorTab.context, tools
//! command = "check"
//! when = "editorLang == java"
//! # view = "<view id>" # required for (only allowed on) viewItem.context
//!
//! [[contributes.keymaps]]
//! command = "check"
@@ -64,8 +63,7 @@ pub const CUSTOM_EDITORS: &str = "customEditors";
pub const FILE_ICONS: &str = "fileIcons";
pub const FILE_TEMPLATES: &str = "fileTemplates";
const VIEW_ITEM_MENU: &str = "viewItem.context";
const MENU_IDS: [&str; 5] = ["editor.context", "projectView.context", "editorTab.context", "tools", VIEW_ITEM_MENU];
const MENU_IDS: [&str; 4] = ["editor.context", "projectView.context", "editorTab.context", "tools"];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
const MAX_PATTERNS: usize = 16;
@@ -79,10 +77,6 @@ fn commands(pkg: &Package) -> BTreeSet<String> {
.collect()
}
fn declared_view(pkg: &Package, id: &str) -> Option<toml::Value> {
pkg.manifest.declarations(VIEWS).into_iter().find(|d| d.get("id").and_then(|v| v.as_str()) == Some(id))
}
fn declared_command(pkg: &Package, point: &str, command: &str) -> Result<(), String> {
if commands(pkg).contains(command) {
Ok(())
@@ -109,8 +103,6 @@ struct MenuDecl {
command: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
view: Option<String>,
}
pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
@@ -122,24 +114,7 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if let Some(w) = &d.when {
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
}
let key = match (d.menu == VIEW_ITEM_MENU, &d.view) {
(true, None) => return Err(format!("contributes.menus: {VIEW_ITEM_MENU} needs `view`")),
(true, Some(v)) => {
pkg.manifest.needs_api(&format!("contributes.menus: {VIEW_ITEM_MENU}"), 2)?;
let Some(view) = declared_view(pkg, v) else {
return Err(format!("contributes.menus: view {v:?} is not declared under [[contributes.views]]"));
};
if view.get("web").is_some() {
return Err(format!(
"contributes.menus: view {v:?} is a web view (viewItem.context needs a tree or list the plugin renders)"
));
}
format!("{VIEW_ITEM_MENU}/{v}/{}", d.command)
}
(false, Some(_)) => return Err(format!("contributes.menus: `view` is only for {VIEW_ITEM_MENU}")),
(false, None) => format!("{}/{}", d.menu, d.command),
};
Ok(UiDecl::new(key, d.command.clone(), json(&d)?))
Ok(UiDecl::new(format!("{}/{}", d.menu, d.command), d.command.clone(), json(&d)?))
}
#[derive(Debug, Deserialize, Serialize)]
@@ -405,7 +380,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
out.files = files;
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
let path = std::path::PathBuf::from(icon);
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
let svg = super::icons::read_icon(pkg, &path)?;
out.assets.push((view_icon_asset(&d.id), svg));
out.files.push(path);
}
@@ -498,7 +473,7 @@ pub(super) fn file_icon(pkg: &Package, decl: toml::Value) -> Result<UiDecl, Stri
let mut assets = Vec::new();
for (path, dark) in [(Some(&d.icon), false), (d.icon_dark.as_ref(), true)] {
let Some(path) = path else { continue };
let svg = super::icons::read_icon(pkg, path, super::icons::MAX_SVG)?;
let svg = super::icons::read_icon(pkg, path)?;
assets.push((file_icon_asset(&d.id, dark), svg));
files.push(path.clone());
}
+1 -6
Переглянути файл
@@ -25,12 +25,7 @@ pub fn view_invocation(
Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() })
}
};
Ok(Invocation {
client: Some(window.to_owned()),
workspace_root: project.as_ref().map(|p| p.root.clone()),
editor,
..Invocation::default()
})
Ok(Invocation { client: Some(window.to_owned()), workspace_root: project.as_ref().map(|p| p.root.clone()), editor })
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
-15
Переглянути файл
@@ -74,21 +74,6 @@ impl TrustStore {
Ok(())
}
pub fn add_location(&self, path: &Path) -> IdeResult<()> {
let root = dunce::canonicalize(path)?;
if !root.is_dir() {
return Err(IdeError::invalid("trusted location must be an existing directory"));
}
let mut state = self.state.lock();
let mut next = state.clone()?;
if !next.locations.contains(&root) {
next.locations.push(root);
persist(&self.file, &next)?;
*state = Ok(next);
}
Ok(())
}
pub fn remove_location(&self, path: &Path) -> IdeResult<()> {
let mut state = self.state.lock();
let mut next = state.clone()?;
+2 -25
Переглянути файл
@@ -1,7 +1,7 @@
//! Versioned installs with automatic rollback, signed packages from
//! a static marketplace index, and revocation.
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, PluginIcon, Publisher, PublisherKey, Revocation};
use ide_extension::package::{self, Index, IndexEntry, KeyEntry, Publisher, PublisherKey, Revocation};
use ide_host::plugins::*;
use ide_plugin::{Invocation, Limits};
use parking_lot::Mutex;
@@ -58,7 +58,7 @@ fn fixture() -> Fixture {
}
fn inv() -> Invocation {
Invocation { client: Some("main".into()), workspace_root: None, editor: None, selected_paths: Vec::new() }
Invocation { client: Some("main".into()), workspace_root: None, editor: None }
}
fn misbehave() -> PathBuf {
@@ -169,7 +169,6 @@ fn signed(
capabilities: vec![],
engine: "^1.0".into(),
categories: vec!["tools".into()],
icon: None,
};
(out, entry)
}
@@ -510,25 +509,3 @@ fn official_plugins_need_the_key_this_ide_was_built_with() {
let dir = f.host.download_market_plugin("openidea.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().publisher.as_deref(), Some(OFFICIAL_PUBLISHER));
}
#[test]
fn marketplace_icons_are_sanitised_or_dropped() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (_, entry) = signed_hello(&market, "1.0.0", &key, &f.host);
let icon = |light: &str| Some(PluginIcon { light: light.into(), dark: None });
let good =
IndexEntry { icon: icon(r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#), ..entry.clone() };
let hostile = IndexEntry { id: "acme.hostile".into(), icon: icon(r#"<svg onload="x()"><rect/></svg>"#), ..entry };
let padded = format!("<svg viewBox=\"0 0 16 16\"><!--{}--><rect/></svg>", " ".repeat(20 << 10));
let padded = IndexEntry { id: "acme.padded".into(), icon: icon(&padded), ..hostile.clone() };
f.host.set_market_url(Some(write_index(&market, &key, vec![good, hostile, padded], vec![], false)));
let listed = f.host.refresh_market().unwrap();
let by_id = |id: &str| listed.iter().find(|p| p.entry.id == id).unwrap_or_else(|| panic!("{id} not listed"));
assert!(by_id("acme.hello").entry.icon.as_ref().unwrap().light.contains("<rect"));
assert!(by_id("acme.hostile").entry.icon.is_none(), "an unsafe icon is dropped, the entry stays");
assert!(by_id("acme.padded").entry.icon.is_none(), "an icon over 16 KiB is dropped before it is sanitised");
}
+1 -12
Переглянути файл
@@ -303,18 +303,7 @@ impl Smoke {
let (doc, pos) = self.locate(of).await;
let want: BTreeSet<String> = files.iter().map(|f| f.to_string()).collect();
self.retry("find usages", self.warm_up, || async {
let found = ops::lsp::lsp_references(
&self.host,
WINDOW,
RequestId(1),
doc,
pos,
true,
true,
false,
ops::Channel::new(|_| {}),
)
.await;
let found = ops::lsp::lsp_references(&self.host, WINDOW, RequestId(1), doc, pos, true, true).await;
match &found {
Ok(r) if want.is_subset(&self.files(r.locations.iter().map(|l| l.path.clone()))) => Ok(()),
_ => Err(found.map(|r| self.files(r.locations.into_iter().map(|l| l.path)))),
+1 -1
Переглянути файл
@@ -160,7 +160,7 @@ async fn light_notebooks_open_without_interpreter_detection_or_execution() {
assert!(ops::notebook::save(&host, "main", notebook.id.clone()).await.is_ok());
let error = ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Python).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"));
assert!(ops::sdk::sdk_python_effective(&host, "main", None).is_err());
assert!(ops::sdk::sdk_python_effective(&host, "main").is_err());
assert!(ops::sdk::sdk_locate_tools(&host, "main", vec!["prettier".into()], Some(root)).await.is_err());
let error = ops::notebook::restart(&host, "main", notebook.id.clone()).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"));
+1 -6
Переглянути файл
@@ -171,12 +171,7 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() {
.index_navigation(
&f.root,
Snapshot { path, version: Some(1), text, symbols: &symbols, scope: "" },
Invocation {
client: Some(client.into()),
workspace_root: Some(f.root.clone()),
editor: None,
selected_paths: Vec::new(),
},
Invocation { client: Some(client.into()), workspace_root: Some(f.root.clone()), editor: None },
)
.unwrap();
}
+2 -385
Переглянути файл
@@ -231,12 +231,7 @@ fn fixture(limits: Limits) -> Fixture {
impl Fixture {
fn inv(&self) -> Invocation {
Invocation {
client: Some("main".into()),
workspace_root: Some(self.project.clone()),
editor: None,
selected_paths: Vec::new(),
}
Invocation { client: Some("main".into()), workspace_root: Some(self.project.clone()), editor: None }
}
fn install(&self, dir: &Path) -> PluginInfo {
@@ -362,7 +357,7 @@ fn read_file_is_confined_to_the_project() {
assert!(err.contains("outside the project root"), "{err}");
assert!(f.run("misbehave", "read", Some("/etc/hosts")).is_err());
// Without a project there is nothing to read.
let inv = Invocation::default();
let inv = Invocation { client: None, workspace_root: None, editor: None };
let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message;
assert!(err.contains("no project is open"), "{err}");
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), to_ipc(&f.project));
@@ -673,7 +668,6 @@ fn contribution_only_plugins() {
let theme = f.install(&theme_template());
assert_eq!(theme.status, PluginStatus::Static);
assert!(!theme.has_code);
assert!(theme.icon.is_none());
assert_eq!(f.theme_kinds("openidea.harbor-night")[0].0, "harbor-night");
let lang = f.install(&sample("language-toy"));
assert_eq!(lang.status, PluginStatus::Static);
@@ -1940,69 +1934,6 @@ fn official_csv_editor_edits_the_shared_document() {
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
}
#[test]
fn view_item_menus_name_a_declared_view() {
/// The menu is new in API 1.2.
fn api_1_2(m: &str) -> String {
m.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.2\"")
}
fn with_menu(extra: &str) -> impl Fn(&str) -> String + '_ {
move |m: &str| format!("{}\n[[contributes.menus]]\ncommand = \"word-count\"\n{extra}\n", api_1_2(m))
}
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let second_view =
"[[contributes.views]]\nid = \"more\"\ntitle = \"More\"\nicon = \"plugin\"\nlocation = \"right\"\n";
let ok = hello_variant(tmp.path(), |m| {
let on_greetings =
with_menu("menu = \"viewItem.context\"\nview = \"greetings\"\nwhen = \"viewItemKind == English\"")(m);
let on_more = with_menu("menu = \"viewItem.context\"\nview = \"more\"")("");
format!("{on_greetings}\n{second_view}\n{on_more}")
});
assert_eq!(f.install(&ok).status, PluginStatus::Inactive);
let item = f.host.ui_items("menus").into_iter().find(|i| i.decl["menu"] == "viewItem.context").unwrap();
assert_eq!(
(item.key.as_str(), item.decl["view"].as_str()),
("viewItem.context/greetings/word-count", Some("greetings"))
);
let keys: Vec<String> = f.host.ui_items("menus").into_iter().map(|i| i.key).collect();
for view in ["greetings", "more"] {
assert!(keys.contains(&format!("viewItem.context/{view}/word-count")), "{keys:?}");
}
f.host.uninstall("hello").unwrap();
for (extra, message) in [
("menu = \"viewItem.context\"", "needs `view`"),
("menu = \"viewItem.context\"\nview = \"nope\"", "view \"nope\" is not declared"),
("menu = \"projectView.context\"\nview = \"greetings\"", "`view` is only for viewItem.context"),
] {
let dir = tempfile::tempdir().unwrap();
let err = f.host.install_from_dir(&hello_variant(dir.path(), with_menu(extra)), &Consent::all()).unwrap_err();
assert!(err.message.contains(message), "{extra}: {}", err.message);
}
let dir = tempfile::tempdir().unwrap();
let web_view = "[[contributes.views]]\nid = \"page\"\ntitle = \"Page\"\nicon = \"plugin\"\nlocation = \"right\"\nweb = \"web/index.html\"\n";
let pkg = hello_variant(dir.path(), |m| {
let on_page = with_menu("menu = \"viewItem.context\"\nview = \"page\"")("");
format!("{}\n{web_view}\n{on_page}", api_1_2(m))
});
std::fs::create_dir_all(pkg.join("web")).unwrap();
std::fs::write(pkg.join("web/index.html"), "<p>hi</p>").unwrap();
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
assert!(err.message.contains("is a web view"), "{}", err.message);
let dir = tempfile::tempdir().unwrap();
let old = hello_variant(dir.path(), |m| {
format!(
"{m}\n[[contributes.menus]]\nmenu = \"viewItem.context\"\nview = \"greetings\"\ncommand = \"word-count\"\n"
)
});
let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.2"), "{}", err.message);
}
/// The sample plugin makes a tool window with a tree view.
/// Its menus, shortcut and status bar item are declarations, listed before
/// any code runs; the tree is rendered by the code, which loads on first show.
@@ -2147,17 +2078,6 @@ fn views_open_project_files_at_a_line() {
assert!(opened.is_none());
}
#[test]
fn commands_see_the_paths_they_were_run_on() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let (a, b) = (f.project.join("src/a.txt"), f.project.join("src/b.txt"));
let inv = Invocation { selected_paths: vec![a.clone(), b.clone()], ..f.inv() };
let out = f.host.run_command("jobs", "selection", Some(&to_ipc(&a)), inv).unwrap();
assert_eq!(out.as_deref(), Some(format!("{}\n{}", to_ipc(&a), to_ipc(&b)).as_str()));
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
}
#[test]
fn vcs_remotes_clipboard_and_open_url() {
let f = fixture(Limits::default());
@@ -2214,126 +2134,6 @@ fn vcs_remotes_clipboard_and_open_url() {
}
}
/// Runs `cmd` of the jobs plugin; once it asks the user, answers after `delay`
/// (`None`: dismisses). Returns the command's result and what it asked.
fn run_and_answer(
f: &Fixture,
cmd: &str,
arg: Option<&str>,
answer: Option<&[&str]>,
delay: Duration,
) -> (Result<Option<String>, String>, ide_plugin::Prompt) {
std::thread::scope(|scope| {
let running = scope.spawn(|| f.run("jobs", cmd, arg));
let deadline = Instant::now() + Duration::from_secs(10);
let (client, prompt_id, prompt) = loop {
let asked = f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::PromptRequested { prompt_id, prompt, .. } => Some((client, prompt_id, prompt)),
_ => None,
});
if let Some(asked) = asked {
break asked;
}
assert!(Instant::now() < deadline && !running.is_finished(), "the command never asked");
std::thread::sleep(Duration::from_millis(10));
};
assert_eq!(client.as_deref(), Some("main"), "asks in the window that ran the command");
std::thread::sleep(delay);
let answer = answer.map(|a| a.iter().map(|s| (*s).to_owned()).collect());
assert!(f.host.answer_prompt(&prompt_id, answer));
assert!(!f.host.answer_prompt(&prompt_id, None), "an answer counts once");
(running.join().unwrap(), prompt)
})
}
#[test]
fn commands_ask_the_user_and_reveal_their_views() {
use ide_plugin::{PickItem, Prompt};
let f = fixture(Limits { timeout: Duration::from_millis(500), ..Limits::default() });
let info = f.install(&sample("jobs"));
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
let none = Duration::ZERO;
let (result, prompt) = run_and_answer(&f, "pick", None, Some(&["b"]), none);
assert_eq!(result.unwrap().as_deref(), Some("b"));
let items = vec![
PickItem { key: "a".into(), label: "Alpha".into(), description: Some("first".into()) },
PickItem { key: "b".into(), label: "Beta".into(), description: None },
PickItem { key: "c".into(), label: "Gamma".into(), description: None },
];
assert_eq!(prompt, Prompt::QuickPick { title: "Pick".into(), items, multiple: false });
let (result, prompt) = run_and_answer(&f, "pick-many", None, Some(&["a", "c"]), none);
assert_eq!(result.unwrap().as_deref(), Some("a,c"));
assert!(matches!(prompt, Prompt::QuickPick { multiple: true, .. }));
assert_eq!(run_and_answer(&f, "pick", None, None, none).0.unwrap().as_deref(), Some("none"));
let (result, prompt) = run_and_answer(&f, "input", Some("Main"), Some(&["Other"]), none);
assert_eq!(result.unwrap().as_deref(), Some("Other"));
assert_eq!(prompt, Prompt::Input { prompt: "Name".into(), value: Some("Main".into()) });
assert_eq!(run_and_answer(&f, "input", None, None, none).0.unwrap().as_deref(), Some("none"));
let (result, prompt) = run_and_answer(&f, "confirm", None, Some(&[]), none);
assert_eq!(result.unwrap().as_deref(), Some("true"));
assert_eq!(prompt, Prompt::Confirm { title: "Delete".into(), message: "Really?".into() });
assert_eq!(run_and_answer(&f, "confirm", None, None, none).0.unwrap().as_deref(), Some("false"));
// The wait is not part of the call's 500 ms budget.
let (result, _) = run_and_answer(&f, "confirm", None, Some(&[]), Duration::from_millis(1200));
assert_eq!(result.unwrap().as_deref(), Some("true"));
// Keys come back as given: one that doesn't fit is refused, not cut.
f.take_events();
let err = f.run("jobs", "pick", Some("long-key")).unwrap_err();
assert!(err.contains("item key is longer"), "{err}");
assert!(f.take_events().iter().all(|(_, e)| !matches!(e, PluginEvent::PromptRequested { .. })));
// Without a window there is nothing to attach the dialog to.
f.take_events();
let no_window = Invocation { client: None, ..f.inv() };
for cmd in ["pick", "input", "confirm"] {
let err = f.host.run_command("jobs", cmd, None, no_window.clone()).unwrap_err().message;
assert!(err.contains("from a command the user invoked"), "{cmd}: {err}");
}
assert!(f.take_events().iter().all(|(_, e)| !matches!(e, PluginEvent::PromptRequested { .. })));
// `views.reveal` only knows the plugin's own declared views.
f.take_events();
f.run("jobs", "reveal", Some("jobs")).unwrap();
let revealed = f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::RevealView { plugin_id, view } => Some((client, plugin_id, view)),
_ => None,
});
assert_eq!(revealed, Some((Some("main".into()), "jobs".into(), "jobs".into())));
for view in ["greetings", ""] {
let err = f.run("jobs", "reveal", Some(view)).unwrap_err();
assert!(err.contains("declares no view"), "{view:?}: {err}");
}
assert!(f.run("jobs", "reveal", Some("jobs")).is_ok(), "the instance survives");
}
#[test]
fn disabling_a_plugin_that_waits_for_an_answer_does_not_hang() {
let f = fixture(Limits::default());
let info = f.install(&sample("jobs"));
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
std::thread::scope(|scope| {
let running = scope.spawn(|| f.run("jobs", "confirm", None));
let deadline = Instant::now() + Duration::from_secs(10);
while !f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })) {
assert!(Instant::now() < deadline && !running.is_finished(), "the command never asked");
std::thread::sleep(Duration::from_millis(10));
}
let started = Instant::now();
f.host.set_enabled("jobs", false).unwrap();
assert!(started.elapsed() < Duration::from_secs(5), "disabling waited for the user");
assert!(running.join().unwrap().is_err(), "the waiting command ends with an error");
});
f.host.set_enabled("jobs", true).unwrap();
let (result, _) = run_and_answer(&f, "confirm", None, Some(&[]), Duration::ZERO);
assert_eq!(result.unwrap().as_deref(), Some("true"), "prompts work again after the restart");
}
#[test]
fn views_can_use_an_svg_icon_from_the_package() {
let f = fixture(Limits::default());
@@ -2810,186 +2610,3 @@ fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
let d = f.workspace.diagnostics.lock().get(&("misbehave".into(), path)).cloned().unwrap();
assert_eq!((d[0].unnecessary, d[0].deprecated, d[0].source.as_deref()), (true, false, Some("lint")));
}
#[test]
fn plugins_set_their_own_context_keys() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.take_events();
f.run("jobs", "context", Some("connected=true")).unwrap();
let changed: Vec<_> = f
.take_events()
.into_iter()
.filter_map(|(client, e)| match e {
PluginEvent::ContextChanged { plugin_id, key, value } => Some((client, plugin_id, key, value)),
_ => None,
})
.collect();
assert_eq!(changed, [(Some("main".into()), "jobs".into(), "connected".into(), Some("true".into()))]);
assert_eq!(f.host.context_keys(Some("main")).len(), 1);
assert!(f.host.context_keys(Some("other")).is_empty(), "window-scoped");
for bad in ["bad key=true", "a.b=true", "x=NaN"] {
assert!(f.run("jobs", "context", Some(bad)).unwrap_err().contains("invalid"), "{bad}");
}
f.run("jobs", "context", Some("connected=")).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty());
f.run("jobs", "context", Some("connected=true")).unwrap();
f.host.set_enabled("jobs", false).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty(), "cleared when the plugin stops");
}
#[test]
fn context_keys_are_capped_and_windows_overlay_global_ones() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
for i in 0..100 {
f.run("jobs", "context", Some(&format!("k{i}=1"))).unwrap();
}
assert!(f.run("jobs", "context", Some("k100=1")).unwrap_err().contains("invalid"));
f.run("jobs", "context", Some("k0=2")).unwrap();
for i in 1..4 {
f.run("jobs", "context", Some(&format!("k{i}="))).unwrap();
}
let global = Invocation { client: None, ..f.inv() };
f.host.run_command("jobs", "context", Some("g=1"), global.clone()).unwrap();
f.host.run_command("jobs", "context", Some("w=global"), global).unwrap();
f.run("jobs", "context", Some("w=window")).unwrap();
let w = |client| f.host.context_keys(Some(client)).into_iter().find(|k| k.key == "w").map(|k| k.value);
assert_eq!(w("main").as_deref(), Some("\"window\""));
assert_eq!(w("other").as_deref(), Some("\"global\""));
f.run("jobs", "context", Some("w=")).unwrap();
assert_eq!(w("main").as_deref(), Some("\"global\""), "removing the window key reveals the global one");
}
#[test]
fn context_values_are_stored_as_json_and_bounded() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let value = |arg: &str| {
f.run("jobs", "context", Some(arg)).unwrap();
f.host.context_keys(Some("main")).into_iter().find(|k| k.key == "x").unwrap().value
};
assert_eq!(value("x=true"), "true");
assert_eq!(value("x=2.5"), "2.5");
assert_eq!(value("x=say \"hi\""), "\"say \\\"hi\\\"\"");
assert_eq!(value("x=1"), "1");
f.take_events();
f.run("jobs", "context", Some("x=1.0")).unwrap();
assert!(f.take_events().is_empty(), "the same value emits nothing");
let long = format!("x={}", "a".repeat(1025));
assert!(f.run("jobs", "context", Some(&long)).unwrap_err().contains("invalid"));
}
#[test]
fn forgetting_a_window_drops_its_context_keys_silently() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.run("jobs", "context", Some("w=1")).unwrap();
f.take_events();
f.host.forget_client("main");
assert!(f.host.context_keys(Some("main")).is_empty());
assert!(f.take_events().is_empty());
}
#[test]
fn a_closed_window_ignores_late_context_writes_until_its_label_is_reused() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.host.forget_client("main");
f.take_events();
f.run("jobs", "context", Some("late=1")).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty());
let events = f.take_events();
assert!(
!events.iter().any(|(_, e)| matches!(e, PluginEvent::ContextChanged { .. })),
"no context event: {events:?}"
);
f.host.reopen_client("main");
f.run("jobs", "context", Some("fresh=1")).unwrap();
assert_eq!(f.host.context_keys(Some("main"))[0].key, "fresh");
}
#[test]
fn stopping_a_plugin_withdraws_each_context_key_in_its_own_scope() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let global = Invocation { client: None, ..f.inv() };
f.host.run_command("jobs", "context", Some("g=1"), global).unwrap();
f.run("jobs", "context", Some("w=1")).unwrap();
f.take_events();
f.host.set_enabled("jobs", false).unwrap();
let mut removed: Vec<_> = f
.take_events()
.into_iter()
.filter_map(|(client, e)| match e {
PluginEvent::ContextChanged { key, value: None, .. } => Some((client, key)),
_ => None,
})
.collect();
removed.sort();
assert_eq!(removed, [(None, "g".to_owned()), (Some("main".to_owned()), "w".to_owned())]);
}
/// A data-only package `id` in `dir` whose manifest ends with `extra`, plus `files`.
fn icon_package(dir: &Path, id: &str, extra: &str, files: &[(&str, &str)]) -> PathBuf {
let pkg = dir.join(id);
std::fs::create_dir_all(&pkg).unwrap();
std::fs::write(
pkg.join("plugin.toml"),
format!("id = \"{id}\"\nname = \"Iconic\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.2\"\n{extra}"),
)
.unwrap();
for (name, text) in files {
std::fs::write(pkg.join(name), text).unwrap();
}
pkg
}
const RECT: &str = r#"<svg viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#;
const CIRCLE: &str = r#"<svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/></svg>"#;
#[test]
fn plugin_icons_install_with_the_package() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = icon_package(
tmp.path(),
"iconic",
"icon = \"icon.svg\"\nicon-dark = \"icon_dark.svg\"\n",
&[("icon.svg", RECT), ("icon_dark.svg", CIRCLE)],
);
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
let icon = info.icon.expect("icon");
assert!(icon.light.contains("<rect"), "{}", icon.light);
assert!(icon.dark.unwrap().contains("<circle"));
assert!(f.installed("iconic").join("icon_dark.svg").is_file());
f.host.set_enabled("iconic", false).unwrap();
assert!(f.host.info_of("iconic").unwrap().icon.is_some(), "disabled plugins keep their icon");
}
#[test]
fn invalid_plugin_icons_refuse_the_package() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let big = format!("<svg>{}</svg>", "<path d=\"M0 0h1v1z\"/>".repeat(1000));
let padded = format!("<svg><!--{}--><rect/></svg>", " ".repeat(20 << 10));
let cases = [
("scripted", "icon = \"icon.svg\"\n", "<svg><script>alert(1)</script></svg>".to_owned(), "icon.svg"),
("oversized", "icon = \"icon.svg\"\n", big, "16 KiB"),
("padded", "icon = \"icon.svg\"\n", padded, "16 KiB"),
("missing", "icon = \"missing.svg\"\n", RECT.to_owned(), "missing.svg"),
];
for (id, extra, svg, expected) in cases {
let pkg = icon_package(tmp.path(), id, extra, &[("icon.svg", &svg)]);
let err = f.host.preview_install(&pkg).map(|_| ()).unwrap_err().message;
assert!(err.contains(expected), "{id}: {err}");
}
}
+1 -1
Переглянути файл
@@ -276,7 +276,7 @@ async fn python_venv() {
// The project's virtualenv: listed first, and the interpreter the project uses.
let found = ops::sdk::sdk_detect(&p.host, WINDOW, ide_sdk::SdkKind::Python).await.unwrap();
assert_eq!(found.first().map(|s| s.source.as_str()), Some("venv"), "{found:?}");
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW, None).unwrap().expect("an interpreter");
let effective = ops::sdk::sdk_python_effective(&p.host, WINDOW).unwrap().expect("an interpreter");
assert!(effective.starts_with(p.root.join(".venv")), "{effective:?}");
}
-26
Переглянути файл
@@ -300,31 +300,5 @@ async fn remote_projects_get_plugin_views_and_custom_editors() {
})
})
.await;
invoke(
&peer,
"plugin_run_command",
json!({ "pluginId": "jobs", "commandId": "context", "arg": "mode=true", "editor": null }),
)
.await
.unwrap();
until("the context key's event", 5, || {
client.plugin_events.lock().iter().any(|m| {
m.window.as_deref() == Some("main")
&& matches!(&m.event, PluginEvent::ContextChanged { key, value, .. } if key == "mode" && value.as_deref() == Some("true"))
})
})
.await;
let keys = invoke(&peer, "plugin_context_keys", json!({})).await.unwrap();
assert_eq!(keys, json!([{ "pluginId": "jobs", "key": "mode", "value": "true" }]), "{keys}");
let selected = invoke(
&peer,
"plugin_run_command",
json!({ "pluginId": "jobs", "commandId": "selection", "arg": null, "editor": null, "paths": ["/srv/src/a.txt"] }),
)
.await
.unwrap();
assert_eq!(selected, "/srv/src/a.txt");
plugins.host().shutdown();
}
-23
Переглянути файл
@@ -349,29 +349,6 @@ fn trusted_locations_use_canonical_directory_boundaries() {
assert_eq!(trust.status(&alias).unwrap().root.as_ref(), dunce::canonicalize(&other).unwrap());
}
#[test]
fn add_location_trusts_every_project_under_it() {
let tmp = tempfile::tempdir().unwrap();
let location = tmp.path().join("projects");
let inside = location.join("nested/deep/app");
let outside = tmp.path().join("projects-other/app");
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let file = tmp.path().join("not-a-dir");
std::fs::write(&file, "x").unwrap();
let trust = TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
trust.add_location(&location).unwrap();
assert!(trust.trusted(&inside).unwrap());
assert!(!trust.trusted(&outside).unwrap());
assert_eq!(trust.decisions().unwrap().locations.len(), 1);
trust.add_location(&location).unwrap();
assert_eq!(trust.decisions().unwrap().locations.len(), 1, "re-adding is a no-op");
assert!(trust.add_location(&file).is_err(), "a file is not a location");
assert!(trust.add_location(&tmp.path().join("missing")).is_err(), "a missing path is not a location");
let reloaded = TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
assert!(reloaded.trusted(&inside).unwrap());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn restricted_git_views_ignore_project_executables_and_mutations_cannot_run_hooks() {
+1 -24
Переглянути файл
@@ -87,19 +87,12 @@ pub fn prepare(
} else {
with_scheme(&url)
};
// Multipart bodies delimit parts with CRLF per RFC 2046 §5.1; joining
// with bare LF leaves servers (e.g. Tomcat) unable to find the boundary.
let is_multipart = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
.is_some_and(|(_, v)| v.to_ascii_lowercase().starts_with("multipart/"));
let eol = if is_multipart { "\r\n" } else { "\n" };
Ok(PreparedRequest {
name: raw.block.name.clone(),
method: raw.block.method.clone(),
url,
headers,
body: (!body_lines.is_empty()).then(|| body_lines.join(eol)),
body: (!body_lines.is_empty()).then(|| body_lines.join("\n")),
})
}
@@ -212,22 +205,6 @@ mod tests {
assert!(err.message.contains("host"), "{}", err.message);
}
#[test]
fn multipart_bodies_join_lines_with_crlf() {
let f = parse(
"POST https://api.test/upload\nContent-Type: multipart/form-data; boundary=xyz\n\n--xyz\nfield\n--xyz--\n",
);
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
assert_eq!(p.body.as_deref(), Some("--xyz\r\nfield\r\n--xyz--"));
}
#[test]
fn non_multipart_bodies_join_lines_with_lf() {
let f = parse("POST https://api.test/x\nContent-Type: application/json\n\n{\n\"a\": 1\n}\n");
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
assert_eq!(p.body.as_deref(), Some("{\n\"a\": 1\n}"));
}
#[test]
fn relative_urls_use_the_host_header() {
let f = parse("GET /status\nHost: localhost:9000\n");
+20 -91
Переглянути файл
@@ -328,9 +328,6 @@ struct SourceImplementations {
/// Receives the implementations found so far, before a slower search for the rest.
type Partial<'a> = Option<&'a (dyn Fn(Vec<Location>) + Send + Sync)>;
/// Receives the references found so far, before a slower search for the rest.
pub type PartialReferences<'a> = Option<&'a (dyn Fn(References) + Send + Sync)>;
/// `first`, then those of `more` not in it (same file and start).
fn merge_locations(first: Vec<Location>, more: Vec<Location>) -> Vec<Location> {
let mut seen: HashSet<(PathBuf, Pos)> = first.iter().map(|l| (l.path.to_path_buf(), l.range.start)).collect();
@@ -1408,44 +1405,21 @@ impl LspManager {
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
self.references_streaming(doc, pos, include_declaration, project_wide, true, cancel, None).await
}
/// [`Self::references`]. Java, `project_wide`: without `libraries`, only the
/// workspace's sources are searched (`libraries_skipped`); with it, those found
/// there arrive on `partial` before the dependencies and the JDK are searched.
#[allow(clippy::too_many_arguments)]
pub async fn references_streaming(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
cancel: CancellationToken,
partial: PartialReferences<'_>,
) -> IdeResult<References> {
let snap = self.snapshot(doc)?;
// Scoped probes back code lenses and bulk analysis. Keep their native cost;
// configuration indexing is reserved for explicit, project-wide usages.
let configuration = if project_wide || snap.language.as_str() != "java" {
self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await?
} else {
None
};
if snap.language.as_str() != "java"
&& let Some(result) = self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await?
&& let Some(result) = configuration
{
return Ok(result);
}
// Scoped probes back code lenses and bulk analysis. Keep their native cost;
// configuration indexing is reserved for explicit, project-wide usages.
let configuration = async {
if project_wide && snap.language.as_str() == "java" {
self.configuration_navigation(&snap, pos, true, include_declaration, &cancel).await
} else {
Ok(None)
}
};
let native =
self.native_references(doc, pos, include_declaration, project_wide, libraries, cancel.clone(), partial);
let (configuration, result) = futures::join!(configuration, native);
let configuration = configuration?;
let mut result = result?;
let mut result = self.native_references(doc, pos, include_declaration, project_wide, cancel).await?;
if let Some(configuration) = configuration {
result.locations.extend(configuration.locations);
result.incomplete = result.incomplete.or(configuration.incomplete);
@@ -1454,16 +1428,13 @@ impl LspManager {
Ok(result)
}
#[allow(clippy::too_many_arguments)]
async fn native_references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
cancel: CancellationToken,
partial: PartialReferences<'_>,
) -> IdeResult<References> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
// The extension preserves method identity before JDT collapses references to locations.
@@ -1475,37 +1446,28 @@ impl LspManager {
let classified = async {
let t = &targets[0];
let extension_error = Mutex::new(None);
let (snap, cancel, extension_error) = (&snap, &cancel, &extension_error);
// `sources`: the workspace's source folders only, without dependency jars and the JDK.
let query = |sources: bool| async move {
let query = || async {
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
let params = snap.pos_params(t, pos);
let mut arguments = json!([
params["textDocument"]["uri"],
params["position"]["line"],
params["position"]["character"],
include_declaration
]);
if sources {
arguments.as_array_mut().expect("arguments").push(json!("sources"));
}
#[derive(serde::Deserialize)]
struct JavaReference {
#[serde(default)]
access: Option<ReferenceAccess>,
location: lsp::Location,
kind: ReferenceKind,
#[serde(default)]
text: Option<String>,
}
let result: IdeResult<Vec<JavaReference>> = self
.call(
t,
"workspace/executeCommand",
json!({ "command": "openidea.java.usages", "arguments": arguments }),
Some(cancel),
json!({
"command": "openidea.java.usages",
"arguments": [params["textDocument"]["uri"], params["position"]["line"],
params["position"]["character"], include_declaration]
}),
Some(&cancel),
LONG_TIMEOUT,
)
.await;
@@ -1524,7 +1486,6 @@ impl LspManager {
location,
kind: r.kind,
access: r.access,
text: r.text,
})
})
.collect::<Vec<_>>())
@@ -1532,42 +1493,10 @@ impl LspManager {
let files = |v: &Vec<ClassifiedReference>| {
v.iter().filter(|r| r.location.uri.is_none()).map(|r| r.location.path.to_path_buf()).collect()
};
let mut libraries_skipped = false;
let widened = if project_wide {
// A library method has thousands of usages in the dependencies and the JDK,
// which take seconds to search: those in the sources (where scope widening
// searches again) are shown first, then the rest are searched once.
let sources = self.widened(snap, t, pos, cancel, || query(true), files).await?;
if let Some(e) = extension_error.lock().take() {
return Err(e);
}
let mut seen = std::collections::HashSet::new();
let found: Vec<_> = sources
.second
.into_iter()
.flatten()
.chain(sources.first)
.filter(|r| seen.insert(r.location.clone()))
.collect();
let all = if !libraries {
libraries_skipped = true;
Vec::new()
} else {
if let Some(partial) = partial
&& !found.is_empty()
{
partial(References {
locations: found.iter().map(|r| r.location.clone()).collect(),
classified: found.clone(),
incomplete: sources.incomplete,
libraries_skipped: false,
});
}
query(false).await?
};
scope::Widened { first: all, second: Some(found), incomplete: sources.incomplete }
self.widened(&snap, t, pos, &cancel, query, files).await?
} else {
let first = query(false).await?;
let first = query().await?;
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
};
@@ -1576,7 +1505,7 @@ impl LspManager {
return Err(IdeError::cancelled());
}
// Scope widening can retain the first answer after a failed second query.
if let Some(e) = extension_error.lock().take() {
if let Some(e) = extension_error.into_inner() {
return Err(e);
}
let mut seen = std::collections::HashSet::new();
@@ -1590,7 +1519,7 @@ impl LspManager {
.collect();
let locations: Vec<Location> = classified.iter().map(|r| r.location.clone()).collect();
self.note_virtual(&t.server, locations.iter().map(|l| l.uri.as_deref()));
Ok(References { locations, classified, incomplete: widened.incomplete, libraries_skipped })
Ok(References { locations, classified, incomplete: widened.incomplete })
}
.await;
match classified {
-8
Переглянути файл
@@ -380,10 +380,6 @@ pub struct References {
pub classified: Vec<ClassifiedReference>,
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
/// The dependencies and the JDK were not searched (asked for without `libraries`).
#[serde(default)]
#[specta(optional)]
pub libraries_skipped: bool,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
@@ -507,8 +503,4 @@ pub struct ClassifiedReference {
pub access: Option<ReferenceAccess>,
pub location: Location,
pub kind: ReferenceKind,
/// The usage's line, when the server has it at hand (a library class's).
#[serde(default)]
#[specta(optional)]
pub text: Option<String>,
}
+1 -93
Переглянути файл
@@ -2882,8 +2882,7 @@ async fn classified_java_references_widen_without_losing_metadata() {
assert!(refs.classified.iter().all(|r| matches!(r.access, Some(ReferenceAccess::ReadWrite))));
assert!(refs.classified.iter().all(|r| matches!(r.kind, ReferenceKind::Field)));
assert_eq!(refs.incomplete, None);
// Scoped; then the sources, widened; then the dependencies too.
assert_eq!(s.requested("workspace/executeCommand").len(), 4);
assert_eq!(s.requested("workspace/executeCommand").len(), 3);
assert!(s.requested("textDocument/references").is_empty());
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
for limit_hit in [true, false] {
@@ -2901,97 +2900,6 @@ async fn classified_java_references_widen_without_losing_metadata() {
}
}
/// A library method's usages in the sources are shown before the dependencies and the JDK
/// are searched, which takes seconds; scope widening searches the sources alone again.
#[tokio::test(flavor = "multi_thread")]
async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
let library = json!({"uri": "jdt://contents/lib.jar/lib/Lib.class", "range": {
"start": {"line": 3, "character": 4}, "end": {"line": 3, "character": 10}}});
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
(method == "workspace/executeCommand").then(|| {
let sources = params["arguments"].get(4) == Some(&json!("sources"));
let mut rows: Vec<Value> = s
.docs
.lock()
.iter()
.flat_map(|(uri, text)| occurrences(uri, text))
.map(|location| json!({"location": location, "kind": "unknown"}))
.chain((!sources).then(|| json!({"location": library, "kind": "unknown", "text": " target();"})))
.collect();
rows.reverse();
Value::Array(rows)
})
}));
let b = h.root.join("b.java");
std::fs::write(&b, "target();").unwrap();
grep_candidates(&h);
let (doc, a) = h.open("a.java", "int target;");
h.wait_status("jdtls", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let partials = Mutex::new(Vec::new());
let refs = h
.mgr
.references_streaming(
doc,
Pos::new(0, 5),
true,
true,
true,
Default::default(),
Some(&|r| partials.lock().push(r)),
)
.await
.unwrap();
let partials = partials.into_inner();
assert_eq!(partials.len(), 1);
let paths =
|r: &References| r.locations.iter().map(|l| (l.path.to_path_buf(), l.uri.is_some())).collect::<Vec<_>>();
let mut shown = paths(&partials[0]);
shown.sort();
assert_eq!(shown, [(a.clone(), false), (b.clone(), false)]);
assert_eq!(partials[0].classified.len(), 2);
// All of them, those in the sources first.
assert_eq!(refs.locations.len(), 3);
assert!(refs.locations[..2].iter().all(|l| l.uri.is_none()));
assert!(refs.locations[2].uri.is_some());
// The server gives a library class's line along.
let line = |r: &References| r.classified.iter().find(|c| c.location.uri.is_some()).and_then(|c| c.text.clone());
assert_eq!(line(&refs).as_deref(), Some(" target();"));
assert!(!refs.libraries_skipped);
let scopes: Vec<_> =
s.requested("workspace/executeCommand").iter().map(|p| p["arguments"].get(4).cloned()).collect();
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources")), None]);
// Without the libraries: the sources alone, widened, and no partial answer.
let partials = Mutex::new(Vec::new());
let project = h
.mgr
.references_streaming(
doc,
Pos::new(0, 5),
true,
true,
false,
Default::default(),
Some(&|r| partials.lock().push(r)),
)
.await
.unwrap();
assert!(partials.into_inner().is_empty());
assert!(project.libraries_skipped);
assert_eq!(project.locations.len(), 2);
assert!(project.locations.iter().all(|l| l.uri.is_none()));
let scopes: Vec<_> =
s.requested("workspace/executeCommand")[3..].iter().map(|p| p["arguments"].get(4).cloned()).collect();
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources"))]);
// Scoped probes (code lenses) search everything at once.
let scoped = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(scoped.locations.len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn failed_java_command_falls_back_to_unclassified_native_references() {
for project_wide in [false, true] {
+1 -32
Переглянути файл
@@ -5,7 +5,7 @@
use crate::types::{CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, ProviderDocument};
use crate::types::{
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput, Prompt,
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput,
RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol, SyntaxToken, WorkbenchEvent,
};
use crate::types::{
@@ -55,32 +55,8 @@ pub trait HostApi: Send + Sync {
let _ = (client, url);
Ok(())
}
/// Shows `prompt` in `client`'s window and waits for the answer until the
/// user gives one or `cancel` fires: the chosen keys (`QuickPick`), the
/// text (`Input`, one element) or any value (`Confirm`: OK); `None` when
/// dismissed.
fn ask(
&self,
client: Option<&str>,
prompt: Prompt,
cancel: &CancellationToken,
) -> Result<Option<Vec<String>>, HostError> {
let _ = (client, prompt, cancel);
Ok(None)
}
/// Brings the plugin's declared view to the front in `client`'s window.
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
let _ = (client, view);
Ok(())
}
/// Sets (`Some`) or removes the plugin's status bar item `id`.
fn status_item(&self, id: &str, item: Option<StatusItem>);
/// Sets (`Some`, validated JSON text) or removes the plugin's context key,
/// for window `client` (every window if `None`).
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
let _ = (client, key, value);
Ok(())
}
/// Roots of the open projects.
fn projects(&self) -> Vec<std::path::PathBuf>;
/// Unsaved text of an open editor's file.
@@ -382,8 +358,6 @@ pub struct StoreData {
pub(crate) granted: Vec<Capability>,
pub(crate) host: Arc<dyn HostApi>,
pub(crate) invocation: Invocation,
/// The running call is a command or an event, so it may ask the user.
pub(crate) interactive: bool,
/// Tasks begun by the running call and not ended yet.
pub(crate) open_tasks: Vec<u64>,
pub(crate) last_report: Option<Instant>,
@@ -564,7 +538,6 @@ impl Runtime {
granted: setup.granted,
host: setup.host,
invocation: Invocation::default(),
interactive: false,
open_tasks: Vec::new(),
last_report: None,
};
@@ -864,7 +837,6 @@ impl Runtime {
) -> Result<Option<String>, CallError> {
let result = self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let r = e.plugin.openidea_plugin_commands().call_run(
&mut *store,
id,
@@ -915,7 +887,6 @@ impl Runtime {
let event = event_to_wit_view(event);
let result = self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let views = e.views.as_ref().expect("checked");
let r = views.call_handle(&mut *store, view, &event, wasmtime::component::Resource::new_borrow(ctx.rep()));
store.data_mut().drop_invocation(ctx);
@@ -929,7 +900,6 @@ impl Runtime {
let events: Vec<wit_events::Event> = events.into_iter().take(MAX_BATCH).map(event_to_wit).collect();
self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let r = e.plugin.openidea_plugin_event_handler().call_handle(
&mut *store,
&events,
@@ -966,7 +936,6 @@ impl Runtime {
let result = f(&self.exports, &mut self.store);
let data = self.store.data_mut();
data.invocation = Invocation::default();
data.interactive = false;
// Tasks don't outlive the call that began them.
for id in std::mem::take(&mut data.open_tasks) {
data.host.task_end(id);
-23
Переглянути файл
@@ -28,8 +28,6 @@ pub struct Invocation {
pub client: Option<String>,
pub workspace_root: Option<PathBuf>,
pub editor: Option<EditorContext>,
/// Files and folders the command was run on.
pub selected_paths: Vec<PathBuf>,
}
/// A failed host call, as the plugin sees it (WIT `types.error`).
@@ -68,27 +66,6 @@ pub struct StatusItem {
pub command: Option<String>,
}
/// An entry of a plugin's `pick` or `pick-many`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PickItem {
pub key: String,
pub label: String,
pub description: Option<String>,
}
/// What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`, `ui.confirm`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Prompt {
#[serde(rename_all = "camelCase")]
QuickPick { title: String, items: Vec<PickItem>, multiple: bool },
#[serde(rename_all = "camelCase")]
Input { prompt: String, value: Option<String> },
#[serde(rename_all = "camelCase")]
Confirm { title: String, message: String },
}
/// Kinds of workbench events a plugin can subscribe to (`on-event:<kind>`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
+2 -113
Переглянути файл
@@ -2,11 +2,9 @@
//! types and the implementation of every import. Capabilities are checked
//! here; a missing one returns `error::denied` (the plugin can degrade).
use crate::runtime::{MAX_TITLE, StoreData, clip};
use crate::runtime::{StoreData, clip};
use crate::sandbox;
use crate::types::{
EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, PickItem, Prompt, StatusItem, net_host,
};
use crate::types::{EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, StatusItem, net_host};
use ide_core::ipc_path::to_ipc;
use ide_extension::Capability;
use std::path::{Path, PathBuf};
@@ -135,8 +133,6 @@ const MAX_DIAGNOSTICS: usize = 5_000;
const MAX_REQUEST_BODY: usize = 8 << 20;
const MAX_FIND: u32 = 10_000;
const MAX_STATUS_TEXT: usize = 128;
const MAX_PICK_ITEMS: usize = 5000;
const MAX_PICK_KEY: usize = 256;
type Fallible<T> = wasmtime::Result<Result<T, wit::Error>>;
@@ -216,52 +212,6 @@ impl log::Host for StoreData {
}
}
impl StoreData {
/// Asks the user and waits; the wait doesn't count against the call's
/// wall-clock budget.
fn ask(&mut self, prompt: Prompt) -> Result<Option<Vec<String>>, wit::Error> {
self.require_interactive()?;
let client = self.invocation.client.clone();
let started = Instant::now();
let answer = self.host.ask(client.as_deref(), prompt, &self.cancel.token());
let waited = started.elapsed();
self.deadline += waited;
self.call_started += waited;
answer.map_err(to_wit)
}
fn pick_prompt(
&mut self,
title: String,
items: Vec<ui::PickItem>,
multiple: bool,
) -> Result<Option<Vec<String>>, wit::Error> {
if items.len() > MAX_PICK_ITEMS {
return Err(wit::Error::Invalid(format!("more than {MAX_PICK_ITEMS} items")));
}
if items.iter().any(|i| i.key.len() > MAX_PICK_KEY) {
return Err(wit::Error::Invalid(format!("an item key is longer than {MAX_PICK_KEY} bytes")));
}
let items = items
.into_iter()
.map(|i| PickItem {
key: i.key,
label: clip(i.label, MAX_TITLE),
description: i.description.map(|d| clip(d, 1024)),
})
.collect();
self.ask(Prompt::QuickPick { title: clip(title, MAX_TITLE), items, multiple })
}
/// Dialogs belong to commands and events; rendering and providers have no one to ask.
fn require_interactive(&self) -> Result<(), wit::Error> {
if self.interactive {
return Ok(());
}
Err(wit::Error::Invalid("can only ask the user from a command or event".into()))
}
}
impl ui::Host for StoreData {
fn show_notification(
&mut self,
@@ -294,36 +244,6 @@ impl ui::Host for StoreData {
Ok(())
}
fn set_context(&mut self, key: String, value: ui::ContextValue) -> Fallible<()> {
let valid_key =
(1..=64).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
if !valid_key {
return Ok(Err(wit::Error::Invalid(format!("context key {key:?}: expected 1-64 of A-Za-z0-9_-"))));
}
// Kept as JSON text, which the windows parse into their context.
let json = match value {
ui::ContextValue::Flag(b) => b.to_string(),
ui::ContextValue::Number(n) if n.fract() == 0.0 && n.abs() < 9e15 => (n as i64).to_string(),
ui::ContextValue::Number(n) => match serde_json::Number::from_f64(n) {
Some(n) => n.to_string(),
None => return Ok(Err(wit::Error::Invalid("context value: not a finite number".into()))),
},
ui::ContextValue::Text(t) if t.len() <= 1024 => serde_json::Value::String(t).to_string(),
ui::ContextValue::Text(_) => {
return Ok(Err(wit::Error::Invalid("context value: text longer than 1024 bytes".into())));
}
};
let client = self.invocation.client.clone();
Ok(self.host.set_context(client.as_deref(), &key, Some(json)).map_err(to_wit))
}
fn remove_context(&mut self, key: String) -> wasmtime::Result<()> {
let client = self.invocation.client.clone();
// Nothing to remove under an invalid key.
let _ = self.host.set_context(client.as_deref(), &key, None);
Ok(())
}
fn copy_to_clipboard(&mut self, text: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::Clipboard) {
return Ok(Err(e));
@@ -341,25 +261,6 @@ impl ui::Host for StoreData {
let client = self.invocation.client.clone();
Ok(self.host.open_url(client.as_deref(), trimmed.to_owned()).map_err(to_wit))
}
fn pick(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<String>> {
let answer = self.pick_prompt(title, items, false);
Ok(answer.map(|keys| keys.and_then(|keys| keys.into_iter().next())))
}
fn pick_many(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<Vec<String>>> {
Ok(self.pick_prompt(title, items, true))
}
fn input(&mut self, prompt: String, value: Option<String>) -> Fallible<Option<String>> {
let prompt = Prompt::Input { prompt: clip(prompt, MAX_TITLE), value: value.map(|v| clip(v, 4096)) };
Ok(self.ask(prompt).map(|answer| answer.and_then(|text| text.into_iter().next())))
}
fn confirm(&mut self, title: String, body: String) -> Fallible<bool> {
let prompt = Prompt::Confirm { title: clip(title, MAX_TITLE), message: clip(body, 16 << 10) };
Ok(self.ask(prompt).map(|answer| answer.is_some()))
}
}
impl storage::Host for StoreData {
@@ -518,10 +419,6 @@ impl invocation::HostInvocation for StoreData {
}
}
fn selected_paths(&mut self, _this: Resource<InvocationRes>) -> wasmtime::Result<Vec<String>> {
Ok(self.invocation.selected_paths.iter().take(MAX_FIND as usize).map(|p| to_ipc(p)).collect())
}
fn drop(&mut self, rep: Resource<InvocationRes>) -> wasmtime::Result<()> {
// Owned by the host for the duration of the call.
let _ = rep;
@@ -752,14 +649,6 @@ impl views::Host for StoreData {
Ok(())
}
fn reveal(&mut self, view: String) -> Fallible<()> {
if let Err(e) = self.require_interactive() {
return Ok(Err(e));
}
let client = self.invocation.client.clone();
Ok(self.host.reveal_view(client.as_deref(), &clip(view, 64)).map_err(to_wit))
}
fn post_message(&mut self, view: String, message: String) -> Fallible<()> {
if message.len() > MAX_VIEW_MESSAGE {
return Ok(Err(wit::Error::Invalid(format!("messages are limited to {MAX_VIEW_MESSAGE} bytes"))));
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
20ce53ecb41ad94e9c7d59cd4ac51f63081c9f150832fd7febe07887fa3c07ab
42044c4b2e3d768b922d6e5026ff4e725d37b265896ea7f383f1d737e2feffb7
+1 -1
Переглянути файл
@@ -1 +1 @@
2e7d8932329d9383ecd4938225a111851f8a9805c6da558431dea84b7cecbe1c
87eb2a28875abbc649b98d2a7f87263da217f9ad28f1395d96a61db5f781d9f0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7f58bace9b60d8b6b87c97e78dd8cca4955bd13d5f0737efe9d9a362cd1552bf
3d3e43d4e49efa7a97984335f7f2df2cb286321bd0368251f37818aa6c1b70ad
-10
Переглянути файл
@@ -25,16 +25,6 @@ id = "follow"
title = "Jobs: Follow Selected Job"
category = "Jobs"
[[contributes.commands]]
id = "context"
title = "Jobs: Set Context"
category = "Jobs"
[[contributes.commands]]
id = "selection"
title = "Jobs: Show Selected Paths"
category = "Jobs"
[contributes.settings]
title = "Jobs"
schema = "settings.schema.json"
+1 -35
Переглянути файл
@@ -4,7 +4,7 @@
use openidea_plugin::host;
use openidea_plugin::views::{Body, Button, TreeItem, View, ViewEvent, Viewport, Views};
use openidea_plugin::{Error, Invocation, NotificationLevel, PickItem, Plugin, register_plugin};
use openidea_plugin::{Error, Invocation, Plugin, register_plugin};
pub const VIEW: &str = "jobs";
@@ -40,19 +40,6 @@ impl Plugin for Jobs {
let remotes = project.vcs_remotes()?;
Ok(Some(remotes.into_iter().map(|(n, u)| format!("{n}={u}")).collect::<Vec<_>>().join("\n")))
}
"context" => {
// `key=` removes; `true` / `false`, numbers and other text set.
let (key, value) = arg.unwrap_or_default().split_once('=').ok_or("expected key=value")?;
match value {
"" => host::remove_context(key),
"true" | "false" => host::set_context(key, value == "true")?,
_ => match value.parse::<f64>() {
Ok(n) => host::set_context(key, n)?,
Err(_) => host::set_context(key, value)?,
},
}
Ok(None)
}
"copy" => {
host::copy_to_clipboard(arg.unwrap_or_default())?;
Ok(None)
@@ -61,27 +48,6 @@ impl Plugin for Jobs {
host::open_url(arg.unwrap_or_default())?;
Ok(None)
}
"pick" | "pick-many" => {
let long_key = "k".repeat(300);
let items = [
PickItem::new(if arg == Some("long-key") { &long_key } else { "a" }, "Alpha").description("first"),
PickItem::new("b", "Beta"),
PickItem::new("c", "Gamma"),
];
let picked = match id {
"pick" => host::pick("Pick", &items)?.map(|key| vec![key]),
_ => host::pick_many("Pick", &items)?,
};
Ok(Some(picked.map_or("none".to_owned(), |keys| keys.join(","))))
}
"input" => Ok(Some(host::input("Name", arg)?.unwrap_or_else(|| "none".to_owned()))),
"confirm" => Ok(Some(host::confirm("Delete", "Really?")?.to_string())),
"reveal" => host::reveal_view(arg.unwrap_or_default()).map(|()| None),
"selection" => {
let paths = ctx.selected_paths().join("\n");
host::notify(NotificationLevel::Info, "Selected paths", &paths);
Ok(Some(paths))
}
_ => Err(Error::NotFound(format!("command {id}"))),
}
}
+1 -1
Переглянути файл
@@ -1 +1 @@
ee5ba9209eaf963ccc423828ca2e8ba221345c9c246635283214562668a872ad
1d8561e04cb777efbafc6f64963473b9b69654a72ebb2be34f49c6c53c6f76e2
+100 -182
Переглянути файл
@@ -27,51 +27,18 @@ pub(crate) fn detect_with_profiles(
) -> Vec<RunConfig> {
let mut out = Vec::new();
detect_node(root, &mut out);
detect_projects(root, &["deno.json", "deno.jsonc"], detect_deno, &mut out);
detect_projects(root, &["Cargo.toml"], detect_cargo, &mut out);
detect_deno(root, &mut out);
detect_cargo(root, &mut out);
detect_gradle(root, &mut out);
detect_maven(root, excluded_poms, &mut out);
detect_go(root, &mut out);
detect_projects_matching(
root,
|dir| {
["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"]
.iter()
.any(|name| dir.join(name).is_file())
|| [".venv", "venv"]
.iter()
.any(|name| dir.join(name).join(PyEnv::bin_dir()).join(PyEnv::python_exe()).is_file())
},
detect_python,
&mut out,
);
detect_projects(
root,
&["composer.json", "phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"],
detect_php,
&mut out,
);
detect_projects_matching(root, ruby_project, detect_ruby, &mut out);
for dir in ide_core::project_roots::discover(root, &["CMakeLists.txt"]) {
let start = out.len();
cmake::detect(&dir, if dir == root { profiles } else { None }, &mut out);
if dir != root {
let scope = Scope::new(root, &dir);
for config in &mut out[start..] {
config.id = scope.id(&config.id);
config.name = scope.name(&config.name);
for task in &mut config.extras.before_launch {
if task.kind == "run" {
task.target = scope.id(&task.target);
}
}
crate::scope::rebase(config, &dir, Some(root));
}
}
}
detect_python(root, &mut out);
detect_php(root, &mut out);
detect_ruby(root, &mut out);
cmake::detect(root, profiles, &mut out);
dotnet::detect(root, &mut out);
detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out);
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_godot(root, &mut out);
crate::external::detect(root, &mut out);
@@ -80,80 +47,6 @@ pub(crate) fn detect_with_profiles(
out
}
fn detect_projects(
root: &Path,
markers: &[&str],
detect: impl Fn(&Path, &mut Vec<RunConfig>),
out: &mut Vec<RunConfig>,
) {
detect_projects_matching(
root,
|dir| {
markers.iter().any(|marker| dir.join(marker).is_file())
&& (markers != ["Cargo.toml"] || !cargo_workspace_owns(root, dir))
},
detect,
out,
);
}
fn detect_projects_matching(
root: &Path,
marked: impl Fn(&Path) -> bool,
detect: impl Fn(&Path, &mut Vec<RunConfig>),
out: &mut Vec<RunConfig>,
) {
let mut covered = HashSet::new();
for dir in ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, marked) {
if covered.contains(&dir) {
continue;
}
let mut configs = Vec::new();
detect(&dir, &mut configs);
for config in &configs {
if let Some(module) = &config.extras.module {
covered.insert(ide_core::project_roots::resolve(&dir, Path::new(module)));
}
}
if dir != root {
let scope = Scope::new(root, &dir);
for config in &mut configs {
config.id = scope.id(&config.id);
config.name = scope.name(&config.name);
for task in &mut config.extras.before_launch {
if task.kind == "run" {
task.target = scope.id(&task.target);
}
}
crate::scope::rebase(config, &dir, Some(root));
}
}
out.extend(configs);
}
}
fn cargo_workspace_owns(root: &Path, dir: &Path) -> bool {
let Some(manifest) = read_toml(&dir.join("Cargo.toml")) else { return false };
if manifest.contains_key("workspace") {
return false;
}
dir.ancestors()
.skip(1)
.take_while(|parent| parent.starts_with(root))
.find_map(|parent| {
let manifest = read_toml(&parent.join("Cargo.toml"))?;
let workspace = manifest.get("workspace")?;
let excluded = string_list(workspace.get("exclude"));
Some(
!excluded.iter().any(|excluded| dir.starts_with(parent.join(excluded)))
&& !expand_members(parent, &excluded, "Cargo.toml")
.iter()
.any(|excluded| dir.starts_with(excluded)),
)
})
.unwrap_or(false)
}
fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: id.into(),
@@ -210,7 +103,19 @@ fn first_existing(root: &Path, names: &[&str]) -> Option<PathBuf> {
/// Sorted immediate subdirectories, skipping hidden and vendored ones.
fn subdirs(dir: &Path) -> Vec<PathBuf> {
ide_core::project_roots::children(dir)
let Ok(entries) = fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<PathBuf> = entries
.filter_map(Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter(|e| {
let name = e.file_name();
let name = name.to_string_lossy();
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "target" | "build" | "dist" | "vendor")
})
.map(|e| e.path())
.collect();
dirs.sort();
dirs
}
/// Expands workspace member patterns one level deep: `dir`, `dir/*`, `dir/**`.
@@ -246,8 +151,25 @@ fn relative(root: &Path, dir: &Path) -> PathBuf {
// ---------------------------------------------------------------- node
pub(crate) fn package_manager(root: &Path, _pkg: &Json) -> &'static str {
ide_core::project_roots::package_manager(root)
pub(crate) fn package_manager(root: &Path, pkg: &Json) -> &'static str {
if let Some(pm) = pkg.get("packageManager").and_then(Json::as_str) {
match pm.split('@').next().unwrap_or_default() {
"pnpm" => return "pnpm",
"yarn" => return "yarn",
"bun" => return "bun",
"npm" => return "npm",
_ => {}
}
}
if root.join("pnpm-lock.yaml").is_file() {
"pnpm"
} else if root.join("yarn.lock").is_file() {
"yarn"
} else if root.join("bun.lock").is_file() || root.join("bun.lockb").is_file() {
"bun"
} else {
"npm"
}
}
pub(crate) fn is_test_script(name: &str) -> bool {
@@ -264,7 +186,6 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option<PathBuf>
None => (format!("npm:{script}"), format!("{pm} run {script}")),
};
let mut c = config(id, name, "npm", pm, &["run", script]).in_dir(cwd.clone()).debug("js-debug");
c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc);
if is_test_script(script) {
c = c.test();
}
@@ -300,34 +221,27 @@ fn node_workspace_patterns(root: &Path, pkg: &Json) -> Vec<String> {
}
fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
let mut covered = HashSet::new();
let projects =
ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("package.json").is_file()
});
for dir in projects {
if !covered.insert(dir.clone()) {
continue;
let Some(pkg) = read_json(&root.join("package.json")) else {
// A polyglot repository: front-end packages one level down (`web/`, `frontend/`).
for dir in subdirs(root) {
let Some(member) = read_json(&dir.join("package.json")) else { continue };
let rel = relative(root, &dir);
let label = rel.to_string_lossy().replace('\\', "/");
push_scripts(&member, package_manager(&dir, &member), Some(&label), Some(rel), out);
}
let Some(pkg) = read_json(&dir.join("package.json")) else { continue };
let pm = package_manager(&dir, &pkg);
return;
};
let pm = package_manager(root, &pkg);
push_scripts(&pkg, pm, None, None, out);
for dir in expand_members(root, &node_workspace_patterns(root, &pkg), "package.json") {
let Some(member) = read_json(&dir.join("package.json")) else { continue };
let rel = relative(root, &dir);
let label = ide_core::ipc_path::to_ipc(&rel);
push_scripts(&pkg, pm, (dir != root).then_some(label.as_str()), (dir != root).then_some(rel), out);
for member_dir in expand_members(&dir, &node_workspace_patterns(&dir, &pkg), "package.json") {
if !covered.insert(member_dir.clone()) {
continue;
}
let Some(member) = read_json(&member_dir.join("package.json")) else { continue };
let rel = relative(root, &member_dir);
let name = member
.get("name")
.and_then(Json::as_str)
.map(str::to_owned)
.unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel));
let name = if dir == root { name } else { format!("{label}:{name}") };
push_scripts(&member, pm, Some(&name), Some(rel), out);
}
let label = member
.get("name")
.and_then(Json::as_str)
.map(str::to_owned)
.unwrap_or_else(|| rel.to_string_lossy().replace('\\', "/"));
push_scripts(&member, pm, Some(&label), Some(rel), out);
}
}
@@ -441,31 +355,12 @@ fn detect_cargo(root: &Path, out: &mut Vec<RunConfig>) {
} else {
format!("cargo:run:{pkg}:{bin}")
};
let mut run = config(id, format!("cargo run {bin}"), "cargo", "cargo", &args).debug("codelldb");
if dir != root {
run.extras.module = Some(ide_core::ipc_path::to_ipc(&relative(root, dir)));
}
out.push(run);
out.push(config(id, format!("cargo run {bin}"), "cargo", "cargo", &args).debug("codelldb"));
}
}
if packages.is_empty() && !is_workspace {
return;
}
if is_workspace {
for (pkg, dir, _) in &packages {
let mut test = config(
format!("cargo:test:{pkg}"),
format!("cargo test {pkg}"),
"cargo",
"cargo",
&["test", "-p", pkg],
)
.test()
.debug("codelldb");
test.extras.module = Some(ide_core::ipc_path::to_ipc(&relative(root, dir)));
out.push(test);
}
}
let ws_flag: &[&str] = if is_workspace { &["--workspace"] } else { &[] };
let test_args: Vec<&str> = ["test"].iter().chain(ws_flag).copied().collect();
let build_args: Vec<&str> = ["build"].iter().chain(ws_flag).copied().collect();
@@ -515,8 +410,32 @@ fn applies_application_plugin(text: &str) -> bool {
})
}
/// How deep a build is looked for when the project root has none (a folder holding
/// several repositories: `backend/pom.xml`, `apps/server/settings.gradle`).
const NESTED_BUILD_DEPTH: usize = 3;
/// The builds marked by any of `markers`: the root itself, else the shallowest marked
/// folder of each branch, up to [`NESTED_BUILD_DEPTH`] levels down.
fn build_dirs(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
ide_core::project_roots::discover(root, markers)
let marked = |d: &Path| markers.iter().any(|m| d.join(m).is_file());
if marked(root) {
return vec![root.to_path_buf()];
}
let mut out = Vec::new();
let mut level = vec![root.to_path_buf()];
for _ in 0..NESTED_BUILD_DEPTH {
let mut next = Vec::new();
for sub in level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src") && !d.ends_with("out")) {
if marked(&sub) {
out.push(sub);
} else {
next.push(sub);
}
}
level = next;
}
out.sort();
out
}
/// Ids, names and working directory of the configurations of a build nested in
@@ -627,7 +546,7 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
let mut budget = SPRING_SCAN_FILES;
let mut modules = vec![build.to_path_buf()];
let mut level = vec![build.to_path_buf()];
for _ in 0..ide_core::project_roots::SEARCH_DEPTH {
for _ in 0..NESTED_BUILD_DEPTH {
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
modules.extend(level.iter().cloned());
}
@@ -789,11 +708,16 @@ fn detect_go(root: &Path, out: &mut Vec<RunConfig>) {
}
return;
}
for dir in ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("go.mod").is_file()
}) {
let rel = relative(root, &dir);
detect_go_module(&dir, (!rel.as_os_str().is_empty()).then_some(rel), out);
if root.join("go.mod").is_file() {
detect_go_module(root, None, out);
return;
}
// A polyglot repository: Go modules one level down (`api/go.mod`).
for dir in subdirs(root) {
if dir.join("go.mod").is_file() {
let rel = relative(root, &dir);
detect_go_module(&dir, Some(rel), out);
}
}
}
@@ -1145,18 +1069,14 @@ fn uses_rspec(root: &Path) -> bool {
|| read(&root.join("Gemfile")).is_some_and(|g| g.contains("rspec"))
}
fn ruby_project(root: &Path) -> bool {
fn detect_ruby(root: &Path, out: &mut Vec<RunConfig>) {
let markers = ["Gemfile", "Rakefile", "rakefile", "Rakefile.rb", ".ruby-version", "config.ru"];
let gemspec = fs::read_dir(root)
.into_iter()
.flatten()
.flatten()
.any(|e| e.path().extension().is_some_and(|x| x == "gemspec"));
gemspec || markers.iter().any(|m| root.join(m).is_file())
}
fn detect_ruby(root: &Path, out: &mut Vec<RunConfig>) {
if !ruby_project(root) {
if !gemspec && !markers.iter().any(|m| root.join(m).is_file()) {
return;
}
if root.join("bin/rails").is_file() {
@@ -1297,10 +1217,8 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
/// Godot projects (`project.godot`) at the root or one level down: "Godot Project"
/// runs the main scene (`godot --path .`), debuggable through the editor's adapter.
fn detect_godot(root: &Path, out: &mut Vec<RunConfig>) {
let dirs = ide_core::project_roots::discover_matching(root, ide_core::project_roots::SEARCH_DEPTH, false, |dir| {
dir.join("project.godot").is_file()
});
for dir in dirs {
let dirs = std::iter::once(root.to_path_buf()).chain(subdirs(root));
for dir in dirs.filter(|d| d.join("project.godot").is_file()) {
let rel = relative(root, &dir);
let (id, name, cwd) = if rel.as_os_str().is_empty() {
("godot:project".to_owned(), "Godot Project".to_owned(), None)
+1 -3
Переглянути файл
@@ -14,7 +14,6 @@ mod process;
pub mod python_path;
pub mod ruby_preload;
pub mod ruby_reporter;
pub mod scope;
pub mod tomcat;
mod utf8;
pub mod which;
@@ -77,8 +76,7 @@ fn is_true(b: &bool) -> bool {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RunExtras {
/// Owning module, independent of the working directory; also supplies a JVM application's classpath.
/// Empty means the project root.
/// Module supplying a JVM application's classpath; empty means the project root.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub module: Option<String>,
-125
Переглянути файл
@@ -1,125 +0,0 @@
//! A configuration's module and relative paths move together when projects are nested.
use crate::RunConfig;
use ide_core::{ipc_path::to_ipc, project_roots};
use std::path::{Path, PathBuf};
pub fn owner(root: &Path, config: &RunConfig) -> PathBuf {
if matches!(config.kind.as_str(), "dotnet" | "dotnet-test")
&& let Some(project) = config.extras.params.get("project").filter(|p| !p.is_empty())
{
return project_roots::resolve(root, Path::new(project)).parent().unwrap_or(root).to_path_buf();
}
let module = (config.kind == "go")
.then(|| config.extras.params.get("module"))
.flatten()
.map(String::as_str)
.or(config.extras.module.as_deref())
.map(Path::new)
.or(config.cwd.as_deref())
.unwrap_or(Path::new(""));
project_roots::resolve(root, module)
}
pub fn rebase(config: &mut RunConfig, from: &Path, relative_to: Option<&Path>) {
let path = |value: &str| {
let absolute = project_roots::resolve(from, Path::new(value));
to_ipc(&relative_to.map_or(absolute.clone(), |root| project_roots::relative(root, &absolute)))
};
let cwd = config.cwd.as_deref().unwrap_or(Path::new("")).to_path_buf();
config.cwd = Some(path(&to_ipc(&cwd)).into());
if config.extras.module.is_some() || !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = Some(path(config.extras.module.as_deref().unwrap_or("")));
}
if config.kind == "go" && config.extras.params.contains_key("goKind") {
config.extras.params.entry("module".into()).or_default();
}
for file in &mut config.extras.env_files {
*file = path(file);
}
for file in [&mut config.extras.stdin_file, &mut config.extras.output_file].into_iter().flatten() {
*file = path(file);
}
let keys: &[&str] = match config.kind.as_str() {
"go" => &["module", "outputDir"],
"dotnet" | "dotnet-test" => &["project", "targetPath"],
_ => &[],
};
for key in keys {
if let Some(value) = config.extras.params.get_mut(*key)
&& (*key == "module" || !value.is_empty())
{
*value = path(value);
}
}
if !matches!(config.kind.as_str(), "shell" | "compound") && Path::new(&config.command).components().count() > 1 {
// Executables are relative to the old cwd, unlike env/input/output files.
let cwd = project_roots::resolve(from, &cwd);
config.command = to_ipc(&project_roots::resolve(&cwd, Path::new(&config.command)));
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn default_go_module_moves_with_member_but_unknown_jvm_module_stays_inferred() {
let temp = tempfile::tempdir().unwrap();
for (kind, params) in
[("go", serde_json::json!({"goKind":"build", "target":"."})), ("application", serde_json::json!({}))]
{
let mut config: RunConfig = serde_json::from_value(serde_json::json!({
"id":"run", "name":"run", "kind":kind, "command":"tool", "args":[], "cwd":null,
"env":{}, "detected":false, "isTest":false, "debugAdapter":null, "params":params
}))
.unwrap();
rebase(&mut config, temp.path(), None);
if kind == "go" {
assert_eq!(config.extras.params["module"], to_ipc(temp.path()));
} else {
assert_eq!(config.extras.module, None);
}
}
}
#[test]
fn workspace_members_rebase_every_typed_root_without_changing_targets() {
let temp = tempfile::tempdir().unwrap();
let member = temp.path().join("member with spaces");
for (kind, params) in [
("application", BTreeMap::<String, String>::new()),
(
"go",
BTreeMap::from([
("module".into(), "api".into()),
("target".into(), "./cmd/server".into()),
("outputDir".into(), "bin".into()),
]),
),
("dotnet", BTreeMap::from([("project".into(), "src/App.csproj".into())])),
] {
let mut config: RunConfig = serde_json::from_value(serde_json::json!({
"id":"run", "name":"run", "kind":kind, "command":"tool", "args":["unchanged"], "cwd":null,
"env":{}, "detected":true, "isTest":false, "debugAdapter":null,
"module":"app", "params":params, "envFiles":[".env"], "stdinFile":"input.txt", "outputFile":"out/result.txt"
})).unwrap();
rebase(&mut config, &member, None);
assert_eq!(config.cwd.as_deref(), Some(member.as_path()));
assert_eq!(config.extras.module.as_deref(), Some(to_ipc(&member.join("app")).as_str()));
assert_eq!(config.extras.env_files, [to_ipc(&member.join(".env"))]);
assert_eq!(config.extras.stdin_file, Some(to_ipc(&member.join("input.txt"))));
assert_eq!(config.extras.output_file, Some(to_ipc(&member.join("out/result.txt"))));
assert_eq!(config.args, ["unchanged"]);
if kind == "go" {
assert_eq!(config.extras.params["module"], to_ipc(&member.join("api")));
assert_eq!(config.extras.params["outputDir"], to_ipc(&member.join("bin")));
assert_eq!(config.extras.params["target"], "./cmd/server");
}
if kind == "dotnet" {
assert_eq!(config.extras.params["project"], to_ipc(&member.join("src/App.csproj")));
}
}
}
}
+5 -125
Переглянути файл
@@ -131,25 +131,9 @@ fn cargo_workspace() {
("cli/src/main.rs", ""),
]);
let c = detect(dir.path());
assert_eq!(
ids(&c),
[
"cargo:run:openidea-cli",
"cargo:test:core",
"cargo:test:openidea-cli",
"cargo:test",
"cargo:build",
"cargo:run:skip:crates/skip",
"cargo:test:crates/skip",
"cargo:build:crates/skip"
]
);
assert_eq!(ids(&c), ["cargo:run:openidea-cli", "cargo:test", "cargo:build"]);
assert_eq!(cmdline(&c[0]), "cargo run -p openidea-cli --bin openidea-cli");
assert_eq!(cmdline(find(&c, "cargo:test")), "cargo test --workspace");
let test = find(&c, "cargo:test:core");
assert_eq!(test.extras.module.as_deref(), Some("crates/core"));
assert_eq!(cmdline(test), "cargo test -p core");
assert_eq!(find(&c, "cargo:run:skip:crates/skip").cwd.as_deref(), Some(Path::new("crates/skip")));
}
#[test]
@@ -316,22 +300,7 @@ fn nested_builds_of_every_kind_and_depth() {
assert_eq!((billing.cwd.as_deref(), billing.extras.module.as_deref()), (None, Some("billing")));
let builds: Vec<&str> =
ids(&c).into_iter().filter(|id| id.starts_with("maven:package") || id.starts_with("gradle:build")).collect();
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing", "maven:package:tool/src"]);
let model = ide_build::load(dir.path(), &dir.path().join("cache"), None);
for config in c.iter().filter(|c| c.kind == "gradle") {
let cwd = config.cwd.as_deref().unwrap();
assert!(model.gradle.iter().any(|g| Path::new(&g.dir) == cwd), "{} has no build model", config.id);
}
let plan = ide_build::compile::plan(
dir.path(),
&model,
ide_build::compile::BuildKind::Build,
Some(&dir.path().join("services/api/app/src/main/kotlin/com/acme/Api.kt")),
None,
)
.unwrap();
assert_eq!(plan.steps[0].cwd, dir.path().join("services/api"));
assert_eq!(plan.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing"]);
}
#[test]
@@ -393,49 +362,6 @@ fn go_projects() {
assert_eq!(ids(&detect(dir.path())), ["go:test"]);
}
#[test]
fn nested_go_modules_keep_their_working_directories() {
let dir = project(&[
("Cargo.toml", "[package]\nname = 'workspace'\n"),
("fixtures/go-app/go.mod", "module example.com/openidea/notes\n"),
("fixtures/go-app/cmd/server/main.go", "package main\nfunc main() {}\n"),
("services/backend/api/go.mod", "module example.com/api\n"),
("services/backend/api/main.go", "package main\nfunc main() {}\n"),
("fixtures/go-app/nested/go.mod", "module ignored\n"),
("vendor/ignored/go.mod", "module ignored\n"),
("node_modules/ignored/go.mod", "module ignored\n"),
("target/ignored/go.mod", "module ignored\n"),
("build/ignored/go.mod", "module ignored\n"),
("dist/ignored/go.mod", "module ignored\n"),
(".hidden/ignored/go.mod", "module ignored\n"),
]);
let configs = detect(dir.path());
let go: Vec<_> = configs.iter().filter(|c| c.kind == "go").map(|c| c.id.as_str()).collect();
assert_eq!(
go,
[
"go:run:server:fixtures/go-app",
"go:test:fixtures/go-app",
"go:test:fixtures/go-app/nested",
"go:run:services/backend/api",
"go:test:services/backend/api",
]
);
let run = find(&configs, "go:run:server:fixtures/go-app");
assert_eq!(cmdline(run), "go run ./cmd/server");
assert_eq!(run.cwd.as_deref(), Some(Path::new("fixtures/go-app")));
let test = find(&configs, "go:test:services/backend/api");
assert_eq!(test.cwd.as_deref(), Some(Path::new("services/backend/api")));
}
#[cfg(unix)]
#[test]
fn nested_go_discovery_does_not_follow_symlinks() {
let dir = project(&[("real/go.mod", "module real\n")]);
std::os::unix::fs::symlink(dir.path().join("real"), dir.path().join("alias")).unwrap();
assert_eq!(ids(&detect(dir.path())), ["go:test:real"]);
}
#[test]
fn python_projects() {
let dir = project(&[
@@ -619,7 +545,7 @@ fn nested_packages_in_polyglot_repo() {
}
#[test]
fn independent_packages_remain_visible_under_a_root_package() {
fn root_package_disables_nested_scan() {
let dir = project(&[
("package.json", r#"{"scripts":{"build":"tsc"}}"#),
("tools/package.json", r#"{"scripts":{"gen":"x"}}"#),
@@ -627,9 +553,9 @@ fn independent_packages_remain_visible_under_a_root_package() {
("svc/go.mod", "module y\n"),
]);
let c = detect(dir.path());
assert!(ids(&c).contains(&"npm:tools:gen"));
assert!(!ids(&c).contains(&"npm:tools:gen"));
assert!(ids(&c).contains(&"go:test"));
assert!(ids(&c).contains(&"go:test:svc"));
assert!(!ids(&c).contains(&"go:test:svc"));
}
#[test]
@@ -921,49 +847,3 @@ fn ruby_without_bundler_runs_bare_tools() {
assert_eq!(cmdline(&c[0]), "rake test");
assert!(detect(project(&[("a.rb", "puts 1\n")]).path()).is_empty());
}
#[test]
fn all_builtin_families_find_independent_nested_projects_and_keep_owners() {
let cases = [
("package.json", r#"{"scripts":{"test":"vitest"}}"#, "npm"),
("deno.json", r#"{"tasks":{"test":"deno test"}}"#, "deno"),
("Cargo.toml", "[package]\nname='demo'\nversion='0.1.0'\n[workspace]", "cargo"),
("go.mod", "module demo", "go"),
("pom.xml", "<project/>", "maven"),
("build.gradle.kts", "plugins { application }", "gradle"),
("pyproject.toml", "[tool.pytest.ini_options]", "pytest"),
("phpunit.xml", "<phpunit/>", "phpunit"),
("Rakefile.rb", "task :test do\nend", "rake"),
("CMakeLists.txt", "project(demo)", "cmake"),
("Makefile", "test:\n\techo ok", "make"),
("justfile", "test:\n echo ok", "just"),
("project.godot", "[application]\nrun/main_scene=\"res://main.tscn\"", "godot"),
];
for (marker, text, kind) in cases {
let dir = project(&[
("package.json", r#"{"scripts":{"build":"echo root"}}"#),
(&format!("packages/apps/demo/{marker}"), text),
]);
let configs = detect(dir.path());
let found: Vec<_> = configs
.iter()
.filter(|c| c.kind == kind && c.cwd.as_deref() == Some(Path::new("packages/apps/demo")))
.collect();
assert!(!found.is_empty(), "{kind}: {configs:?}");
for c in found {
// JVM and Go configs already identify ownership through cwd / their typed model.
if !matches!(kind, "gradle" | "maven" | "go" | "godot") {
assert_eq!(c.extras.module.as_deref(), Some("packages/apps/demo"));
}
}
}
}
#[test]
fn cmake_subdirectories_are_not_independent_builds() {
let dir = project(&[
("CMakeLists.txt", "project(demo)\nadd_subdirectory(lib)"),
("lib/CMakeLists.txt", "add_library(lib lib.cpp)"),
]);
assert!(detect(dir.path()).iter().filter(|c| c.kind == "cmake").all(|c| c.cwd.is_none()));
}
-24
Переглянути файл
@@ -529,30 +529,6 @@ fn revoking_one_project_stops_only_its_runs() {
h.pm.stop(theirs.id).unwrap();
}
/// Quitting the app kills what every project's runs started, forked children included (#1691).
#[test]
fn kill_all_stops_every_projects_process_trees() {
let h = harness();
let other = tempfile::tempdir().unwrap();
let (mine, chunks) = start(&h, &cfg("mine", "/bin/sh", &["-c", "sleep 30 & echo $!; wait"]));
let grandchild: i32 = wait_for(&chunks, "\n").trim().parse().expect("pid");
let theirs =
h.pm.start(
other.path(),
&cfg("theirs", "/bin/sh", &["-c", "sleep 30"]),
&StartOptions::default(),
h.sink.clone(),
Box::new(|_| {}),
)
.unwrap();
h.pm.kill_all();
let deadline = Instant::now() + Duration::from_secs(8);
while alive(grandchild) || h.pm.list().iter().any(|r| (r.id == mine || r.id == theirs.id) && r.running) {
assert!(Instant::now() < deadline, "a run survived kill_all");
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
#[ignore = "requires CMake, CTest and a C++ compiler"]
fn cmake_configure_discovers_builds_and_runs_a_multifile_target() {
+15 -221
Переглянути файл
@@ -11,7 +11,6 @@ use ide_core::{IdeError, IdeResult};
use ide_language::{LanguageConfig, LanguageServerConfig};
use ide_run::RunConfig;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
@@ -71,18 +70,6 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_python(root))
}
/// An explicit project interpreter wins; otherwise use the closest virtualenv to the file.
pub fn python_interpreter_near(root: &Path, near: Option<&Path>, s: &Settings) -> Option<PathBuf> {
if let Some(python) = setting_path(root, &s.languages.python.interpreter) {
return Some(python);
}
let near = near.filter(|dir| dir.starts_with(root)).unwrap_or(root);
near.ancestors()
.take_while(|dir| dir.starts_with(root))
.find_map(project_venv_python)
.or_else(|| pinned::pinned_python(near))
}
/// The project Ruby: the configured one, else the `.ruby-version` / mise / asdf
/// install, else `ruby` on PATH.
pub fn ruby_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
@@ -258,103 +245,6 @@ fn resolve_gradle_command(root: &Path, build_dir: &Path, s: &Settings, use_wrapp
.unwrap_or_else(|| name.into())
}
fn gradle_run_jdk<'a>(
release: Option<u32>,
configured: Option<&'a crate::java::Jdk>,
installed: &'a [crate::java::Jdk],
gradle: Option<(u32, u32)>,
) -> Option<&'a crate::java::Jdk> {
configured.or_else(|| {
let release = release?;
// An unknown Gradle version cannot narrow the choice: the release alone decides.
let Some(gradle) = gradle else { return crate::java::pick_jdk(installed, Some(release)) };
let compatible: Vec<_> = installed.iter().filter(|jdk| gradle_supports_java(gradle, jdk.major)).collect();
compatible
.iter()
.copied()
.find(|jdk| jdk.major == release)
.or_else(|| compatible.iter().copied().filter(|jdk| jdk.major > release).min_by_key(|jdk| jdk.major))
.or_else(|| compatible.iter().copied().max_by_key(|jdk| jdk.major))
})
}
/// Default environment shared by Gradle model builds and Run configurations.
pub fn gradle_build_env(
root: &Path,
build_dir: &Path,
command: &str,
settings: &Settings,
release: Option<u32>,
) -> std::collections::BTreeMap<String, String> {
let configured = project_jdk(root, settings);
let installed = crate::java::installed_jdks();
let jdk = gradle_run_jdk(
release.or_else(|| crate::java::project_java_version(build_dir)),
configured.as_ref(),
&installed,
gradle_distribution_version(build_dir, command),
);
let env = jdk
.map(|jdk| std::collections::BTreeMap::from([("JAVA_HOME".into(), jdk.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
gradle_env(root, settings, env)
}
fn gradle_supports_java(gradle: (u32, u32), java: u32) -> bool {
// https://docs.gradle.org/current/userguide/compatibility.html#java_runtime
let minimum = match java {
8 => (2, 0),
9 => (4, 3),
10 => (4, 7),
11 => (5, 0),
12 => (5, 4),
13 => (6, 0),
14 => (6, 3),
15 => (6, 7),
16 => (7, 0),
17 => (7, 3),
18 => (7, 5),
19 => (7, 6),
20 => (8, 3),
21 => (8, 5),
22 => (8, 8),
23 => (8, 10),
24 => (8, 14),
25 => (9, 1),
26 => (9, 4),
27 => (9, 8),
_ => return false,
};
gradle >= minimum && (java >= 17 || gradle < (9, 0))
}
fn gradle_distribution_version(build_dir: &Path, command: &str) -> Option<(u32, u32)> {
let version = |text: &str| {
let mut parts = text.split('.');
Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
};
if Path::new(command).file_stem().is_some_and(|name| name == "gradlew") {
let properties = std::fs::read_to_string(build_dir.join("gradle/wrapper/gradle-wrapper.properties")).ok()?;
let url = properties.lines().find_map(|line| line.trim().strip_prefix("distributionUrl="))?;
return version(url.rsplit_once("gradle-")?.1.split('-').next()?);
}
let path = Path::new(command);
let path = if path.is_absolute() { path.to_path_buf() } else { crate::exec::which(command)? };
let path = dunce::canonicalize(path).ok()?;
let home = path.parent()?.parent()?;
for lib in [home.join("lib"), home.join("libexec/lib")] {
let Ok(entries) = std::fs::read_dir(lib) else { continue };
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if let Some(v) = name.strip_prefix("gradle-launcher-").and_then(|name| name.strip_suffix(".jar")) {
return version(v);
}
}
}
None
}
/// Gradle JVM overrides Project JDK; model callers supply the module's fallback environment.
pub fn gradle_env(
root: &Path,
@@ -798,22 +688,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
);
}
// m2e resolves and downloads into `maven.repo.local`; without it the
// embedded Maven falls back to ~/.m2 even when the IDE's own `mvn`
// runs honor the configured local repository. A `-Dmaven.repo.local`
// the user put in their own jdtls VM options wins.
if let Some(repo) = maven_local_repository(root, s) {
let arg = format!("-Dmaven.repo.local={}", repo.to_string_lossy());
let taken = cfg.args.iter().enumerate().any(|(i, a)| {
let value = a
.strip_prefix("--jvm-arg=")
.or_else(|| (i > 0 && cfg.args[i - 1] == "--jvm-arg").then_some(a.as_str()));
value.is_some_and(|a| a.split('=').next() == Some("-Dmaven.repo.local"))
});
if !taken {
cfg.args.push(format!("--jvm-arg={arg}"));
}
}
}
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
@@ -1074,38 +948,19 @@ fn add_maven_options(args: &mut Vec<String>, options: &[String]) {
/// (and Maven the configured home and options).
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
let explicit_python = setting_path(root, &s.languages.python.interpreter);
let python = python_interpreter(root, s);
let pm = non_empty(&s.languages.node.package_manager);
let node = node_dir(root, s);
let php = setting_path(root, &s.languages.php.interpreter);
let rust = rust_bin(root, s);
let go = goroot(root, s);
let gopath = setting_path(root, &s.languages.go.gopath);
let jdk = project_jdk(root, s);
let mvn = maven_command(root, s);
let mvn_options = maven_options(root, s);
// Module-local toolchains, looked up once per owning module and only for the kinds using them.
let mut toolchains: HashMap<(&'static str, PathBuf), Option<PathBuf>> = HashMap::new();
let mut toolchain = |tool: &'static str, owner: &Path| {
toolchains
.entry((tool, owner.to_path_buf()))
.or_insert_with(|| {
// A module outside the project (an external linked build) keeps the project's choices.
let near = if owner.starts_with(root) { owner } else { root };
match tool {
"python" => python_interpreter_near(root, Some(near), s),
"node" if non_empty(&s.languages.node.interpreter).is_none() => {
node_dir(near, s).or_else(|| node_dir(root, s))
}
"node" => node_dir(root, s),
"go" if non_empty(&s.languages.go.goroot).is_none() => goroot(near, s).or_else(|| goroot(root, s)),
"go" => goroot(root, s),
_ => setting_path(root, &s.languages.ruby.interpreter).or_else(|| ruby_interpreter(near, s)),
}
})
.clone()
};
let ruby = ruby_interpreter(root, s);
for c in configs.iter_mut() {
let owner = ide_run::scope::owner(root, c);
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
@@ -1129,7 +984,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.args = ["-m".to_owned(), "pytest".to_owned()].into_iter().chain(rest).collect();
}
}
let python = toolchain("python", &owner);
if let Some(venv) = python.as_deref().and_then(venv_of)
&& !c.env.contains_key("VIRTUAL_ENV")
{
@@ -1137,9 +991,8 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
path_dirs.push(venv.join(bin_dir()));
}
}
"npm" | "node" | "deno" | "bun" => {
"npm" => {
if let Some(pm) = pm
&& c.kind == "npm"
&& c.detected
&& matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun")
{
@@ -1147,9 +1000,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
}
// The configuration's own Node interpreter, else the project's.
let own = c.extras.params.get("nodeInterpreter").and_then(|p| setting_path(root, p));
if let Some(dir) =
own.and_then(|p| p.parent().map(Path::to_path_buf)).or_else(|| toolchain("node", &owner))
{
if let Some(dir) = own.and_then(|p| p.parent().map(Path::to_path_buf)).or_else(|| node.clone()) {
path_dirs.push(dir);
}
}
@@ -1176,7 +1027,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
for (key, value) in crate::go::module_environment(root, &s.languages.go.modules) {
c.env.entry(key).or_insert(value);
}
if let Some(goroot) = &toolchain("go", &owner) {
if let Some(goroot) = &go {
let bin = goroot.join("bin");
if c.command == "go" && bin.join(exe("go")).is_file() {
c.command = bin.join(exe("go")).to_string_lossy().into_owned();
@@ -1193,12 +1044,18 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
if matches!(c.command.as_str(), "gradle" | "gradle.bat") {
c.command = resolve_gradle_command(root, &build_dir, s, false).to_string_lossy().into_owned();
}
for (key, value) in gradle_build_env(root, &build_dir, &c.command, s, None) {
let defaults = jdk
.as_ref()
.map(|j| {
std::collections::BTreeMap::from([("JAVA_HOME".into(), j.home.to_string_lossy().into_owned())])
})
.unwrap_or_default();
for (key, value) in gradle_env(root, s, defaults) {
c.env.entry(key).or_insert(value);
}
}
"ruby" | "rake" | "rspec" => {
if let Some(ruby) = &toolchain("ruby", &owner)
if let Some(ruby) = &ruby
&& let Some(bin) = crate::ruby::bin_dir_of(ruby)
{
// `ruby`, `bundle`, `rake`, `rspec` of the chosen interpreter when installed
@@ -1445,69 +1302,6 @@ mod java_compiler_tests {
}
}
#[cfg(test)]
mod gradle_runtime_tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn gradle_runs_use_the_builds_toolchain_without_overriding_user_choices() {
let temp = tempfile::tempdir().unwrap();
let installed =
[25, 21, 17, 11, 8].map(|major| crate::java::Jdk { major, home: temp.path().join(format!("jdk{major}")) });
for (name, script, expected) in [
("kotlin", "kotlin { jvmToolchain(21) }", Some(21)),
("java", "java { toolchain { languageVersion = JavaLanguageVersion.of(17) } }", Some(17)),
("unspecified", "plugins { id 'java' }", None),
] {
let dir = temp.path().join(name);
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("build.gradle.kts"), script).unwrap();
let picked = gradle_run_jdk(crate::java::project_java_version(&dir), None, &installed, Some((9, 0)));
assert_eq!(picked.map(|jdk| jdk.major), expected);
assert_eq!(gradle_run_jdk(expected, Some(&installed[0]), &installed, Some((9, 0))), Some(&installed[0]));
let mut settings = Settings::default();
settings.languages.java.gradle.jvm = "custom-gradle-jdk".into();
let env = gradle_env(temp.path(), &settings, BTreeMap::from([("JAVA_HOME".into(), "/fallback".into())]));
assert_eq!(env["JAVA_HOME"], temp.path().join("custom-gradle-jdk").to_string_lossy());
}
let dir = temp.path().join("kotlin");
for (gradle, target, expected) in
[((9, 0), 8, 17), ((8, 4), 21, 17), ((8, 5), 21, 21), ((7, 2), 21, 11), ((9, 0), 25, 21), ((9, 1), 25, 25)]
{
std::fs::write(dir.join("build.gradle.kts"), format!("kotlin {{ jvmToolchain({target}) }}")).unwrap();
assert_eq!(gradle_run_jdk(Some(target), None, &installed, Some(gradle)).unwrap().major, expected);
}
assert_eq!(gradle_run_jdk(Some(21), None, &installed, None).unwrap().major, 21);
assert_eq!(gradle_run_jdk(Some(19), None, &installed, None).unwrap().major, 21);
assert!(gradle_run_jdk(None, None, &installed, None).is_none());
}
#[test]
fn reads_wrapper_and_local_gradle_versions_without_running_them() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("gradle/wrapper")).unwrap();
std::fs::write(
root.join("gradle/wrapper/gradle-wrapper.properties"),
"distributionUrl=https\\://services.gradle.org/distributions/gradle-8.4.0-bin.zip\n",
)
.unwrap();
for command in ["./gradlew", "gradlew.bat"] {
assert_eq!(gradle_distribution_version(root, command), Some((8, 4)));
}
for layout in ["lib", "libexec/lib"] {
let home = root.join(layout.replace('/', "-"));
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::create_dir_all(home.join(layout)).unwrap();
let command = home.join("bin/gradle");
std::fs::write(&command, "").unwrap();
std::fs::write(home.join(layout).join("gradle-launcher-9.0.0.jar"), "").unwrap();
assert_eq!(gradle_distribution_version(root, &command.to_string_lossy()), Some((9, 0)));
}
}
}
#[cfg(test)]
mod maven_linkage_tests {
use super::*;
+5 -15
Переглянути файл
@@ -540,12 +540,10 @@ pub fn project_java_version(module_dir: &Path) -> Option<u32> {
}
for name in ["build.gradle.kts", "build.gradle"] {
let Some(text) = read(name) else { continue };
for key in ["JavaLanguageVersion.of(", "jvmToolchain("] {
if let Some(i) = text.find(key) {
let rest = &text[i + key.len()..];
if let Some(v) = parse_java_version(rest.split(')').next().unwrap_or_default()) {
return Some(v);
}
if let Some(i) = text.find("JavaLanguageVersion.of(") {
let rest = &text[i + "JavaLanguageVersion.of(".len()..];
if let Some(v) = parse_java_version(rest.split(')').next().unwrap_or_default()) {
return Some(v);
}
}
for key in ["sourceCompatibility", "targetCompatibility"] {
@@ -1140,14 +1138,6 @@ mod tests {
assert_eq!(project_java_version(dir), Some(11));
std::fs::write(dir.join("build.gradle.kts"), "sourceCompatibility = '1.8'").unwrap();
assert_eq!(project_java_version(dir), Some(8));
for (script, version) in [
("kotlin { jvmToolchain(21) }", Some(21)),
("kotlin { jvmToolchain(17) }", Some(17)),
("kotlin { jvmToolchain(projectVersion) }", None),
] {
std::fs::write(dir.join("build.gradle.kts"), script).unwrap();
assert_eq!(project_java_version(dir), version);
}
}
}
@@ -1196,7 +1186,7 @@ mod kotlin_bridge_bundle_tests {
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
let extension = data_dir.join("java-usages-1.7.0.jar");
let extension = data_dir.join("java-usages-1.6.0.jar");
let bytes = include_bytes!("../../../java/java-usages/openidea-java-usages.jar");
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
clean_usages_bundles(data_dir, &extension);
-57
Переглянути файл
@@ -115,26 +115,6 @@ fn jdtls_vm_args() {
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok.jar"]);
}
#[test]
fn jdtls_honors_the_configured_maven_local_repository() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("m2-repo");
let mut s = Settings::default();
s.languages.java.maven.local_repository = repo.to_string_lossy().into_owned();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.args, [format!("--jvm-arg=-Dmaven.repo.local={}", repo.to_string_lossy())]);
// A `-Dmaven.repo.local` the user put in their own jdtls VM options wins.
s.languages.java.jdtls_vm_args = "-Xmx2g -Dmaven.repo.local=/user/repo".into();
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-Dmaven.repo.local=/user/repo"]);
// Unset: jdtls keeps m2e's own default (no arg at all).
let mut cfg = server("jdtls");
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
assert!(cfg.args.iter().all(|a| !a.contains("maven.repo.local")));
}
#[test]
fn rust_analyzer_check_command_and_toolchain() {
if cfg!(windows) {
@@ -1635,40 +1615,3 @@ fn saving_a_loaded_run_configuration_drops_what_settings_derived() {
assert_eq!(next[1].args, ["-Dmaven.repo.local=/m3/repo", "-s", "/mine.xml", "test"]);
}
}
#[test]
fn nested_python_configs_get_their_own_virtualenv_but_explicit_settings_stay_project_relative() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let outer = fake_venv(root, ".venv");
let nested = fake_venv(&root.join("apps").join("python"), ".venv");
let mut config = run("python", "python3", &["main.py"]);
config.extras.module = Some("apps/python".into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &Settings::default());
assert_eq!(config.env["VIRTUAL_ENV"], nested.parent().unwrap().parent().unwrap().to_string_lossy());
// A workspace member without its own virtualenv uses the one at the project root (uv workspaces).
let mut member = run("pytest", "python3", &["-m", "pytest"]);
member.extras.module = Some("packages/lib".into());
apply_to_run_configs(std::slice::from_mut(&mut member), root, &Settings::default());
assert_eq!(member.env["VIRTUAL_ENV"], outer.parent().unwrap().parent().unwrap().to_string_lossy());
let mut settings = Settings::default();
settings.languages.python.interpreter = "custom/bin/python".into();
let mut config = run("python", "python3", &["main.py"]);
config.extras.module = Some("apps/python".into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, root.join("custom/bin/python").to_string_lossy());
}
#[test]
fn file_runtime_uses_nearest_virtualenv_and_explicit_project_settings_win() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let outer = fake_venv(root, ".venv");
let inner = fake_venv(&root.join("apps/api"), ".venv");
let near = root.join("apps/api/src/package");
let mut settings = Settings::default();
assert_eq!(crate::apply::python_interpreter_near(root, Some(&near), &settings), Some(inner));
assert_eq!(crate::apply::python_interpreter_near(root, Some(&root.join("apps/other")), &settings), Some(outer));
settings.languages.python.interpreter = "selected/python".into();
assert_eq!(crate::apply::python_interpreter_near(root, Some(&near), &settings), Some(root.join("selected/python")));
}
+1 -41
Переглянути файл
@@ -361,48 +361,14 @@ pub(crate) fn run_cancellable(root: &Path, args: &[&str], cancel: &CancellationT
/// Cancellable capture preserving exit codes for commands with documented non-error states.
pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
run_cancellable_raw_stdin(root, args, None, cancel)
}
/// Like `run_cancellable`, feeding `stdin` to git. Revisions and paths passed through
/// `--stdin` are not bound by the command-line length limit (Windows: ~32K characters).
pub(crate) fn run_cancellable_stdin(
root: &Path,
args: &[&str],
stdin: &[u8],
cancel: &CancellationToken,
) -> IdeResult<Output> {
let out = run_cancellable_raw_stdin(root, args, Some(stdin), cancel)?;
if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) }
}
fn run_cancellable_raw_stdin(
root: &Path,
args: &[&str],
stdin: Option<&[u8]>,
cancel: &CancellationToken,
) -> IdeResult<Output> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = command(root)?;
cmd.args(args)
.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped());
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
own_group(&mut cmd);
let mut session = CommandSession::start(&mut cmd);
let mut child = cmd.spawn().map_err(spawn_error)?;
let writer = match (stdin, child.stdin.take()) {
(Some(data), Some(mut pipe)) => {
let data = data.to_vec();
Some(std::thread::spawn(move || {
// A broken pipe just means git stopped reading early; its exit status tells the story.
let _ = pipe.write_all(&data);
}))
}
_ => None,
};
let capture = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut bytes = Vec::new();
@@ -416,9 +382,6 @@ fn run_cancellable_raw_stdin(
terminate_tree(&mut child, KILL_GRACE);
let _ = stdout.join();
let _ = stderr.join();
if let Some(w) = writer {
let _ = w.join();
}
return Err(IdeError::cancelled());
}
if let Some(status) = child.try_wait()? {
@@ -426,9 +389,6 @@ fn run_cancellable_raw_stdin(
}
std::thread::sleep(Duration::from_millis(20));
};
if let Some(w) = writer {
let _ = w.join();
}
let join = |thread: std::thread::JoinHandle<std::io::Result<Vec<u8>>>| {
thread.join().map_err(|_| IdeError::internal("git output reader panicked"))?.map_err(IdeError::from)
};
+21 -55
Переглянути файл
@@ -80,18 +80,12 @@ fn git_select(
args.push("--first-parent".into());
}
args.extend(filter.iter().cloned());
// Past this many bytes of paths the command line risks Windows' ~32K limit.
let stdin = (paths.iter().map(|p| p.len() + 12).sum::<usize>() > 8 * 1024).then(|| paths_stdin(paths));
if stdin.is_some() {
args.push("--stdin".into());
}
args.push("--end-of-options".into());
args.extend(scope.split_whitespace().map(str::to_string));
if stdin.is_none() {
args.push("--".into());
args.extend(paths.iter().map(|p| format!(":(literal){p}")));
}
let output = run_log(r, args, stdin.as_deref(), cancel)?;
args.push("--".into());
args.extend(paths.iter().map(|p| format!(":(literal){p}")));
let output =
crate::cli::run_cancellable(r.root(), &args.iter().map(String::as_str).collect::<Vec<_>>(), cancel)?;
for line in output.stdout_str().lines() {
ids.insert(ObjectId::from_hex(line.as_bytes()).map_err(gx)?);
}
@@ -99,28 +93,6 @@ fn git_select(
Ok(ids)
}
/// Stdin for `git log --stdin` that limits the walk to `paths`, however many there are.
fn paths_stdin(paths: &[String]) -> String {
let mut text = String::from("--\n");
for p in paths {
text.push_str(&format!(":(literal){p}\n"));
}
text
}
fn run_log(
r: &Repo,
args: Vec<String>,
stdin: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<crate::cli::Output> {
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
match stdin {
Some(text) => crate::cli::run_cancellable_stdin(r.root(), &argv, text.as_bytes(), cancel),
None => crate::cli::run_cancellable(r.root(), &argv, cancel),
}
}
/// The commits of a file's history and the path it had in each. The commits that changed
/// the path, merges included (`--full-history --simplify-merges`); where it appears, a
/// rename from any parent continues the history under the old path from that parent.
@@ -142,27 +114,21 @@ fn file_history(
if !started.insert((revs.clone(), path.clone())) {
continue;
}
let mut opts: Vec<String> =
let mut args: Vec<String> =
["log", "--format=%x00%H", "--name-status", "-z", "--full-history", "--simplify-merges", "--no-follow"]
.map(String::from)
.into();
if first_parent {
opts.push("--first-parent".into());
args.push("--first-parent".into());
}
args.push("--end-of-options".into());
args.extend(revs);
let pathspec = ["--".to_string(), format!(":(literal){path}")];
// `excluded` can name a revision per created file, so it goes through stdin.
let run = |excluded: &[String]| -> IdeResult<Vec<(ObjectId, Option<char>)>> {
let mut args = opts.clone();
if !excluded.is_empty() {
args.push("--stdin".into());
}
args.push("--end-of-options".into());
args.extend(revs.iter().cloned());
args.extend(pathspec.iter().cloned());
let stdin = (!excluded.is_empty()).then(|| excluded.join("\n") + "\n");
Ok(parse_name_status_log(&run_log(r, args, stdin.as_deref(), cancel)?.stdout_str()))
let run = |args: &[String]| -> IdeResult<Vec<(ObjectId, Option<char>)>> {
let argv: Vec<&str> = args.iter().chain(&pathspec).map(String::as_str).collect();
Ok(parse_name_status_log(&crate::cli::run_cancellable(r.root(), &argv, cancel)?.stdout_str()))
};
let records = run(&[])?;
let records = run(&args)?;
// Where the file appears its history ends: what is behind that is another file of
// the same name (a rename continues the history below). The commits of the history
// are those not behind a creation; the statuses come from the full listing (with
@@ -171,8 +137,8 @@ fn file_history(
let kept: Option<HashSet<ObjectId>> = if created.is_empty() {
None
} else {
let excluded: Vec<String> = created.iter().map(|id| format!("^{id}^@")).collect();
Some(run(&excluded)?.into_iter().map(|(id, _)| id).collect())
args.extend(created.iter().map(|id| format!("^{id}^@")));
Some(run(&args)?.into_iter().map(|(id, _)| id).collect())
};
let mut created = Vec::new();
for (id, first_status) in records {
@@ -388,9 +354,7 @@ fn log_indexed(
let mut history_paths = HashMap::new();
let path_ids = if paths.is_empty() {
None
} else if q.follow && paths.len() == 1 && !r.root().join(&paths[0]).is_dir() {
// Following renames is for a file: a directory gains files all the time, and each
// creation would cut its history short.
} else if q.follow && paths.len() == 1 {
let (ids, at) = file_history(r, &scopes, &paths[0], q.first_parent, cancel)?;
history_paths = at;
Some(ids)
@@ -984,11 +948,13 @@ pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId,
let platform = repo.references().map_err(gx)?;
for reference in platform.all().map_err(gx)? {
let Ok(mut reference) = reference else { continue };
if reference.target().try_name().is_some() {
continue;
}
let full = reference.name().as_bstr().to_owned();
let label = if let Some(n) = full.strip_prefix(b"refs/heads/").or_else(|| full.strip_prefix(b"refs/remotes/")) {
let label = if let Some(n) = full.strip_prefix(b"refs/heads/") {
to_string(n.as_bstr())
} else if let Some(n) = full.strip_prefix(b"refs/remotes/") {
if n.ends_with(b"/HEAD") {
continue;
}
to_string(n.as_bstr())
} else if let Some(n) = full.strip_prefix(b"refs/tags/") {
format!("tag: {}", to_string(n.as_bstr()))
+1 -41
Переглянути файл
@@ -260,22 +260,6 @@ fn snapshot(file: &Path) -> IdeResult<Option<Snapshot>> {
}
}
/// `sync_all` failures that mean "this filesystem cannot fsync at all", not that
/// the data was lost: ENOTTY (`os error 25`, virtio-fs on macOS VMs answering
/// F_FULLFSYNC/fsync with "Inappropriate ioctl for device") and EINVAL (some
/// network filesystems). Mirrors `sync_error_is_tolerable` in ide-vfs atomic
/// writes; other errors keep failing the update.
fn sync_error_is_tolerable(e: &std::io::Error) -> bool {
if e.kind() == std::io::ErrorKind::InvalidInput {
return true;
}
// EINVAL is already covered by InvalidInput; ENOTTY has no ErrorKind of its own.
#[cfg(unix)]
return e.raw_os_error() == Some(25);
#[cfg(not(unix))]
false
}
fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
fs::create_dir_all(file.parent().unwrap())?;
@@ -332,16 +316,7 @@ fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
};
temp.as_file().set_permissions(permissions)?;
temp.write_all(&updated)?;
if let Err(e) = temp.as_file().sync_all() {
// Filesystems without fsync (virtio-fs on macOS VMs, some network mounts):
// the write itself already went through, so keep the updated ignore file
// instead of failing the whole update.
if sync_error_is_tolerable(&e) {
tracing::debug!("fsync unsupported for {}: {e}; continuing", file.display());
} else {
return Err(e.into());
}
}
temp.as_file().sync_all()?;
replace_if_unchanged(file, before, temp)
}
@@ -381,19 +356,4 @@ mod tests {
assert!(replace_if_unchanged(&file, before, temp).unwrap_err().message.contains("changed"));
assert_eq!(fs::read_to_string(file).unwrap(), "external writer\n");
}
#[test]
fn sync_errors_without_fsync_support_are_tolerable() {
// Some network filesystems report EINVAL for fsync.
assert!(sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::InvalidInput, "EINVAL")));
#[cfg(unix)]
{
// virtio-fs on macOS VMs answers fsync with "Inappropriate ioctl for device".
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(25)));
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(22)));
}
// Real write failures still fail the update.
assert!(!sync_error_is_tolerable(&std::io::Error::from_raw_os_error(28)));
assert!(!sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied")));
}
}
+2 -2
Переглянути файл
@@ -910,7 +910,7 @@ impl Repo {
let id = commit_id.to_string();
let contains = format!("--contains={id}");
let branches =
cli::run_cancellable(self.root(), &["branch", "-a", &contains, refs::DIRECT_BRANCH_FORMAT], cancel)?;
cli::run_cancellable(self.root(), &["branch", "-a", &contains, "--format=%(refname:short)"], cancel)?;
let cache_key = format!("{allowed}:{id}");
let cached = self.log_signatures.lock().unwrap_or_else(|p| p.into_inner()).get(&cache_key).cloned();
let mut details = if let Some(details) = cached {
@@ -952,7 +952,7 @@ impl Repo {
details
};
details.containing_branches =
branches.stdout_str().lines().filter(|s| !s.is_empty()).map(str::to_string).collect();
branches.stdout_str().lines().filter(|s| !s.ends_with("/HEAD")).map(str::to_string).collect();
Ok(details)
}
+3 -3
Переглянути файл
@@ -95,9 +95,9 @@ fn branch_at(r: &Repo, commit: &str) -> Option<String> {
}
["refs/heads", "refs/remotes"].into_iter().find_map(|refs| {
let out =
run(r.root(), &["for-each-ref", "--points-at", commit, crate::refs::DIRECT_BRANCH_FORMAT, refs], None)
.ok()?;
let names: Vec<String> = out.stdout_str().lines().filter(|l| !l.is_empty()).map(str::to_string).collect();
run(r.root(), &["for-each-ref", "--points-at", commit, "--format=%(refname:short)", refs], None).ok()?;
let names: Vec<String> =
out.stdout_str().lines().filter(|l| !l.is_empty() && !l.ends_with("/HEAD")).map(str::to_string).collect();
match names.as_slice() {
[one] => Some(one.clone()),
_ => None,
+3 -9
Переглянути файл
@@ -4,9 +4,6 @@ use crate::repo::{gx, to_string};
use crate::{Branch, BranchInfo, Repo, Stash};
use ide_core::IdeResult;
// Filter symbolic refs before shortening; `refname:short` also strips remote `/HEAD` suffixes.
pub(crate) const DIRECT_BRANCH_FORMAT: &str = "--format=%(if)%(symref)%(then)%(else)%(refname:lstrip=2)%(end)";
pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
let repo = r.gix()?;
let head_ref = repo.head_name().map_err(gx)?;
@@ -96,9 +93,6 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
for reference in platform.local_branches().map_err(gx)? {
let mut reference = reference.map_err(gx)?;
if reference.target().try_name().is_some() {
continue;
}
let full = reference.name().to_owned();
let Ok(id) = reference.peel_to_id().map(|id| id.detach()) else { continue };
let current = head_name.as_ref().is_some_and(|h| h == &full);
@@ -124,11 +118,11 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
}
for reference in platform.remote_branches().map_err(gx)? {
let mut reference = reference.map_err(gx)?;
// Skip symbolic aliases such as `refs/remotes/<remote>/HEAD`.
if reference.target().try_name().is_some() {
let full = reference.name().to_owned();
// Skip `refs/remotes/<remote>/HEAD` symbolic pointers.
if full.as_bstr().ends_with(b"/HEAD") {
continue;
}
let full = reference.name().to_owned();
let Ok(id) = reference.peel_to_id().map(|id| id.detach()) else { continue };
out.push(Branch {
name: to_string(full.as_ref().shorten()),
-15
Переглянути файл
@@ -149,21 +149,6 @@ fn merge_versions_put_the_users_work_on_the_left() {
assert_eq!(repo.merge_sides().unwrap(), MergeSides { branch: Some("topic".into()), ..Default::default() });
}
#[test]
fn rebase_conflict_names_the_remote_branch_without_its_symbolic_aliases() {
let fx = diverged();
let main = fx.git(&["rev-parse", "main"]);
fx.git(&["update-ref", "refs/remotes/origin/main", &main]);
fx.git(&["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
fx.git(&["symbolic-ref", "refs/remotes/origin/alias", "refs/remotes/origin/main"]);
fx.git(&["branch", "-D", "main"]);
let repo = fx.repo();
assert!(repo.rebase("origin/main").is_err());
assert_eq!(repo.merge_sides().unwrap().other_branch.as_deref(), Some("origin/main"));
let (cancel, out) = quiet();
repo.abort_operation(&cancel, &out).unwrap();
}
#[test]
fn rebase_conflict_then_abort_and_skip() {
let fx = diverged();
-88
Переглянути файл
@@ -113,43 +113,6 @@ fn lazy_summaries_seek_and_index_survive_refresh_and_restart() {
assert_eq!(repo.log_details(&ids[69]).unwrap().signature, "N");
}
#[test]
fn containing_branches_exclude_symbolic_aliases_but_keep_direct_head_names() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let tip = commit(dir, "a", "tip");
git(dir, &["branch", "topic/HEAD"]);
for remote in ["origin", "contributor-742", "issue-739", "issue-765"] {
let main = format!("refs/remotes/{remote}/main");
git(dir, &["update-ref", &main, &tip]);
git(dir, &["symbolic-ref", &format!("refs/remotes/{remote}/HEAD"), &main]);
git(dir, &["symbolic-ref", &format!("refs/remotes/{remote}/alias"), &main]);
}
git(dir, &["update-ref", "refs/remotes/origin/topic/HEAD", &tip]);
git(dir, &["symbolic-ref", "refs/heads/local-alias", "refs/heads/main"]);
let repo = Repo::discover(dir).unwrap().unwrap();
let expected = [
"contributor-742/main",
"issue-739/main",
"issue-765/main",
"main",
"origin/main",
"origin/topic/HEAD",
"topic/HEAD",
];
let mut branches = repo.log_details(&tip).unwrap().containing_branches;
branches.sort();
assert_eq!(branches, expected);
let mut listed: Vec<_> = repo.branches().unwrap().into_iter().map(|b| b.name).collect();
listed.sort();
assert_eq!(listed, expected);
let log = repo.log(&LogQuery::default()).unwrap();
let mut labels: Vec<_> = log[0].refs.iter().filter(|r| *r != "HEAD").cloned().collect();
labels.sort();
assert_eq!(labels, expected);
}
#[test]
fn followed_history_carries_the_filename_at_each_revision() {
let tmp = tempfile::tempdir().unwrap();
@@ -649,54 +612,3 @@ fn file_history_through_a_cyclic_rename() {
pairs(&[("b to a", "a.txt"), ("Modified b", "b.txt"), ("a to b", "b.txt"), ("Created a", "a.txt")])
);
}
/// One commit per file under `dir/`, made with fast-import so hundreds stay quick.
fn commit_files(repo_dir: &Path, count: usize, name: impl Fn(usize) -> String) {
let mut stream = String::new();
for i in 0..count {
let path = name(i);
stream.push_str(&format!(
"commit refs/heads/main\ncommitter T <[email protected]> {} +0000\ndata 3\nc{}\n",
1_700_000_000 + i,
i % 10
));
stream.push_str(&format!("M 100644 inline {path}\ndata 1\nx\n\n"));
}
let mut child = Command::new("git")
.current_dir(repo_dir)
.args(["fast-import", "--quiet"])
.stdin(Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(stream.as_bytes()).unwrap();
assert!(child.wait().unwrap().success());
git(repo_dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
git(repo_dir, &["reset", "-q", "--hard"]);
}
#[test]
fn followed_directory_history_survives_hundreds_of_created_files() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
// Every created file adds a `^<sha>^@` exclusion: ~800 of them passed as arguments exceed
// Windows' command-line limit (os error 206).
commit_files(dir, 800, |i| format!("module/src/main/java/com/example/generated/Class{i:04}.java"));
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { path: Some("module".into()), follow: true, ..Default::default() }).unwrap();
assert_eq!(log.len(), 800);
}
#[test]
fn many_selected_paths_filter_history_without_a_huge_command_line() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
commit_files(dir, 600, |i| format!("module/src/main/java/com/example/generated/Class{i:04}.java"));
let repo = Repo::discover(dir).unwrap().unwrap();
let paths: Vec<String> =
(0..500).map(|i| format!("module/src/main/java/com/example/generated/Class{i:04}.java")).collect();
let paths = paths.into_iter().map(Into::into).collect();
let log = repo.log(&LogQuery { paths, text: Some("c3".into()), ..Default::default() }).unwrap();
assert_eq!(log.len(), 50);
}
+1 -41
Переглянути файл
@@ -301,21 +301,6 @@ pub(crate) fn is_atomic_temp(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.') && n.contains(TMP_MARKER))
}
/// `sync_all` failures that mean "this filesystem cannot fsync at all", not that
/// the data was lost: ENOTTY (`os error 25`, virtio-fs on macOS VMs answering
/// F_FULLFSYNC/fsync with "Inappropriate ioctl for device") and EINVAL (some
/// network filesystems). Other errors keep failing the write.
fn sync_error_is_tolerable(e: &std::io::Error) -> bool {
if e.kind() == std::io::ErrorKind::InvalidInput {
return true;
}
// EINVAL is already covered by InvalidInput; ENOTTY has no ErrorKind of its own.
#[cfg(unix)]
return e.raw_os_error() == Some(25);
#[cfg(not(unix))]
false
}
/// Writes `bytes` to `path` atomically: temp file in the same directory, fsync,
/// rename over the target. Preserves the permissions of an existing file and
/// writes through symlinks. Falls back to an in-place write when the directory
@@ -362,17 +347,7 @@ fn write_atomic_impl(path: &Path, bytes: &[u8], allow_in_place: bool) -> IdeResu
};
let result = (|| -> std::io::Result<()> {
file.write_all(bytes)?;
if let Err(e) = file.sync_all() {
// virtio-fs (macOS VMs) and similar filesystems have no fsync/F_FULLFSYNC
// (ENOTTY, EINVAL): the write itself already went through, so the rename is
// still the best durability the filesystem offers — degrade like SQLite
// instead of failing the whole atomic write.
if sync_error_is_tolerable(&e) {
tracing::debug!("fsync unsupported for {}: {e}; continuing", target.display());
} else {
return Err(e);
}
}
file.sync_all()?;
if let Some(meta) = &existing {
fs::set_permissions(&tmp, meta.permissions())?;
}
@@ -551,19 +526,4 @@ mod tests {
assert_eq!(encode("x", "nope", false).unwrap_err().kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(encode("中", "windows-1252", false).unwrap_err().kind, ide_core::error::ErrorKind::InvalidInput);
}
#[test]
fn sync_errors_without_fsync_support_are_tolerable() {
// Some network filesystems report EINVAL for fsync.
assert!(sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::InvalidInput, "EINVAL")));
#[cfg(unix)]
{
// virtio-fs on macOS VMs answers fsync with "Inappropriate ioctl for device".
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(25)));
assert!(sync_error_is_tolerable(&std::io::Error::from_raw_os_error(22)));
}
// Real write failures still fail the atomic write.
assert!(!sync_error_is_tolerable(&std::io::Error::from_raw_os_error(28)));
assert!(!sync_error_is_tolerable(&std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied")));
}
}
+32 -122
Переглянути файл
@@ -81,14 +81,6 @@ fn exclude_path(root: &Path) -> PathBuf {
.unwrap_or_else(|| root.join(".git/info/exclude"))
}
#[derive(Default)]
struct NestedRepos {
/// Directory -> enclosing repository root when different from `GitignoreStack::repo_root`.
by_dir: HashMap<PathBuf, Option<PathBuf>>,
/// Repository root -> shared `GitignoreStack` for that nested repository.
by_root: HashMap<PathBuf, Arc<GitignoreStack>>,
}
/// Layered gitignore matching: per-directory `.gitignore` / `.ignore` from the
/// path's directory up to the repository root (or the file system root when
/// not in a repository), then `.git/info/exclude` and the global excludes file.
@@ -97,7 +89,7 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
nested: Mutex<NestedRepos>,
nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
}
/// How long [`GitignoreStack::cached`] reuses the repository lookup of a directory.
@@ -199,23 +191,13 @@ impl GitignoreStack {
if let (Some(root), Some(map)) = (&self.repo_root, REPO_LEVEL.lock().as_mut()) {
map.retain(|dir, _| !dir.starts_with(root));
}
self.nested.lock().by_root.values().for_each(|s| s.reload_repo_level());
self.nested.lock().clear();
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
}
/// Forgets the cached rules of `dir` and every directory below it.
pub fn invalidate_tree(&self, dir: &Path) {
{
let mut nested = self.nested.lock();
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
}
for stack in nested.by_root.values() {
stack.invalidate_tree(dir);
}
}
self.nested.lock().clear();
let mut cache = self.cache.lock();
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
@@ -229,57 +211,10 @@ impl GitignoreStack {
/// Forgets the cached rules of `dir` (after its `.gitignore` changed).
pub fn invalidate(&self, dir: &Path) {
for stack in self.nested.lock().by_root.values() {
stack.invalidate(dir);
}
self.nested.lock().clear();
self.cache.lock().remove(dir);
}
/// Returns the shared `GitignoreStack` of the nested repository enclosing `dir`, if any.
fn nested_for(&self, dir: &Path) -> Option<Arc<GitignoreStack>> {
let mut nested = self.nested.lock();
let root = if let Some(cached) = nested.by_dir.get(dir) {
cached.clone()
} else {
let mut chain = Vec::new();
let mut found = None;
for anc in dir.ancestors() {
if let Some(cached) = nested.by_dir.get(anc) {
found = cached.clone();
break;
}
chain.push(anc.to_path_buf());
if self.repo_root.as_deref() == Some(anc) {
found = None;
break;
}
if anc.join(".git").exists() {
found = Some(anc.to_path_buf());
break;
}
}
for p in chain {
nested.by_dir.insert(p, found.clone());
}
found
}?;
Some(
nested
.by_root
.entry(root.clone())
.or_insert_with(|| {
let repo_level = RwLock::new(Self::load_repo_level(Some(&root)));
Arc::new(Self {
repo_root: Some(root),
repo_level,
cache: Mutex::default(),
nested: Mutex::default(),
})
})
.clone(),
)
}
fn matcher_for(&self, dir: &Path) -> Option<Arc<Gitignore>> {
if let Some(cached) = self.cache.lock().get(dir) {
return cached.clone();
@@ -315,10 +250,20 @@ impl GitignoreStack {
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
// A project's watcher can span independent nested repositories. Their local
// excludes and ignore ancestry must stop at their own repository boundary.
if let Some(parent) = path.parent()
&& let Some(nested) = self.nested_for(parent)
{
return nested.is_ignored(path, is_dir);
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored(path, is_dir);
}
}
if self.repo_root.as_deref() == Some(path) {
return false;
@@ -357,10 +302,20 @@ impl GitignoreStack {
/// ignored) still emit its own create/remove so the tree can show it
/// appearing marked as ignored, while files inside it stay filtered out.
pub fn is_ignored_self(&self, path: &Path, is_dir: bool) -> bool {
if let Some(parent) = path.parent()
&& let Some(nested) = self.nested_for(parent)
{
return nested.is_ignored_self(path, is_dir);
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored_self(path, is_dir);
}
}
if self.repo_root.as_deref() == Some(path) {
return false;
@@ -450,49 +405,4 @@ mod tests {
assert_eq!(first.repo_root(), again.repo_root());
assert_eq!(again.repo_root(), Some(tmp.path()));
}
#[test]
fn nested_repository_shares_one_gitignore_stack_across_subdirectories() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path();
let repo = workspace.join("yolo");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(repo.join("a/b/c")).unwrap();
std::fs::create_dir_all(repo.join("x/y/z")).unwrap();
std::fs::write(repo.join(".gitignore"), "*.ignored\n").unwrap();
let stack = GitignoreStack::new(workspace);
assert!(stack.is_ignored(&repo.join("a/b/c/file.ignored"), false));
assert!(stack.is_ignored(&repo.join("x/y/z/other.ignored"), false));
assert!(!stack.is_ignored(&repo.join("x/y/z/keep.rs"), false));
assert_eq!(stack.nested.lock().by_root.len(), 1);
let nested = stack.nested.lock().by_root.get(&repo).unwrap().clone();
assert!(nested.cache.lock().contains_key(&repo));
// Invalidating a leaf file or directory inside the nested repo keeps its shared stack.
stack.invalidate_tree(&repo.join("a/b/c/new.rs"));
assert_eq!(stack.nested.lock().by_root.len(), 1);
assert!(Arc::ptr_eq(&nested, stack.nested.lock().by_root.get(&repo).unwrap()));
}
#[test]
fn a_repository_created_inside_the_workspace_becomes_a_boundary() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path();
std::fs::create_dir_all(workspace.join(".git")).unwrap();
std::fs::create_dir_all(workspace.join("sub/deep")).unwrap();
std::fs::write(workspace.join(".gitignore"), "*.tmp\n").unwrap();
let stack = GitignoreStack::new(workspace);
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
std::fs::create_dir(workspace.join("sub/.git")).unwrap();
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(!stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
std::fs::remove_dir(workspace.join("sub/.git")).unwrap();
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
}
}
+13 -144
Переглянути файл
@@ -13,7 +13,7 @@ use crate::FsBatch;
use crate::rules::{ExcludeMatcher, GitignoreStack};
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
use notify::event::{ModifyKind, RenameMode};
use notify::{ErrorKind, Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use notify::{Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use parking_lot::{Condvar, Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Component, Path, PathBuf};
@@ -27,9 +27,6 @@ const DEBOUNCE: Duration = Duration::from_millis(100);
const MAX_DELAY: Duration = Duration::from_millis(1000);
/// How often the polling fallback rescans the watched directories.
const POLL_INTERVAL: Duration = Duration::from_secs(2);
/// Directories watched synchronously in [`Watcher::start`] before handing the
/// remainder of a large tree to the watcher thread.
const SYNC_WATCH_BUDGET: usize = 256;
/// How directories are registered with the OS.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -179,14 +176,13 @@ impl Watcher {
},
config,
)
.map_err(|e| watcher_error("cannot start file watcher", e))?;
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
*state.watcher.lock() = Some(Box::new(watcher));
let deferred = if mode == WatchMode::PerDirectory {
state.watch_tree_bounded(root, SYNC_WATCH_BUDGET)
if mode == WatchMode::PerDirectory {
state.watch_tree(root, false, &mut Vec::new());
} else {
state.add_watch(root);
Vec::new()
};
}
if state.watched.lock().is_empty() {
return Err(io_error(format!("cannot watch {}", root.display())));
}
@@ -194,7 +190,7 @@ impl Watcher {
let state = state.clone();
std::thread::Builder::new()
.name("openidea-fs-watch".into())
.spawn(move || state.run(deferred, &*emit))
.spawn(move || state.run(&*emit))
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?
};
Ok(Inner { state, thread: Some(thread) })
@@ -227,29 +223,6 @@ fn is_dir_touch(event: &notify::Event) -> bool {
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
}
const MAX_WATCHES_HINT: &str = "the inotify watch limit is exhausted (fs.inotify.max_user_watches); raise it, e.g. \
`sudo sysctl -w fs.inotify.max_user_watches=524288`";
/// `io_error` with a fix hint when Linux's inotify limits are exhausted: one
/// instance per watcher (`EMFILE`, os error 24) or one watch per directory
/// (`ENOSPC`, mapped by notify to [`ErrorKind::MaxFilesWatch`]). A bare OS
/// error sends users off to search engines otherwise (issue #788).
fn watcher_error(what: &str, error: notify::Error) -> IdeError {
let hint = match error.kind {
ErrorKind::MaxFilesWatch => Some(MAX_WATCHES_HINT),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(24) => Some(
"the inotify instance limit is exhausted (fs.inotify.max_user_instances); raise it, e.g. \
`sudo sysctl -w fs.inotify.max_user_instances=1024`",
),
ErrorKind::Io(ref e) if cfg!(target_os = "linux") && e.raw_os_error() == Some(28) => Some(MAX_WATCHES_HINT),
_ => None,
};
match hint {
Some(hint) => io_error(format!("{what}: {error}; {hint}")),
None => io_error(format!("{what}: {error}")),
}
}
/// Shared with the notify callback (weakly) and the debounce thread.
struct DirState {
filter: EventFilter,
@@ -266,12 +239,8 @@ impl DirState {
self.stop.load(Ordering::SeqCst)
}
/// Debounce loop: finishes any deferred startup watches, then waits for a
/// quiet period and processes each batch.
fn run(&self, deferred: Vec<(PathBuf, bool)>, emit: impl Fn(&FsBatch)) {
if !deferred.is_empty() {
self.watch_stack(deferred, false, &mut Vec::new(), None);
}
/// Debounce loop: waits for a quiet period, then processes the batch.
fn run(&self, emit: impl Fn(&FsBatch)) {
loop {
let events = {
let mut q = self.queue.lock();
@@ -329,7 +298,6 @@ impl DirState {
// during this batch would otherwise never be seen.
for path in &batch.vcs {
if !self.watched.lock().contains(path) && path.symlink_metadata().is_ok_and(|m| m.is_dir()) {
self.filter.gitignore.invalidate_tree(path);
self.watch_tree(path, false, &mut discovered);
}
}
@@ -381,33 +349,11 @@ impl DirState {
/// files and directories found inside (created before the watch was in
/// place) are appended to `found`.
fn watch_tree(&self, dir: &Path, report: bool, found: &mut Vec<PathBuf>) {
self.watch_stack(vec![(dir.to_path_buf(), false)], report, found, None);
}
/// Watches up to `budget` directories synchronously and returns any
/// remaining `(dir, parent_verified)` entries for background registration.
fn watch_tree_bounded(&self, dir: &Path, budget: usize) -> Vec<(PathBuf, bool)> {
self.watch_stack(vec![(dir.to_path_buf(), false)], false, &mut Vec::new(), Some(budget))
}
fn watch_stack(
&self,
mut stack: Vec<(PathBuf, bool)>,
report: bool,
found: &mut Vec<PathBuf>,
budget: Option<usize>,
) -> Vec<(PathBuf, bool)> {
let mut watched_now = 0;
while let Some((dir, parent_ok)) = stack.pop() {
if self.stopped() {
break;
}
let should_watch =
if parent_ok { self.filter.should_watch_child_dir(&dir) } else { self.filter.should_watch_dir(&dir) };
if !should_watch || !self.add_watch(&dir) {
let mut stack = vec![dir.to_path_buf()];
while let Some(dir) = stack.pop() {
if self.stopped() || !self.filter.should_watch_dir(&dir) || !self.add_watch(&dir) {
continue;
}
watched_now += 1;
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
@@ -416,14 +362,10 @@ impl DirState {
found.push(path.clone());
}
if is_dir {
stack.push((path, true));
stack.push(path);
}
}
if budget.is_some_and(|max| watched_now >= max) {
break;
}
}
stack
}
fn unwatch_tree(&self, dir: &Path) {
@@ -527,15 +469,6 @@ impl EventFilter {
/// and `worktrees/` (HEAD, index, refs and worktree metadata are what VCS
/// refresh needs).
pub fn should_watch_dir(&self, dir: &Path) -> bool {
self.should_watch_dir_inner(dir, false)
}
/// Fast path when `dir`'s parent directory is already known to be watchable.
fn should_watch_child_dir(&self, dir: &Path) -> bool {
self.should_watch_dir_inner(dir, true)
}
fn should_watch_dir_inner(&self, dir: &Path, parent_ok: bool) -> bool {
let Ok(rel) = dir.strip_prefix(&self.root) else { return false };
if rel.as_os_str().is_empty() {
return true;
@@ -551,11 +484,7 @@ impl EventFilter {
_ => false,
};
}
if parent_ok {
!self.excludes.read().is_match(rel) && !self.gitignore.is_ignored_self(dir, true)
} else {
!self.excludes.read().is_excluded(rel) && !self.gitignore.is_ignored(dir, true)
}
!self.excludes.read().is_excluded(rel) && !self.gitignore.is_ignored(dir, true)
}
/// Whether a path found by scanning a new directory would be reported.
@@ -1146,42 +1075,6 @@ mod tests {
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn per_directory_mode_watches_the_rest_of_a_large_tree_after_start() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let dirs = SYNC_WATCH_BUDGET + 40;
for i in 0..dirs {
std::fs::create_dir_all(root.join(format!("d{i:03}"))).unwrap();
}
std::fs::create_dir_all(root.join("node_modules/x")).unwrap();
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
let watcher = {
let batches = batches.clone();
Watcher::start_with(
&root,
vec!["**/node_modules".into()],
sink,
Box::new(move |b| batches.lock().push(b.clone())),
WatchMode::PerDirectory,
)
.unwrap()
};
let deadline = Instant::now() + Duration::from_secs(10);
while watcher.watch_count() < dirs + 1 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
// root and every d*, but not node_modules
assert_eq!(watcher.watch_count(), dirs + 1);
std::thread::sleep(Duration::from_millis(200));
for i in [0, dirs - 1] {
let file = root.join(format!("d{i:03}/f.rs"));
std::fs::write(&file, "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{file:?}");
}
}
#[test]
fn per_directory_mode_follows_worktree_registrations() {
let tmp = tempfile::tempdir().unwrap();
@@ -1296,28 +1189,4 @@ mod tests {
std::fs::write(root.join("src/new/inner/h.rs"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/new/inner/h.rs"))));
}
#[test]
fn ordinary_watcher_errors_keep_the_bare_message() {
let other = notify::Error::io(std::io::Error::other("no space left"));
assert_eq!(
watcher_error("cannot start file watcher", other).message,
"cannot start file watcher: no space left"
);
}
#[cfg(target_os = "linux")]
#[test]
fn inotify_limits_get_a_sysctl_hint() {
let emfile = notify::Error::io(std::io::Error::from_raw_os_error(24));
let msg = watcher_error("cannot start file watcher", emfile).message;
assert!(msg.contains("os error 24"), "{msg}");
assert!(msg.contains("max_user_instances"), "{msg}");
let enospc = notify::Error::io(std::io::Error::from_raw_os_error(28));
assert!(watcher_error("cannot watch /proj", enospc).message.contains("max_user_watches"));
let max_files = notify::Error::new(ErrorKind::MaxFilesWatch);
assert!(watcher_error("cannot watch /proj", max_files).message.contains("max_user_watches"));
let other = notify::Error::io(std::io::Error::from_raw_os_error(13));
assert!(!watcher_error("cannot start file watcher", other).message.contains("inotify"));
}
}
+2 -3
Переглянути файл
@@ -69,8 +69,7 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
await expect(page.getByText(/1 file committed: Return order DTOs from create/)).toBeVisible();
const [committed] = await ipcCalls(page, "vcs_commit");
expect(committed).toMatchObject({ repo: ROOT, message: "Return order DTOs from create" });
// The commit takes the checked file itself; the index isn't staged beforehand.
expect((committed!.options as { stage: string[] }).stage).toEqual([`${ROOT}/build.gradle.kts`]);
expect(await ipcCalls(page, "vcs_stage")).toHaveLength(0);
const staged = (await ipcCalls(page, "vcs_stage")).flatMap((a) => a.paths as string[]);
expect(staged).toEqual([`${ROOT}/build.gradle.kts`]);
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
+10 -6
Переглянути файл
@@ -8,11 +8,12 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const NAMES = Array.from({ length: 20 }, (_, i) => `src/f${i}.ts`);
/** Twenty modified tracked files; `vcs_commit` takes the files it commits out of the status. */
/** Twenty modified tracked files; `vcs_stage` + `vcs_commit` take the staged ones out of the status. */
async function stubTwentyChanges(page: Page) {
await stubDesktop(page);
await page.evaluate(
async ({ root, names }) => {
const staged = new Set<string>();
const committed = new Set<string>();
const all = names.map((rel) => ({
path: `${root}/${rel}`,
@@ -32,10 +33,14 @@ async function stubTwentyChanges(page: Page) {
operation: null,
});
h.vcs_status = () => all.filter((f) => !committed.has(f.path));
h.vcs_stage = () => null;
h.vcs_stage = (args) => {
for (const path of args.paths as string[]) staged.add(path);
return null;
};
h.vcs_unstage = () => null;
h.vcs_commit = (args) => {
for (const path of (args.options as { stage: string[] }).stage) committed.add(path);
h.vcs_commit = () => {
for (const path of staged) committed.add(path);
staged.clear();
return "2222222";
};
const vcsModule = "/src/features/vcs/store.ts";
@@ -66,8 +71,7 @@ test("changes left out of a commit stay unchecked (#1539)", async ({ workbench:
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit 5 of 20");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect(page.getByText(/5 files committed: Commit 5 of 20/)).toBeVisible();
const [commit] = await ipcCalls(page, "vcs_commit");
expect([...(commit!.options as { stage: string[] }).stage].sort()).toEqual(
expect((await ipcCalls(page, "vcs_stage")).flatMap((a) => a.paths as string[]).sort()).toEqual(
NAMES.slice(0, 5)
.map((rel) => `${ROOT}/${rel}`)
.sort(),
-148
Переглянути файл
@@ -1,148 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("shows GitHub check statuses for each commit's repository", async ({ workbench: page }) => {
await page.clock.install();
await stubDesktop(page);
await page.evaluate(async () => {
const primary = "/dev/acme-api";
const linked = "/dev/acme-web";
const tip = "1".repeat(40);
const pending = "2".repeat(40);
const missing = "3".repeat(40);
const h = window.__ipc.handlers;
h.vcs_roots = () =>
[
{ root: primary, head: "main" },
{ root: linked, head: "release" },
].map((repo) => ({ ...repo, operation: null, headCommit: tip }));
h.vcs_branch_info = ({ repo }) => ({
head: repo === linked ? "release" : "main",
headCommit: tip,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_branches = ({ repo }) =>
[repo === linked ? "origin/dev" : "origin/other"].map((name) => ({
name,
commit: tip,
remote: true,
current: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
}));
h.vcs_log = ({ repo }) => {
const rows: [string, string][] =
repo === linked
? [[tip, "Linked repository commit"]]
: [
[tip, "Primary repository commit"],
[pending, "Pending commit"],
[missing, "Local-only commit"],
];
return rows.map(([id, summary], i) => ({
id,
shortId: id.slice(0, 8),
parents: [],
refs: i === 0 ? [repo === linked ? "origin/dev" : "origin/other"] : [],
author: "A",
email: "[email protected]",
timeMs: 0,
summary,
message: summary,
}));
};
h.vcs_log_refs = () => ({});
h.vcs_log_details_batch = ({ revisions }) =>
(revisions as string[]).map(() => ({
message: "Linked repository commit",
containingBranches: [],
signature: "N",
signer: "",
key: "",
fingerprint: "",
}));
h.vcs_commit_files = () => [];
h.vcs_config_get = () => null;
h.vcs_tags = () => [];
h.vcs_status = () => [];
h.vcs_remotes = ({ repo }) => [
{ name: "origin", url: `[email protected]:example/${repo === linked ? "web" : "api"}.git` },
];
let pendingQueries = 0;
h.gh_api = ({ repo, request }) => {
const { variables } = JSON.parse((request as { body: string }).body) as { variables: Record<string, string> };
const linkedRepo = repo === linked;
const state = linkedRepo ? "FAILURE" : "SUCCESS";
if (variables.oid)
return JSON.stringify({
data: {
repository: {
object: {
statusCheckRollup: {
contexts: {
nodes: [{ __typename: "StatusContext", context: "Frontend", state, targetUrl: null }],
pageInfo: { hasNextPage: false, endCursor: null },
},
},
},
},
},
});
const statuses = Object.entries(variables)
.filter(([key]) => /^oid\d+$/.test(key))
.map(([key, revision]) => [
key.replace("oid", "c"),
revision === missing
? null
: { statusCheckRollup: { state: revision === pending && ++pendingQueries === 1 ? "PENDING" : state } },
]);
return JSON.stringify({ data: { repository: Object.fromEntries(statuses) } });
};
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root: primary, repo: primary });
await refreshNow();
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showLog");
});
const primary = page.getByRole("option", { name: /Primary repository commit/ });
const linked = page.getByRole("option", { name: /Linked repository commit/ });
await expect(primary).toBeVisible();
expect(await ipcCalls(page, "gh_api")).toEqual([]);
await page.getByRole("button", { name: "View Options" }).first().click();
await page.getByRole("menuitem", { name: "Columns", exact: true }).hover();
await page.getByRole("menuitemcheckbox", { name: "GitHub Commit Checks" }).click({ timeout: 4000 });
await expect(primary.getByRole("button", { name: "Checks passed" })).toBeVisible();
await expect(linked.getByRole("button", { name: "Checks failed" })).toBeVisible();
await expect(
page.getByRole("option", { name: /Pending commit/ }).getByRole("button", { name: "Checks in progress…" }),
).toBeVisible();
await expect(
page.getByRole("option", { name: /Local-only commit/ }).getByRole("button", { name: /^Checks / }),
).toHaveCount(0);
const calls = await ipcCalls(page, "gh_api");
expect(calls.map((c) => c.repo).sort()).toEqual(["/dev/acme-api", "/dev/acme-web"]);
expect(calls.map((c) => JSON.parse((c.request as { body: string }).body).variables.repoName).sort()).toEqual([
"api",
"web",
]);
await linked.getByRole("button", { name: "Checks failed" }).click();
await expect(page.getByRole("option", { name: /Frontend/ })).toBeVisible();
expect((await ipcCalls(page, "gh_api")).at(-1)).toMatchObject({ repo: "/dev/acme-web" });
await page.keyboard.press("Escape");
await page.clock.fastForward(31_000);
await expect(
page.getByRole("option", { name: /Pending commit/ }).getByRole("button", { name: "Checks passed" }),
).toBeVisible();
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.7.0
Bundle-Version: 1.6.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+5 -21
Переглянути файл
@@ -12,14 +12,6 @@ The Rust bridge logs the failure once per project session. Cancelled requests an
changed source documents remain cancelled and do not start a fallback search.
No global `includeAccessors` preference is changed.
An optional fifth argument `"sources"` restricts the search to the workspace's
source folders (no dependency jars, no JDK). A library method can have thousands of
usages in those, which take seconds to search. Find Usages searches the sources alone
(Project Files) unless asked for Project and Libraries; then it shows the sources' usages
first and runs the full search after it. Rows in library classes (`jdt:` URIs) carry their
line as `text`, from the contents the client would request for the class, so the client
need not fetch thousands of class files to show them.
## Search plan and access semantics
For source fields on the verified JDT LS implementation, a single plan merges
@@ -28,14 +20,10 @@ Targets are deduplicated by JDT element identity before search, retaining native
search scope and ranges. Builder results remain unknown. The optimized native
plan is guarded by SHA-256 of ReferencesHandler.class:
`31ff5a10c7d69d58c6a9b619ef17e3ec41b11b545751ba428618a76cc1341064`
(JDT LS 1.63.0.202610191322). On that version, non-field and library/decompiled
selections resolve their target as `ReferencesHandler.findReferences` does, and every
search replicates `ReferencesHandler.search` with one difference: a class file whose
decompiled source fails to parse loses only its own matches (logged), where the server
throws and fails the whole search after searching most dependencies. Different
implementations retain native discovery plus deduplicated category searches. This
conservative fallback preserves coverage when the server changes; it does not promise
the same speedup or fault isolation on unverified versions.
(JDT LS 1.63.0.202610191322). Different implementations, non-field selections and
library/decompiled selections retain native discovery plus deduplicated category
searches. This conservative fallback preserves coverage when the server changes;
it does not promise the same speedup on unverified versions.
SearchEngine resolves exact targets. A query-local syntax AST per referenced source
file supplies expression context without another reference search: simple field
@@ -69,7 +57,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.7.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.6.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -99,10 +87,6 @@ Version 1.6.0 adds `openidea.java.configuration.warmup`, which builds configurat
low-priority background job after import, and builds them under cancellable per-project locks
instead of one global lock; its reproducible SHA-256 is
`33cfa1bb8489247ffeb6fc8249966c8a2955b7b2858c8169a70486eb70ade696`.
Version 1.7.0 adds the `"sources"` scope to `openidea.java.usages`, searches each class
file's decompiled source on its own and returns the line (`text`) of each usage in a library
class; its reproducible SHA-256 is
`56d35619d5be937b028ac143ba748365a66a74c803bc112e4788a7dce98b44fc`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
+22 -168
Переглянути файл
@@ -4,25 +4,13 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.SearchUtils;
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
import org.eclipse.jdt.ls.core.internal.handlers.ReferencesHandler;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences.SearchScope;
import org.eclipse.lsp4j.*;
/** Classifies search results using JDT method identities, never reference text. */
@@ -33,14 +21,8 @@ public final class UsagesCommand implements IDelegateCommandHandler {
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
boolean declarations = Boolean.TRUE.equals(arguments.get(3));
// "sources": the workspace's source folders only, without dependency jars or the JDK. A
// library method's usages there are found long before the full search ends.
boolean sources = arguments.size() > 4 && "sources".equals(arguments.get(4));
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
var handler = new ReferencesHandler(preferences);
// The verified server's search is replicated (see `search`); others keep their own.
boolean replicated = sources || NATIVE_PLAN_SUPPORTED;
Search search = replicated ? (element, locations, m, d) -> search(element, locations, m, d, sources) : handler::search;
var params = new ReferenceParams(new TextDocumentIdentifier(uri), new Position(line, column), new ReferenceContext(declarations));
Map<Location, String> results = new LinkedHashMap<>();
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
@@ -49,95 +31,40 @@ public final class UsagesCommand implements IDelegateCommandHandler {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
boolean accessors = preferences.getPreferences().isIncludeAccessors();
SearchPlan plan = new SearchPlan();
ITypeRoot targetRoot = null;
try {
// Only replace native target discovery for the exact implementation verified by
// integration tests. New server implementations retain their full native behavior.
if (selected instanceof IField field && root instanceof ICompilationUnit &&
root.getResource() != null && NATIVE_PLAN_SUPPORTED) {
// Only replace native target discovery for the exact implementation verified by
// integration tests. New server implementations retain their full native behavior.
if (selected instanceof IField field && root instanceof ICompilationUnit &&
root.getResource() != null && NATIVE_PLAN_SUPPORTED) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else {
// Includes non-fields, library/decompiled roots, and unverified JDT LS builds.
for (var location : handler.findReferences(params, monitor)) results.put(location, "unknown");
if (selected instanceof IField field) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else if (replicated) {
// Non-fields and library/decompiled roots: the target ReferencesHandler.findReferences
// resolves (a class file without source through its decompiled working copy), widened
// as it widens a field.
boolean decompiled = preferences.isClientSupportsClassFileContent() && preferences.getPreferences().isIncludeDecompiledSources();
targetRoot = JDTUtils.resolveTypeRoot(uri, decompiled, monitor);
IJavaElement target = targetRoot == null ? null :
JDTUtils.findElementAtSelection(targetRoot, line, column, preferences, monitor);
if (target == null && targetRoot != null) {
target = targetRoot.getElementAt(JsonRpcHelpers.toOffset(targetRoot.getBuffer(), line, column));
}
plan.add(target, target instanceof IField ? "field" : "unknown", declarations);
if (accessors && target instanceof IField field) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
if (NATIVE_PLAN_SUPPORTED) addNativeBuilderTargets(handler, field, plan);
addConfiguredAccessors(field, plan);
}
} else {
// Unverified JDT LS builds.
for (var location : handler.findReferences(params, monitor)) results.put(location, "unknown");
if (selected instanceof IField field) {
plan.add(field, "field", declarations);
if (accessors) {
plan.add(GetterSetterUtil.getGetter(field), "getter", false);
plan.add(GetterSetterUtil.getSetter(field), "setter", false);
addConfiguredAccessors(field, plan);
}
}
}
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(search, target.element, target.kind(), target.declarations, results, monitor);
}
} finally {
if (targetRoot != null) JDTUtils.discardClassFileWorkingCopy(targetRoot);
}
for (var target : plan.targets.values()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
add(handler, target.element, target.kind(), target.declarations, results, monitor);
}
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
List<Map<String, Object>> response = new ArrayList<>();
UsageAccess access = new UsageAccess(monitor, results);
Map<String, String[]> libraryLines = new java.util.HashMap<>();
for (var entry : results.entrySet()) {
if (monitor.isCanceled()) throw new org.eclipse.core.runtime.OperationCanceledException();
Location location = entry.getKey();
Map<String, Object> row = new LinkedHashMap<>();
row.put("location", location);
row.put("kind", entry.getValue());
row.put("access", access.classify(location, entry.getValue()));
String text = libraryLine(location, libraryLines, monitor);
if (text != null) row.put("text", text);
response.add(row);
}
results.forEach((location, kind) -> response.add(Map.of("location", location, "kind", kind, "access", access.classify(location, kind))));
return response;
}
/**
* The line of a usage in a library class (`jdt:` URI), from the contents the client would
* request for it: so the client need not fetch thousands of class files to show the lines.
*/
private static String libraryLine(Location location, Map<String, String[]> cache, IProgressMonitor monitor) {
String uri = location.getUri();
if (uri == null || !uri.startsWith("jdt:")) return null;
if (!cache.containsKey(uri)) {
String contents = null;
try {
contents = JavaLanguageServerPlugin.getContentProviderManager().getContent(JDTUtils.toURI(uri), monitor);
} catch (RuntimeException e) {
if (e instanceof org.eclipse.core.runtime.OperationCanceledException) throw e;
}
cache.put(uri, contents == null ? null : contents.split("\\r\\n?|\\n", -1));
}
String[] lines = cache.get(uri);
int line = location.getRange().getStart().getLine();
return lines != null && line >= 0 && line < lines.length ? lines[line] : null;
}
/** Resolve explicit Lombok @Accessors naming, then search exact JDT method identities.
* Configuration-file-only naming is deliberately not guessed.
*/
@@ -264,84 +191,11 @@ public final class UsagesCommand implements IDelegateCommandHandler {
(resolved[0][0].isEmpty() ? resolved[0][1] : resolved[0][0] + "." + resolved[0][1]).equals(owner.getFullyQualifiedName());
}
private interface Search {
void run(IJavaElement element, List<Location> locations, IProgressMonitor monitor, boolean declarations) throws Exception;
}
/**
* ReferencesHandler.search of the verified server, except that a class file whose decompiled
* source fails to parse loses only its own matches: there the server throws and fails the
* whole search, after searching most of the dependencies. `sources`: the workspace's source
* folders only, without dependency jars and the JDK.
*/
private static void search(IJavaElement element, List<Location> locations, IProgressMonitor monitor,
boolean declarations, boolean sources) throws CoreException {
SearchPattern pattern = SearchPattern.createPattern(element, IJavaSearchConstants.REFERENCES);
if (pattern == null) return;
if (declarations) {
SearchPattern declaration = SearchPattern.createPattern(element, IJavaSearchConstants.DECLARATIONS);
if (declaration != null) pattern = SearchPattern.createOrPattern(pattern, declaration);
}
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
SearchScope setting = preferences.getPreferences().getSearchScope();
int mask = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
if (!sources && setting != SearchScope.projectOnly) {
mask |= IJavaSearchScope.APPLICATION_LIBRARIES;
if (insideJre(element)) mask |= IJavaSearchScope.SYSTEM_LIBRARIES;
}
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(setting == SearchScope.main, projects, mask);
boolean classFiles = preferences.isClientSupportsClassFileContent();
boolean decompiled = preferences.getPreferences().isIncludeDecompiledSources();
new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.getAccuracy() == SearchMatch.A_INACCURATE || !(match.getElement() instanceof IJavaElement found)) return;
if (found.getAncestor(IJavaElement.COMPILATION_UNIT) instanceof ICompilationUnit unit) {
locations.add(JDTUtils.toLocation(unit, match.getOffset(), match.getLength()));
return;
}
if (!classFiles || !(found.getAncestor(IJavaElement.CLASS_FILE) instanceof IClassFile classFile)) return;
if (classFile.getSourceRange() != null) {
locations.add(JDTUtils.toLocation(classFile, match.getOffset(), match.getLength()));
return;
}
if (!decompiled) return;
try {
if (found instanceof IMember member) {
Location location = SearchUtils.searchOtherSources(member);
if (location != null) locations.add(location);
}
locations.addAll(JDTUtils.searchDecompiledSources(found, classFile, false, false, monitor));
} catch (org.eclipse.core.runtime.OperationCanceledException e) {
throw e;
} catch (RuntimeException | CoreException e) {
JavaLanguageServerPlugin.logInfo("Usages in decompiled " + classFile.getElementName() + " skipped: " + e);
}
}
}, monitor);
}
/** ReferencesHandler.isInsideJRE: a JDK element is searched in the JDK too. */
private static boolean insideJre(IJavaElement element) {
if (!(element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT) instanceof IPackageFragmentRoot root)) return true;
try {
IClasspathEntry entry = root.getRawClasspathEntry();
if (entry.getEntryKind() != IClasspathEntry.CPE_CONTAINER) return false;
IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), root.getJavaProject());
return container != null && container.getKind() == IClasspathContainer.K_DEFAULT_SYSTEM;
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException(e);
return true;
}
}
private static void add(Search search, IJavaElement element, String kind, boolean declarations,
private static void add(ReferencesHandler handler, IJavaElement element, String kind, boolean declarations,
Map<Location, String> results, IProgressMonitor monitor) throws Exception {
if (element == null) return;
List<Location> locations = new ArrayList<>();
search.run(element, locations, monitor, declarations);
handler.search(element, locations, monitor, declarations);
for (var location : locations) {
if (kind.equals("unknown")) { results.putIfAbsent(location, kind); continue; }
String previous = results.get(location);
-13
Переглянути файл
@@ -106,14 +106,6 @@ def request(method, params):
if 'error' in msg: raise RuntimeError(msg['error'])
return msg.get('result')
raise TimeoutError(method)
def assert_sources(line, col, full=None):
"""The "sources" scope finds what the full search finds in the workspace's sources."""
usages = lambda *scope: request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),line,col,False,*scope]})
full = usages() if full is None else full
sources = usages('sources')
key = lambda rows: sorted(json.dumps(r, sort_keys=True) for r in rows)
assert key(sources) == key(r for r in full if r['location']['uri'].startswith('file:')), (line, col, sources, full)
return sources
try:
init = request('initialize', {'processId':None, 'rootUri':project.as_uri(), 'workspaceFolders':[{'uri':project.as_uri(), 'name':'accessors'}], 'capabilities':{}, 'initializationOptions':{'bundles':[str(bundle)], 'settings':{'java':{'references':{'includeAccessors':True}, 'import':{'gradle':{'enabled':False}, 'maven':{'enabled':False}}}}}})
send({'jsonrpc':'2.0','method':'initialized','params':{}})
@@ -131,11 +123,6 @@ try:
assert kinds.count('getter') == expected[0], (field, kinds)
assert kinds.count('setter') == expected[1], (field, kinds)
assert kinds.count('field') == expected[2], (field, kinds)
assert_sources(line, col, after)
# A JDK method: in the sources, the same as the full search's sources part.
line, text = next((i, t) for i, t in enumerate(source.splitlines()) if 'println' in t)
evidence['jdkSources'] = assert_sources(line, text.index('println'))
assert evidence['jdkSources'], 'no JDK method usages in the sources'
# Respect the existing global preference: the command must not switch it on.
send({'jsonrpc':'2.0','method':'workspace/didChangeConfiguration','params':{'settings':{'java':{'references':{'includeAccessors':False}}}}})
disabled = request('workspace/executeCommand', {'command':'openidea.java.usages','arguments':[file.as_uri(),3,19,False]})
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.38",
"version": "0.1.37",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+2 -40
Переглянути файл
@@ -94,8 +94,6 @@ homepage = "https://example.com" # optional
license = "MIT" # optional
change-notes = "1.2.0 — …" # shown under What's New
categories = ["tools"] # marketplace categories, see below
icon = "icon.svg" # optional, see below
icon-dark = "icon_dark.svg" # optional
engines.openidea = "^1.0" # the plugin API this package needs
wasm = "dist/plugin.wasm" # omit for data-only plugins
activation = ["on-language:markdown"] # optional, see below
@@ -118,14 +116,6 @@ icon themes or languages is filed under those, any other under `other`.
Categories an IDE doesn't know, and any after the first three it knows, are
ignored (`check` warns about both).
`icon` is an SVG of the package shown in Settings › Plugins and the
marketplace; `icon-dark`, if given, replaces it with dark themes. Each is at
most 16 KiB and sanitised like file icons (no scripts, external references or
`foreignObject`); an invalid one fails the package. Without `icon`, the
plugin gets the generic plugin icon. `icon` is new in API 1.2: IDEs before it
refuse the manifest, so a package with one declares `engines.openidea = "^1.2"`
(`check` and installing refuse it otherwise).
All paths are relative to the package directory and may not leave it. A
manifest is validated as a whole: if one contribution is invalid, nothing is
installed or loaded. Contribution types the IDE does not know (a newer API) are
@@ -146,7 +136,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`), `view?`, `command`, `when?` | no |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `tools`), `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
@@ -155,25 +145,6 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
A `viewItem.context` menu needs `view`, the id of one of the plugin's own
views. It adds the commands to the right-click menu of the items in that
view's `tree` or `list`, and each command gets the item's key as its argument.
`when` clauses can use `viewItem` (the key) and `viewItemKind` (the key up to
its first `:`, so `pod` for `pod:default/nginx`; the whole key when it has no
`:`). Only the menu's `when` sees them, not the command's own `when`; a command
whose `when` is false shows greyed out. Other menus refuse `view`, a web view
has no item menu, and no menu opens when no declaration matches the item.
The menu is new in API 1.2, so a plugin using it declares
`engines.openidea = "^1.2"`. For example:
```toml
[[contributes.menus]]
menu = "viewItem.context"
view = "pods"
command = "kube.logs"
when = "viewItemKind == pod"
```
Declared contributions are live as soon as the plugin is enabled — commands
show in Find Action, menus and the status bar, shortcuts work, themes and icon
themes can be applied, settings pages are there — **before** any plugin code
@@ -187,10 +158,6 @@ The path is exact (no globs) and relative to the project root; in a workspace th
key is true when any of its projects contains the path. It updates when
files change. An IDE that doesn't know the key treats it as
false: the plugin still installs and the key reads as false there.
Plugins can set their own keys, `plugin.<id>.<key>`, with `host::set_context`:
a key set from a command or event applies to that window, one set outside any
applies to every window, and a window's value wins over the global one. Keys are
kept across a window reload and idle reclaim, and dropped when the plugin stops.
### Background associations
@@ -353,27 +320,22 @@ then run `openidea-plugin check`.
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Asks the user to pick from `PickItem`s and waits: the chosen key(s), or `None` when dismissed. Only from a command or event of a window (else `invalid`); the wait isn't charged to the time limit. |
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. |
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
`run-command` receives an optional string argument: `executeAction("plugin.<plugin id>.<command id>", "arg")`
from another feature, or nothing when run from Search Everywhere / a shortcut. `ctx.selected_paths()` lists the files and folders a Project view or editor tab menu ran the command on (the argument is the first of them); it is empty otherwise. No capability is needed.
from another feature, or nothing when run from Search Everywhere / a shortcut.
### Events
+1 -1
Переглянути файл
@@ -1 +1 @@
fd5d8c0b9c6828bbeb0a93e394a0468abe83f051d1c20e50a7ac91fe12d5ab68
5a707c0a9efb6f98f43d93f1b4207cc0ab21ac84d693e0fd9981d143e7552a1c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
eb4d8c5d84dd2ea0171297f756cdf56bf72d3db88b8f4736bc2b3ab8346bd5eb
34728307b2054d6a494040f0523caf6f62b96c0f67f5b5e9a7e4508370e79419
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5db8c9213f6bef54f92c39c994717c8dfd4623a46b615293fe10b7a2990014a9
c8de2df9607fef2a7e75023e78db06ac83de8598a43632b684756d4e0df6b51b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b95b4b5c2e4451e670d1b013ad03662469456de03fabdbd8a3c62eccd93fb0f0
2523894a6fb5a75d29429ab096fdd9acf150c05eb4ea13c9e92920c8d8ca4459
+1 -1
Переглянути файл
@@ -1 +1 @@
6b800f268041ebb169117dfa31eead60315f51ebd92e409751f2670c92eac473
b534a088809e38ff210ed169b6968f3e793fa0fdcb12d022d2bcee5a58834514
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6a2c0c1f354b9c8defbcc9ec4a098fd956991dfb656ef2a4df92a219e60102d7
145bad8868c73368d4e83087861293fad309aaa87263bb12508a6acf693c25da
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
341466108d3a98c295a33d56c6f2a11736ced33dc0c4358d395cb376c24be663
f2f4a7d3fbe4b86369e35969782dd66150df6ae4451e375122d3c1b232caeac1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a6d1331afb12c8b215d8dc4450b8c4a424a6951b359dadb925da5ef0c52ecedc
c29594e55d321ee5240f8f61223d72c9095695a5b19ff1f8a25c5a6402a4a736
+22 -247
Переглянути файл
@@ -70,156 +70,6 @@ fn ident(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// The index just past the string or char literal opening at `bytes[i]`.
fn skip_string(bytes: &[u8], mut i: usize) -> usize {
let quote = bytes[i];
i += 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b if b == quote => return i + 1,
_ => i += 1,
}
}
i
}
/// The index just past the `//…` or `/*…*/` comment opening at `bytes[i]`.
fn skip_comment(bytes: &[u8], mut i: usize) -> usize {
if bytes.get(i + 1) == Some(&b'/') {
bytes[i + 2..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + 2 + n)
} else {
i += 2;
while i + 1 < bytes.len() && (bytes[i] != b'*' || bytes[i + 1] != b'/') {
i += 1;
}
(i + 2).min(bytes.len())
}
}
/// A method declaration in a fragment of an interface's body: the name's byte
/// range and its parameter list's `(` and `)` (offsets in the fragment).
#[derive(Debug, PartialEq, Eq)]
struct Declaration {
name: (usize, usize),
parens: (usize, usize),
}
/// The method declaration in `stmt`, skipping comments, strings and annotations
/// on the way: an annotation's arguments nest parentheses and may hold strings
/// and comments, so the name is the identifier before the first `(` left over —
/// `@Select("…") User find(…)` names `find`, not `Select`. Anything past that
/// `(` (where `@Param(…)` lives) only matters for its matching `)`, so it never
/// confuses the scan.
fn scan_declaration(stmt: &str) -> Option<Declaration> {
let bytes = stmt.as_bytes();
let mut i = 0;
let mut nested = 0usize; // paren depth inside an annotation's arguments
while i < bytes.len() {
match bytes[i] {
b' ' | b'\t' | b'\r' | b'\n' => i += 1,
b'/' if matches!(bytes.get(i + 1), Some(b'/' | b'*')) => i = skip_comment(bytes, i),
b'"' | b'\'' => i = skip_string(bytes, i),
b'@' if nested == 0 => {
// The annotation's qualified name, then (optionally) its arguments.
i += 1;
while i < bytes.len() && (ident(bytes[i] as char) || bytes[i] == b'.') {
i += 1;
}
let mut j = i;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'(') {
nested = 1;
i = j + 1;
}
}
b'(' if nested > 0 => {
nested += 1;
i += 1;
}
b')' if nested > 0 => {
nested -= 1;
i += 1;
}
b'(' => {
let before = stmt[..i].trim_end();
let start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1);
if start == before.len() {
return None;
}
// The matching `)`, minding strings and nested parens.
let (mut close, mut depth) = (i + 1, 1usize);
while close < bytes.len() {
match bytes[close] {
b'"' | b'\'' => close = skip_string(bytes, close),
b'/' if matches!(bytes.get(close + 1), Some(b'/' | b'*')) => close = skip_comment(bytes, close),
b'(' => {
depth += 1;
close += 1;
}
b')' => {
depth -= 1;
if depth == 0 {
return Some(Declaration { name: (start, before.len()), parens: (i, close) });
}
close += 1;
}
_ => close += 1,
}
}
return None; // an unterminated parameter list is no declaration
}
_ => i += 1,
}
}
None
}
/// The parameter names in a declaration's parameter list: `@Param("…")` wins,
/// otherwise the parameter's last identifier. Split at commas outside nested
/// parens, braces, brackets and strings, so `@Size(min = 1, max = 5) String n`
/// stays one parameter and a `@Param("a,b")` keeps its whole name.
fn params_of(list: &str) -> Vec<String> {
let bytes = list.as_bytes();
let mut parts = Vec::new();
let (mut depth, mut start) = (0usize, 0usize);
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' | b'\'' => i = skip_string(bytes, i),
b'/' if matches!(bytes.get(i + 1), Some(b'/' | b'*')) => i = skip_comment(bytes, i),
b'(' | b'{' | b'[' => {
depth += 1;
i += 1;
}
b')' | b'}' | b']' => {
depth = depth.saturating_sub(1);
i += 1;
}
b',' if depth == 0 => {
parts.push(&list[start..i]);
start = i + 1;
i += 1;
}
_ => i += 1,
}
}
parts.push(&list[start..]);
parts
.into_iter()
.filter_map(|p| {
// `@Param("id") long id` → the @Param name wins.
if let Some(q) = p.find("@Param(\"") {
return p[q + 8..].split('"').next().map(str::to_owned);
}
p.split_whitespace().last().map(|n| n.trim_matches(|c: char| !ident(c)).to_owned())
})
.filter(|n| !n.is_empty())
.collect()
}
/// The interface's name and methods (with their parameter names).
pub fn parse_java(text: &str) -> MapperJava {
let package =
@@ -245,14 +95,28 @@ pub fn parse_java(text: &str) -> MapperJava {
}
';' if depth == 0 => {
let stmt = &text[stmt_start..k];
if let Some(decl) = scan_declaration(stmt)
&& !stmt[..decl.parens.0].contains(" default ")
{
let (s, e) = (stmt_start + decl.name.0, stmt_start + decl.name.1);
methods.push((
Named { name: stmt[decl.name.0..decl.name.1].to_owned(), range: range_of(text, s, e) },
params_of(&stmt[decl.parens.0 + 1..decl.parens.1]),
));
if let Some(paren) = stmt.find('(') {
let before = stmt[..paren].trim_end();
let name_start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1);
let method = &before[name_start..];
if !method.is_empty() && !before.contains(" default ") {
let s = stmt_start + name_start;
let params = stmt[paren + 1..stmt.rfind(')').unwrap_or(stmt.len())]
.split(',')
.filter_map(|p| {
// `@Param("id") long id` → the @Param name wins.
if let Some(q) = p.find("@Param(\"") {
return p[q + 8..].split('"').next().map(str::to_owned);
}
p.split_whitespace().last().map(|n| n.trim_matches(|c: char| !ident(c)).to_owned())
})
.filter(|n| !n.is_empty())
.collect();
methods.push((
Named { name: method.to_owned(), range: range_of(text, s, s + method.len()) },
params,
));
}
}
stmt_start = k + 1;
}
@@ -463,22 +327,6 @@ mod tests {
assert_eq!(xml.statements[0].range, Range::new(Position::new(2, 14), Position::new(2, 22)));
}
const ANNOTATED: &str = concat!(
"package com.acme;\n\n",
"import org.apache.ibatis.annotations.Param;\n\n",
"public interface UserMapper {\n",
" @Select(\"SELECT (a, b) FROM users WHERE c = ')' OR d = 'x, y'\")\n",
" List<User> selectAnnotated(Long id);\n\n",
" @Cacheable(key = @Key(value = \"x(y)\", of = {@Part(\"a)b\"), @Part(\"c,d\")}))\n",
" @Override\n",
" // a comment (with parens) before the name\n",
" User findAnnotated(@Param(\"id\") Long id, @Size(min = 1, max = 5) String name);\n\n",
" List<User> selectPlain(Long id);\n",
"}\n"
);
const ANNOTATED_XML: &str = "<?xml version=\"1.0\"?>\n<mapper namespace=\"com.acme.UserMapper\">\n <select id=\"selectAnnotated\" resultType=\"User\">SELECT (a, b) FROM users</select>\n <select id=\"findAnnotated\">SELECT 1</select>\n</mapper>\n";
fn setup() -> MockHost {
let host = MockHost::install();
host.add_file("src/main/java/com/acme/UserMapper.java", JAVA);
@@ -487,68 +335,6 @@ mod tests {
host
}
fn annotated_setup() -> MockHost {
let host = MockHost::install();
host.add_file("src/main/java/com/acme/UserMapper.java", ANNOTATED);
host.add_file("src/main/resources/mapper/UserMapper.xml", ANNOTATED_XML);
host.add_file("pom.xml", "<project/>");
host
}
/// Methods behind method-level annotations keep their names, parameters and
/// positions: the scanner skips comments, strings and annotation arguments
/// (nested annotations, `(` `)` `{` `}` `,` in strings) before the name.
#[test]
fn parses_methods_with_annotations() {
let java = parse_java(ANNOTATED);
let names: Vec<_> = java.methods.iter().map(|(m, p)| (m.name.as_str(), p.clone())).collect();
assert_eq!(
names,
[
("selectAnnotated", vec!["id".to_owned()]),
("findAnnotated", vec!["id".to_owned(), "name".to_owned()],),
("selectPlain", vec!["id".to_owned()])
],
"annotation names must not become method names, @Param wins, argument commas must not split a parameter"
);
// ` List<User> ` before the name on its line (UTF-16 columns).
assert_eq!(java.methods[0].0.range, Range::new(Position::new(6, 15), Position::new(6, 30)));
assert_eq!(java.methods[1].0.range, Range::new(Position::new(11, 9), Position::new(11, 22)));
}
/// A multibyte annotation string on the name's line keeps UTF-16 columns:
/// `中文` is one unit each and `😀` two, while bytes would run ahead.
#[test]
fn keeps_utf16_columns_around_multibyte_annotations() {
let text = "package com.acme;\n\npublic interface UserMapper {\n @Select(\"中文 😀 注释\") List<User> find(Long id);\n}\n";
let java = parse_java(text);
assert_eq!(java.methods.len(), 1);
assert_eq!(java.methods[0].0.name, "find");
// `"中文 😀 注释"` costs 10 UTF-16 units (😀 two); `find` starts at 4 + 8 + 1 + 10 + 1 + 11 = 35.
assert_eq!(java.methods[0].0.range, Range::new(Position::new(3, 35), Position::new(3, 39)));
assert_eq!(java.methods[0].1, ["id".to_owned()]);
}
/// Annotated methods still get both directions of navigation.
#[test]
fn navigates_annotated_methods() {
let _host = annotated_setup();
let mut n = Navigator::default();
let java = doc("/project/src/main/java/com/acme/UserMapper.java", "java", ANNOTATED);
let markers = n.line_markers(&java);
assert_eq!(markers.iter().map(|m| m.line).collect::<Vec<_>>(), [6, 11], "selectPlain has no statement");
assert_eq!(markers[1].tooltip, "Go to UserMapper.xml: findAnnotated");
let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", ANNOTATED_XML);
let to_java = n.definition(&xml, Position::new(2, 20));
assert_eq!(to_java.len(), 1);
assert_eq!(
(to_java[0].path.ends_with("UserMapper.java"), to_java[0].range.start),
(true, Position::new(6, 15)),
"the XML statement jumps back to the annotated method"
);
}
fn doc(path: &str, language: &str, text: &str) -> Document {
Document { path: path.into(), language: language.into(), version: 1, text: text.into() }
}
@@ -575,17 +361,6 @@ mod tests {
assert_eq!(n.line_markers(&xml)[0].tooltip, "Go to UserMapper.findById()");
}
#[test]
fn method_annotations_do_not_swallow_the_method_name() {
// A method-level annotation with arguments: `stmt.find('(')` would land
// inside `@DataPermission(…)` and read `DataPermission` as the name.
let java = parse_java(
"package com.acme;\n\npublic interface SecuredMapper {\n @DataPermission(column = \"id\", scope = (@Scope(\"self\")))\n List<User> findAll(@Param(\"org\") String org);\n\n @org.acme.Check(value = \"(nested)\")\n int count();\n}\n",
);
let names: Vec<_> = java.methods.iter().map(|(m, p)| (m.name.as_str(), p.clone())).collect();
assert_eq!(names, [("findAll", vec!["org".to_owned()]), ("count", Vec::<String>::new())]);
}
#[test]
fn completes_ids_and_parameters() {
let _host = setup();
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff. Show more