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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 961344c0f9 fix(debugger): run debug adapters on the tool search path
Debug adapters were found on the tool search path but ran with the
app's own PATH. When the login shell's PATH didn't reach the app, what an
adapter starts in turn was missing although Run found it: js-debug's
wrapper failed with "exec: node: not found", and Delve's go build with
"exec: go: executable file not found in $PATH". Adapters now get the
search path language servers get, unless the launch sets its own PATH
(a selected SDK's bin first), and adapter binaries are resolved on it.

Fixes #1690
Fixes #1707
2026-11-06 14:40:08 +08:00
139 змінених файлів з 1458 додано та 6139 видалено

No files matched your search

+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"));
}
}
-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",
+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());
}
+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 -27
Переглянути файл
@@ -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,
@@ -1532,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
@@ -1555,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,
});
@@ -1650,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!(
@@ -1700,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,
@@ -1750,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),
};
@@ -2105,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);
@@ -2172,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),
@@ -2282,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,
+1 -1
Переглянути файл
@@ -124,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())
}
-3
Переглянути файл
@@ -1,7 +1,6 @@
//! 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, StatusItem, WorkbenchEvent};
use serde::{Deserialize, Serialize};
@@ -51,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,
@@ -115,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,
+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());
}
-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()?;
+1 -24
Переглянути файл
@@ -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;
@@ -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"));
-122
Переглянути файл
@@ -668,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);
@@ -1935,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.
@@ -2674,61 +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")));
}
/// 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:?}");
}
-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] {
+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")));
}
+6 -4
Переглянути файл
@@ -948,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();
-37
Переглянути файл
@@ -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();
+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"));
}
}
+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 -30
Переглянути файл
@@ -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
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5e7f7adc2c49503d2278ed2a446f18f69561ce51df264100f77f50d69804c277
c29594e55d321ee5240f8f61223d72c9095695a5b19ff1f8a25c5a6402a4a736
+1 -57
Переглянути файл
@@ -70,51 +70,6 @@ fn ident(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// Index of the `(` opening a method's parameter list inside a declaration
/// fragment. `(`s that belong to annotation arguments — `@Anno(…)` — are
/// skipped so `@DataPermission(column = "id") int count()` finds the paren
/// after `count`, not the one after `DataPermission`.
fn method_paren(stmt: &str) -> Option<usize> {
let mut rest = stmt;
let mut base = 0;
while let Some(i) = rest.find('(') {
// Is the token right before this `(` an annotation name (`@Anno`, `@a.b.Anno`)?
let before = rest[..i].trim_end();
let annotation = before.rfind('@').is_some_and(|a| before[a + 1..].chars().all(|c| ident(c) || c == '.'));
if !annotation {
return Some(base + i);
}
// Skip the annotation's argument list (it may nest and hold literals).
let mut depth = 1usize;
let mut end = None;
let mut chars = rest[i + 1..].char_indices().peekable();
while let Some((j, c)) = chars.next() {
match c {
'"' | '\'' => {
for (_, d) in chars.by_ref() {
if d == c {
break;
}
}
}
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = Some(i + 1 + j + 1);
break;
}
}
_ => {}
}
}
let skip = end?;
base += skip;
rest = &rest[skip..];
}
None
}
/// The interface's name and methods (with their parameter names).
pub fn parse_java(text: &str) -> MapperJava {
let package =
@@ -140,7 +95,7 @@ pub fn parse_java(text: &str) -> MapperJava {
}
';' if depth == 0 => {
let stmt = &text[stmt_start..k];
if let Some(paren) = method_paren(stmt) {
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..];
@@ -406,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();
+1 -1
Переглянути файл
@@ -109,7 +109,7 @@ afterEach(() => {
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
if (base) rmSync(base, { recursive: true, force: true });
});
async function open(c: Case): Promise<string> {
+1 -1
Переглянути файл
@@ -133,7 +133,7 @@ afterEach(() => {
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
if (base) rmSync(base, { recursive: true, force: true });
});
async function open(c: Case): Promise<string> {
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ pub fn observe(app: &tauri::AppHandle) {
}
}
pub(crate) fn application_active(app: &tauri::AppHandle) -> bool {
fn application_active(app: &tauri::AppHandle) -> bool {
// A settings window, utility window or native dialog is still this application.
#[cfg(target_os = "macos")]
{
-7
Переглянути файл
@@ -314,13 +314,6 @@ pub async fn project_trust_set(
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn project_trust_add_location(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
state.trust.add_location(&path)?;
state.host.refresh_project_trust().await
}
#[tauri::command]
#[specta::specta]
pub async fn project_trust_remove_location(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
+1 -10
Переглянути файл
@@ -136,13 +136,9 @@ pub async fn lsp_resolve_class_file(
/// 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)`.
/// leave it off. Cancel with `cancel_request(request)`.
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_references(
window: Window,
state: State<'_, AppState>,
@@ -151,10 +147,7 @@ pub async fn lsp_references(
pos: Pos,
include_declaration: bool,
project_wide: bool,
libraries: bool,
on_partial: tauri::ipc::Channel<References>,
) -> IdeResult<References> {
let on_partial = super::sender(on_partial);
ide_host::ops::lsp::lsp_references(
&state.host,
window.label(),
@@ -163,8 +156,6 @@ pub async fn lsp_references(
pos,
include_declaration,
project_wide,
libraries,
on_partial,
)
.await
}
-1
Переглянути файл
@@ -75,7 +75,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::project_trust_status,
app::project_trust_list,
app::project_trust_set,
app::project_trust_add_location,
app::project_trust_remove_location,
workspace::workspace_create,
workspace::workspace_attach,
+2 -6
Переглянути файл
@@ -20,12 +20,8 @@ pub async fn sdk_detect(window: Window, state: State<'_, AppState>, kind: SdkKin
/// The interpreter the project uses: the configured one, else its virtualenv.
#[tauri::command]
#[specta::specta]
pub fn sdk_python_effective(
window: Window,
state: State<'_, AppState>,
near: Option<PathBuf>,
) -> IdeResult<Option<ide_core::IpcPath>> {
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label(), near)
pub fn sdk_python_effective(window: Window, state: State<'_, AppState>) -> IdeResult<Option<ide_core::IpcPath>> {
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label())
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
+3 -6
Переглянути файл
@@ -214,9 +214,7 @@ pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
});
}
/// Sets the menu's labels / shortcut text and rebuilds it when they changed.
/// Focusing another project window re-pushes the same shared menu; an identical
/// config must not call `set_menu`, which redraws the macOS menu bar.
/// Sets the menu's labels / shortcut text (on locale or keymap change) and rebuilds it.
#[tauri::command]
#[specta::specta]
pub fn menu_configure(
@@ -225,9 +223,8 @@ pub fn menu_configure(
state: State<'_, AppState>,
config: MenuConfig,
) {
if menu::store_config(&menu_state, config) {
menu::install(&app, &menu_state, &state.recent.list());
}
*menu_state.config.lock() = config;
menu::install(&app, &menu_state, &state.recent.list());
}
/// Rebuilds the menu (e.g. after the recent-projects list changed).
+1 -24
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{EventSink, IdeEvent};
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
use tauri::{AppHandle, Emitter};
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
pub const IDE_EVENT: &str = "ide://event";
@@ -38,31 +38,8 @@ pub struct TauriSink {
pub window: Option<String>,
}
/// A debug session stopped on a breakpoint: bounce/flash the taskbar icon
/// (IDEA) unless the user is already looking at an OpenIDEA window. The focus
/// check and the request both touch the windowing system, so they run on the
/// main thread; `emit` itself can come from any debug worker thread.
fn flash_taskbar_unless_focused(app: &AppHandle) {
let handle = app.clone();
let _ = app.run_on_main_thread(move || {
if crate::application_focus::application_active(&handle) {
return;
}
for window in handle.webview_windows().values() {
let _ = window.request_user_attention(Some(UserAttentionType::Informational));
}
});
}
impl EventSink for TauriSink {
fn emit(&self, event: IdeEvent) {
if matches!(
&event,
IdeEvent::Debug { event: ide_core::event::DebugEvent::Stopped { reason, .. }, .. }
if matches!(reason.as_str(), "breakpoint" | "function breakpoint")
) {
flash_taskbar_unless_focused(&self.app);
}
let result = match &self.window {
Some(label) => {
for target in crate::windows::document_windows(&self.app, label) {
+1 -8
Переглянути файл
@@ -174,8 +174,6 @@ pub fn run() {
app.manage(windows);
app.manage(application_focus::ApplicationFocus::default());
#[cfg(target_os = "macos")]
macos::intercept_system_quit(app.handle());
#[cfg(target_os = "macos")]
application_focus::observe(app.handle());
app.manage(menu_state);
if let Some(paths) = setup_opens.lock().take() {
@@ -236,7 +234,6 @@ pub fn run() {
let _ = &early_opens;
if let tauri::RunEvent::Exit = event {
if let Some(state) = app.try_state::<AppState>() {
state.host.stop_processes_on_exit();
state.host.clear_workspace_edit_history_on_exit();
state.host.shutdown_notebooks_on_exit();
}
@@ -256,11 +253,7 @@ fn window_state_flags() -> tauri_plugin_window_state::StateFlags {
/// Routes IDE menu items to the focused window's frontend (`executeAction`).
fn on_menu_event(app: &tauri::AppHandle, event: tauri::menu::MenuEvent) {
dispatch_menu_action(app, event.id().as_ref());
}
/// Runs menu item `id` as if it were chosen: in the focused window's frontend, or here without one.
pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
let id = event.id().as_ref();
let Some(route) = menu::route(&menu::spec(menu::Os::current()), id) else { return };
match windows::target_window(app) {
Some(w) => {
+3 -127
Переглянути файл
@@ -7,9 +7,8 @@ use objc2::{
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
};
use objc2_app_kit::{NSWindow, NSWindowAnimationBehavior, NSWindowUserTabbingPreference};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSRect};
use std::cell::Cell;
use tauri::{AppHandle, Manager, WebviewWindow};
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
@@ -203,43 +202,6 @@ fn present(fullscreen: bool) {
NSApplication::sharedApplication(mtm).setPresentationOptions(options);
}
type ShouldTerminate = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> usize;
/// `NSApplicationTerminateReply`.
const TERMINATE_CANCEL: usize = 0;
const TERMINATE_NOW: usize = 1;
/// The Dock's Quit, the system's app menu and a logout ask the application delegate whether it
/// may terminate; tao's delegate doesn't answer, so AppKit terminated at once, past the exit,
/// running-process and unsaved-changes prompts. Answer it: cancel, and quit like Cmd+Q does.
pub fn intercept_system_quit(app: &AppHandle) {
let _ = APP.set(app.clone());
let Some(mtm) = MainThreadMarker::new() else { return };
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
unsafe {
let delegate: *mut AnyObject = objc2::msg_send![&*application, delegate];
if delegate.is_null() {
return;
}
let class = objc2::ffi::object_getClass(delegate.cast()) as *mut AnyClass;
let imp: Imp = std::mem::transmute(should_terminate as ShouldTerminate);
let added = objc2::ffi::class_addMethod(class, objc2::sel!(applicationShouldTerminate:), imp, c"Q@:@".as_ptr());
if !added.as_bool() {
tracing::warn!("could not handle applicationShouldTerminate:");
}
}
}
unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) -> usize {
let Some(app) = APP.get() else { return TERMINATE_NOW };
// Our own quit exits through the event loop; a system quit during it goes ahead.
if app.try_state::<WindowsState>().is_none_or(|w| w.quitting()) {
return TERMINATE_NOW;
}
crate::dispatch_menu_action(app, "app.quit");
TERMINATE_CANCEL
}
type ToggleFullScreen = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
static NATIVE_TOGGLE_FULLSCREEN: std::sync::OnceLock<ToggleFullScreen> = std::sync::OnceLock::new();
@@ -276,102 +238,16 @@ type ConstrainFrameRect = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, NSRec
static NATIVE_CONSTRAIN_FRAME_RECT: std::sync::OnceLock<ConstrainFrameRect> = std::sync::OnceLock::new();
thread_local! {
/// Native window whose next frame assignment must keep the rectangle it was given.
static EXACT_FRAME: Cell<usize> = const { Cell::new(0) };
}
struct ExactFrame(usize);
impl ExactFrame {
fn begin(native: usize) -> Self {
EXACT_FRAME.with(|slot| slot.set(native));
Self(native)
}
}
impl Drop for ExactFrame {
fn drop(&mut self) {
EXACT_FRAME.with(|slot| {
if slot.get() == self.0 {
slot.set(0);
}
});
}
}
/// Copies `from`'s frame onto `to`. `setFrame:display:animate:` finishes before it returns;
/// tao's position and size setters only schedule the change.
pub fn copy_window_frame(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
apply_window_frame(from, to, false)
}
/// Copies the frame and orders `to` front before AppKit can animate or constrain it.
/// A later `show` runs `constrainFrameRect:toScreen:` and slides a titled window into place.
pub fn present_window_frame(from: &WebviewWindow, to: &WebviewWindow) -> tauri::Result<()> {
apply_window_frame(from, to, true)
}
fn apply_window_frame(from: &WebviewWindow, to: &WebviewWindow, show: bool) -> tauri::Result<()> {
if MainThreadMarker::new().is_some() {
return apply_window_frame_on_main(from, to, show);
}
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let from = from.clone();
let to = to.clone();
to.clone().run_on_main_thread(move || {
let _ = tx.send(apply_window_frame_on_main(&from, &to, show));
})?;
rx.recv().map_err(|error| tauri::Error::Io(std::io::Error::other(error.to_string())))?
}
fn apply_window_frame_on_main(from: &WebviewWindow, to: &WebviewWindow, show: bool) -> tauri::Result<()> {
let source_pointer = from.ns_window()?;
let target_pointer = to.ns_window()?;
unsafe {
let source = &*source_pointer.cast::<NSWindow>();
let target = &*target_pointer.cast::<NSWindow>();
let frame = source.frame();
let current = target.frame();
let differs = frame.origin.x != current.origin.x
|| frame.origin.y != current.origin.y
|| frame.size.width != current.size.width
|| frame.size.height != current.size.height;
if !differs && !show {
return Ok(());
}
// Zoom and ordering use the window's animation behavior. `animate: false` alone does not
// stop a zoomed window from sliding to the new frame as it is shown.
let behavior = target.animationBehavior();
target.setAnimationBehavior(NSWindowAnimationBehavior::None);
let result = (|| {
let _exact = ExactFrame::begin(target_pointer as usize);
if differs {
target.setFrame_display_animate(frame, false, false);
}
if show {
to.show()?;
to.set_focus()?;
}
Ok(())
})();
target.setAnimationBehavior(behavior);
result
}
}
/// AppKit keeps a titled window's top edge below the menu bar, and on a notched display below the
/// camera housing, whenever the window is placed, shown or resized. A window in simple fullscreen
/// is titled for its buttons but must still cover the whole screen. A group-tab frame copy also
/// keeps the rectangle it was given, so the window about to be shown is not shifted.
/// is titled for its buttons but must still cover the whole screen.
unsafe extern "C-unwind" fn constrain_frame_rect(
this: *mut AnyObject,
selector: Sel,
frame: NSRect,
screen: *mut AnyObject,
) -> NSRect {
let exact = EXACT_FRAME.with(|slot| slot.get() == this as usize);
if exact || COVERING.with_borrow(|windows| windows.values().any(|covering| covering.native == this as usize)) {
if COVERING.with_borrow(|windows| windows.values().any(|covering| covering.native == this as usize)) {
return frame;
}
match NATIVE_CONSTRAIN_FRAME_RECT.get() {
+1 -22
Переглянути файл
@@ -895,7 +895,7 @@ pub fn action_ids(spec: &[Entry]) -> Vec<&'static str> {
}
/// Localised labels and displayed shortcuts, pushed by the frontend.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MenuConfig {
pub locale: String,
@@ -961,17 +961,6 @@ pub struct MenuState {
pub disabled: Mutex<HashSet<String>>,
}
/// Stores `next` when it differs from the config last used to build the menu.
/// Callers must not replace the menu on `false`: `set_menu` redraws the macOS menu bar.
pub fn store_config(state: &MenuState, next: MenuConfig) -> bool {
let mut current = state.config.lock();
if *current == next {
return false;
}
*current = next;
true
}
/// The action an item id stands for, if it is an IDE action item.
fn item_action(id: &str) -> Option<&str> {
if id.starts_with(RECENT_PREFIX) || id == "recent.none" || id.starts_with("submenu:") {
@@ -1278,16 +1267,6 @@ mod tests {
}
}
#[test]
fn unchanged_menu_config_is_not_rebuilt() {
let state = MenuState::default();
let mut config = MenuConfig { locale: "en".into(), ..MenuConfig::default() };
assert!(store_config(&state, config.clone()));
assert!(!store_config(&state, config.clone()));
config.labels.insert("menu.file".into(), "File".into());
assert!(store_config(&state, config));
}
#[test]
fn recent_items_route_to_open_recent_with_path() {
let spec = spec(Os::Mac);
+54 -196
Переглянути файл
@@ -56,76 +56,30 @@ fn changed(app: &AppHandle) {
app.state::<AppState>().sink.emit(IdeEvent::WindowGroupsChanged);
}
/// Outer frame in physical pixels. A maximized window is represented by the rectangle it
/// occupies, not by the maximized flag: that flag can match while the rectangles do not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct OuterFrame {
x: i32,
y: i32,
width: u32,
height: u32,
}
/// Where a group member can be placed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FrameHost {
/// The client can move and resize the window.
Desktop,
/// Wayland does not let clients place top-level windows.
#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
Wayland,
/// macOS simple fullscreen already covers the screen; rewriting the frame would shrink it.
SimpleFullscreen,
/// Native fullscreen owns a Space. A different frame is transferred, not assigned.
NativeFullscreen,
}
/// What to write before the target window is shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FrameWrite {
/// Already the same rectangle, or this host must not be placed.
Leave,
TransferFullscreen,
Assign(OuterFrame),
}
/// Two windows are aligned only when their outer rectangles match. Maximized or fullscreen
/// flags are not a substitute: `show` presents the current rectangle, and a later move is visible.
fn frame_write(host: FrameHost, from: OuterFrame, to: OuterFrame) -> FrameWrite {
match host {
FrameHost::Wayland | FrameHost::SimpleFullscreen => FrameWrite::Leave,
FrameHost::NativeFullscreen if from == to => FrameWrite::Leave,
FrameHost::NativeFullscreen => FrameWrite::TransferFullscreen,
FrameHost::Desktop if from == to => FrameWrite::Leave,
FrameHost::Desktop => FrameWrite::Assign(from),
/// Whether `to` already presents `from`'s frame, so moving it would only make it flicker.
fn same_frame(from: &WebviewWindow, to: &WebviewWindow) -> bool {
let (Ok(from_max), Ok(to_max)) = (from.is_maximized(), to.is_maximized()) else { return false };
let (Ok(from_full), Ok(to_full)) = (from.is_fullscreen(), to.is_fullscreen()) else { return false };
if from_max != to_max || from_full != to_full {
return false;
}
}
fn outer_frame(window: &WebviewWindow) -> IdeResult<OuterFrame> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
let position = window.outer_position().map_err(err)?;
let size = window.outer_size().map_err(err)?;
Ok(OuterFrame { x: position.x, y: position.y, width: size.width, height: size.height })
}
fn frame_host(from: &WebviewWindow) -> IdeResult<FrameHost> {
if simple_fullscreen(from.label()) {
return Ok(FrameHost::SimpleFullscreen);
let same_monitor = match (from.current_monitor(), to.current_monitor()) {
(Ok(Some(a)), Ok(Some(b))) => a.position() == b.position() && a.size() == b.size(),
// An unmapped window may not report a monitor; treat only equal states as matching.
(Ok(None), Ok(None)) | (Err(_), Err(_)) => true,
_ => false,
};
if !same_monitor {
return false;
}
#[cfg(target_os = "linux")]
if crate::linux_window_state::is_wayland() {
return Ok(FrameHost::Wayland);
}
if from.is_fullscreen().map_err(|error| IdeError::internal(error.to_string()))? {
return Ok(FrameHost::NativeFullscreen);
}
Ok(FrameHost::Desktop)
from_full
|| from_max
|| (from.outer_position().ok() == to.outer_position().ok() && from.inner_size().ok() == to.inner_size().ok())
}
/// Moves a hidden window onto `from`'s monitor. A restored window keeps its normal position on
/// the monitor it last occupied; maximizing or going fullscreen there would make the window
/// visibly jump across displays when its tab is selected. macOS copies the AppKit frame instead.
#[cfg(not(target_os = "macos"))]
/// visibly jump across displays when its tab is selected.
fn place_on_monitor(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
// Wayland does not let clients place top-level windows; maximizing stays on that output.
#[cfg(target_os = "linux")]
@@ -139,91 +93,47 @@ fn place_on_monitor(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
Ok(())
}
/// Gives `to` the source window's outer frame before `to` is shown.
///
/// Tauri's position, size and maximize calls are queued. On macOS the AppKit calls return
/// before the frame changes, while `show` orders the window front immediately, so the old
/// rectangle appears and then jumps. The frame is written synchronously instead.
fn copy_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let host = frame_host(from)?;
if matches!(host, FrameHost::Wayland | FrameHost::SimpleFullscreen) {
if same_frame(from, to) {
return Ok(());
}
// Tauri's physical rectangles round through the scale factor. On macOS the AppKit frame is
// the one `show` will present, so compare that instead of skipping a real difference.
#[cfg(target_os = "macos")]
if host == FrameHost::Desktop {
return crate::macos::copy_window_frame(from, to).map_err(|error| IdeError::internal(error.to_string()));
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let fullscreen = from.is_fullscreen().map_err(err)?;
if fullscreen {
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
to.set_fullscreen(false).map_err(err)?;
place_on_monitor(from, to)?;
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
}
return Ok(());
}
match frame_write(host, outer_frame(from)?, outer_frame(to)?) {
FrameWrite::Leave => Ok(()),
FrameWrite::TransferFullscreen => transfer_native_fullscreen(from, to),
FrameWrite::Assign(frame) => assign_outer_frame(from, to, frame),
}
}
fn transfer_native_fullscreen(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
#[cfg(target_os = "macos")]
crate::macos::transfer_fullscreen(from, to).map_err(err)?;
#[cfg(not(target_os = "macos"))]
{
to.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(false).map_err(err)?;
let maximized = from.is_maximized().map_err(err)?;
if !maximized {
to.unmaximize().map_err(err)?;
to.set_position(from.outer_position().map_err(err)?).map_err(err)?;
// `set_size` excludes GTK's CSD shadow, which tao's inner size includes on Wayland.
#[cfg(target_os = "linux")]
let size = crate::linux_window_state::content_size(&from.as_ref().window()).map_err(err)?;
#[cfg(not(target_os = "linux"))]
let size = from.inner_size().map_err(err)?;
#[cfg(target_os = "linux")]
crate::linux_window_state::normal_size_requested(to.app_handle(), to.label(), size);
to.set_size(size).map_err(err)?;
} else {
// Maximize the target on the source's monitor, not on the monitor it happened to
// occupy while hidden.
to.unmaximize().map_err(err)?;
place_on_monitor(from, to)?;
from.set_fullscreen(false).map_err(err)?;
to.set_fullscreen(true).map_err(err)?;
to.maximize().map_err(err)?;
}
Ok(())
}
fn assign_outer_frame(from: &WebviewWindow, to: &WebviewWindow, _frame: OuterFrame) -> IdeResult<()> {
#[cfg(target_os = "macos")]
{
crate::macos::copy_window_frame(from, to).map_err(|error| IdeError::internal(error.to_string()))
}
#[cfg(not(target_os = "macos"))]
{
let err = |error: tauri::Error| IdeError::internal(error.to_string());
to.set_fullscreen(false).map_err(err)?;
if from.is_maximized().map_err(err)? {
// Maximize on the source's monitor. The rectangles differed, so the maximized flags
// alone are not enough; a hidden peer would otherwise appear at its old size.
to.unmaximize().map_err(err)?;
place_on_monitor(from, to)?;
to.maximize().map_err(err)?;
} else {
to.unmaximize().map_err(err)?;
to.set_position(from.outer_position().map_err(err)?).map_err(err)?;
// `set_size` excludes GTK's CSD shadow, which tao's inner size includes on Wayland.
#[cfg(target_os = "linux")]
let size = crate::linux_window_state::content_size(&from.as_ref().window()).map_err(err)?;
#[cfg(not(target_os = "linux"))]
let size = from.inner_size().map_err(err)?;
#[cfg(target_os = "linux")]
crate::linux_window_state::normal_size_requested(to.app_handle(), to.label(), size);
to.set_size(size).map_err(err)?;
}
Ok(())
}
}
/// Shows `to` in place of `from`, at `from`'s frame.
fn show_at_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
let err = |error: tauri::Error| IdeError::internal(error.to_string());
// Order the target front in the same AppKit turn as the frame write. A separate `show` runs
// after that turn and constrains the titled window, which is the jump. Native fullscreen is
// handed over by `copy_frame` instead.
#[cfg(target_os = "macos")]
if !from.is_fullscreen().map_err(err)? {
to.unminimize().map_err(err)?;
return crate::macos::present_window_frame(from, to).map_err(err);
}
copy_frame(from, to)?;
to.unminimize().map_err(err)?;
to.show().map_err(err)?;
to.set_focus().map_err(err)
}
/// Keeps hidden group members at the selected window's frame. Selecting a tab then only
/// changes which window is visible instead of moving or resizing one on screen.
fn sync_member_frames(app: &AppHandle, selected: &str) {
@@ -325,12 +235,11 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
&& previous.selected != target
&& let Some(from) = app.get_webview_window(&previous.selected)
{
show_at_frame(&from, &to)?;
} else {
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
to.show().map_err(|e| IdeError::internal(e.to_string()))?;
to.set_focus().map_err(|e| IdeError::internal(e.to_string()))?;
copy_frame(&from, &to)?;
}
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
to.show().map_err(|e| IdeError::internal(e.to_string()))?;
to.set_focus().map_err(|e| IdeError::internal(e.to_string()))?;
for member in &previous.members {
if member != target
&& let Some(window) = app.get_webview_window(member)
@@ -637,54 +546,3 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{FrameHost, FrameWrite, OuterFrame, frame_write};
fn frame(x: i32, y: i32, width: u32, height: u32) -> OuterFrame {
OuterFrame { x, y, width, height }
}
#[test]
fn matching_outer_rects_are_left_alone() {
let frame = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::Desktop, frame, frame), FrameWrite::Leave);
}
#[test]
fn a_different_outer_rect_is_assigned_before_the_window_is_shown() {
let from = frame(100, 80, 1200, 800);
let to = frame(40, 40, 900, 600);
assert_eq!(frame_write(FrameHost::Desktop, from, to), FrameWrite::Assign(from));
}
#[test]
fn maximized_windows_with_different_rects_still_assign() {
let from = frame(0, 25, 1728, 1055);
let to = frame(0, 25, 1512, 900);
assert_eq!(frame_write(FrameHost::Desktop, from, to), FrameWrite::Assign(from));
}
#[test]
fn simple_fullscreen_does_not_copy_a_frame() {
let from = frame(0, 0, 1728, 1117);
let to = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::SimpleFullscreen, from, to), FrameWrite::Leave);
}
#[test]
fn wayland_does_not_place_a_window() {
let from = frame(0, 0, 1200, 800);
let to = frame(10, 10, 800, 600);
assert_eq!(frame_write(FrameHost::Wayland, from, to), FrameWrite::Leave);
}
#[test]
fn native_fullscreen_transfers_only_when_the_rects_differ() {
let from = frame(0, 0, 1728, 1117);
let other = frame(100, 80, 1200, 800);
assert_eq!(frame_write(FrameHost::NativeFullscreen, from, from), FrameWrite::Leave);
assert_eq!(frame_write(FrameHost::NativeFullscreen, from, other), FrameWrite::TransferFullscreen);
}
}
+6 -37
Переглянути файл
@@ -28,7 +28,6 @@ export const commands = {
projectTrustStatus: (path: string) => typedError<TrustStatus, IdeError>(__TAURI_INVOKE("project_trust_status", { path })),
projectTrustList: () => typedError<TrustDecisions, IdeError>(__TAURI_INVOKE("project_trust_list")),
projectTrustSet: (path: string, trusted: boolean, folder: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_set", { path, trusted, folder })),
projectTrustAddLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_add_location", { path })),
projectTrustRemoveLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_remove_location", { path })),
workspaceCreate: (path: string, name: string, projects: string[]) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_create", { path, name, projects })),
workspaceAttach: (path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_attach", { path })),
@@ -425,12 +424,9 @@ export const commands = {
/**
* 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)`.
* leave it off. Cancel with `cancel_request(request)`.
*/
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean, libraries: boolean, onPartial: Channel<References>) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide, libraries, onPartial })),
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
lspWorkspaceSymbols: (request: RequestId, query: string) => typedError<WorkspaceSymbol[], IdeError>(__TAURI_INVOKE("lsp_workspace_symbols", { request, query })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
@@ -796,7 +792,7 @@ export const commands = {
/** Installed interpreters / toolchains of `kind`; project-local ones first. */
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
sdkPythonEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective")),
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
/** The PHP language level of the project `path` belongs to: the effective one and Auto's. */
@@ -901,11 +897,7 @@ export const commands = {
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
/** A window vetoed the quit (user cancelled its unsaved-changes prompt). */
appCancelQuit: () => __TAURI_INVOKE<void>("app_cancel_quit"),
/**
* Sets the menu's labels / shortcut text and rebuilds it when they changed.
* Focusing another project window re-pushes the same shared menu; an identical
* config must not call `set_menu`, which redraws the macOS menu bar.
*/
/** Sets the menu's labels / shortcut text (on locale or keymap change) and rebuilds it. */
menuConfigure: (config: MenuConfig) => __TAURI_INVOKE<void>("menu_configure", { config }),
/** Rebuilds the menu (e.g. after the recent-projects list changed). */
menuRefresh: () => __TAURI_INVOKE<void>("menu_refresh"),
@@ -2029,7 +2021,6 @@ export type CatalogPlugin = {
authors: string[],
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
/** Package directory; install with `install_from_dir(path)`. */
path: IpcPath,
hasCode: boolean,
@@ -2118,8 +2109,6 @@ export type ClassifiedReference = {
access?: ReferenceAccess | null,
location: Location,
kind: ReferenceKind,
/** The usage's line, when the server has it at hand (a library class's). */
text?: string | null,
};
export type ClearCachesResult = {
@@ -4424,11 +4413,6 @@ export type IndexEntry = {
engine?: string,
/** Marketplace categories (`CATEGORIES`); an IDE ignores those it doesn't know. */
categories?: string[],
/**
* The manifest's icon, sanitised by whoever wrote the index and again by
* the IDE before showing it.
*/
icon?: PluginIcon | null,
};
export type IndexStatus = {
@@ -5707,12 +5691,6 @@ export type PluginEvent =
/** Open `url` (`http(s)://`) in the system browser. */
{ type: "openUrl"; pluginId: string; url: string };
/** A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup. */
export type PluginIcon = {
light: string,
dark: string | null,
};
export type PluginInfo = {
id: string,
name: string,
@@ -5721,7 +5699,6 @@ export type PluginInfo = {
authors: string[],
homepage: string | null,
changeNotes: string | null,
icon: PluginIcon | null,
source: PluginSource,
/** Package directory. */
path: IpcPath,
@@ -6197,8 +6174,6 @@ export type References = {
classified?: ClassifiedReference[],
locations: Location[],
incomplete: ReferencesIncomplete | null,
/** The dependencies and the JDK were not searched (asked for without `libraries`). */
librariesSkipped?: boolean,
};
/** Why a references search may have missed usages. */
@@ -6495,10 +6470,7 @@ export type RunConfig_Serialize = {
export type RunExtras = RunExtras_Serialize | RunExtras_Deserialize;
export type RunExtras_Deserialize = {
/**
* 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. */
module?: string | null,
/** Values of the configuration type's own form fields (the command line derives from them). */
params?: { [key in string]: string },
@@ -6537,10 +6509,7 @@ export type RunExtras_Deserialize = {
};
export type RunExtras_Serialize = {
/**
* 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. */
module?: string | null,
/** Values of the configuration type's own form fields (the command line derives from them). */
params?: { [key in string]: string },
+3 -70
Переглянути файл
@@ -1,9 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { clipboardDocumentPath, clipboardFilesExtension, pasteEditorClipboard, pasteEditorText } from "./clipboard";
import { clipboardDocumentPath, clipboardFilesExtension, pasteEditorClipboard } from "./clipboard";
import { markdownImages } from "./markdownImages";
vi.mock("@/platform/remote", () => ({ isRemoteWindow: vi.fn(() => false) }));
@@ -204,70 +204,3 @@ it("does not insert into a read-only editor", async () => {
expect(view.state.doc.toString()).toBe("");
expect(list).not.toHaveBeenCalled();
});
describe("multi-caret paste", () => {
const view = (doc: string, ranges: Array<[number, number]>) => {
const v = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.create(
ranges.length > 1
? ranges.map(([from, to]) => EditorSelection.range(from, to))
: [EditorSelection.cursor(ranges[0]![0])],
),
extensions: EditorState.allowMultipleSelections.of(true),
}),
parent: document.body,
});
views.push(v);
return v;
};
it("pastes one line per caret when the counts match", () => {
const line = 'icjsdiocjosid "" cdscsd';
// A caret inside each pair of quotes (index 15), as in the issue.
const v = view(
Array(7).fill(line).join("\n"),
Array.from({ length: 7 }, (_, i) => {
const from = i * (line.length + 1) + 15;
return [from, from] as [number, number];
}),
);
pasteEditorText(v, "s\nd\nd\ns\nd\nd\ne");
expect(v.state.doc.toString()).toBe(
Array.from({ length: 7 }, (_, i) => `icjsdiocjosid "${"sddsdde"[i]}" cdscsd`).join("\n"),
);
});
it("keeps a trailing newline as the last caret's empty line (issue #1828)", () => {
const line = 'icjsdiocjosid "" cdscsd';
// Seven carets, six copied lines with a trailing newline: split keeps the
// empty seventh segment, so the last caret gets "" as the issue expects.
const v = view(
Array(7).fill(line).join("\n"),
Array.from({ length: 7 }, (_, i) => {
const from = i * (line.length + 1) + 15;
return [from, from] as [number, number];
}),
);
pasteEditorText(v, "s\nd\nd\ns\nd\nd\n");
expect(v.state.doc.toString()).toBe(
Array.from({ length: 7 }, (_, i) => `icjsdiocjosid "${"sddsdd"[i] ?? ""}" cdscsd`).join("\n"),
);
});
it("pastes the whole text at every caret when the counts differ", () => {
const v = view("a b", [
[1, 1],
[3, 3],
]);
pasteEditorText(v, "x\ny\nz");
expect(v.state.doc.toString()).toBe("ax\ny\nz bx\ny\nz");
});
it("pastes the whole text at a single caret", () => {
const v = view("a", [[1, 1]]);
pasteEditorText(v, "x\ny");
expect(v.state.doc.toString()).toBe("ax\ny");
});
});
+2 -28
Переглянути файл
@@ -1,4 +1,4 @@
import { EditorSelection, Facet, Prec } from "@codemirror/state";
import { Facet, Prec } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { isRemoteWindow } from "@/platform/remote";
@@ -13,35 +13,9 @@ function clipboardFileFormatter(view: EditorView): ((paths: string[]) => string)
: undefined;
}
/**
* The dispatch shared by every paste entry point. With several carets and a
* clipboard of exactly one line per caret, each caret gets its own line
* (JetBrains behavior): `"a\nb"` at two carets inserts `a` then `b`, not the
* block twice. Any other count pastes the full text at every caret.
* `userEvent` is `"input.paste"` unless the caller passes another (plain-text
* paste opts out of Reformat on Paste through `"input.pastePlain"`).
*/
export function dispatchPaste(view: EditorView, text: string, userEvent = "input.paste") {
const ranges = view.state.selection.ranges;
const lines = text.replace(/\r\n?/g, "\n").split("\n");
if (ranges.length > 1 && lines.length === ranges.length) {
let i = 0;
const spec = view.state.changeByRange((range) => {
const insert = lines[i++]!;
return {
changes: { from: range.from, to: range.to, insert },
range: EditorSelection.cursor(range.from + insert.length),
};
});
view.dispatch({ ...spec, userEvent, scrollIntoView: true });
} else {
view.dispatch(view.state.replaceSelection(text), { userEvent, scrollIntoView: true });
}
}
export function pasteEditorText(view: EditorView, text: string) {
if (!text || !view.dom.isConnected || view.state.readOnly) return;
dispatchPaste(view, text);
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
view.focus();
}
-2
Переглянути файл
@@ -18,7 +18,6 @@ export const findLocals = {
export const findStyles = {
".cm-openidea-findMatch": {
backgroundColor: "var(--editor-search)",
color: "var(--fg-search-match, inherit)",
borderRadius: "2px",
},
".cm-openidea-findExcluded": {
@@ -30,7 +29,6 @@ export const findStyles = {
},
".cm-openidea-findMatch-current": {
backgroundColor: "var(--editor-search-current)",
color: "var(--fg-search-match, inherit)",
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
},
};
+2 -3
Переглянути файл
@@ -6,7 +6,6 @@ import { offsetToPos, posToOffset } from "@/editor/lsp/positions";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { executeAction } from "@/platform/actions";
import { clipLabel, clipboardHistory, recordClipboard } from "./clipboardHistory";
import { dispatchPaste } from "./cm/clipboard";
import { unwrapOptions, type ChainNode, type UnwrapOption } from "./cm/unwrap";
import type { EditorSlot } from "./model/slot";
@@ -14,7 +13,7 @@ const hint = (text: string) => void executeAction("editor.showHint", { text });
export function pasteText(view: EditorView, text: string) {
if (view.state.readOnly) return;
dispatchPaste(view, text);
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
view.focus();
}
@@ -126,6 +125,6 @@ export async function pasteAsPlainText(view: EditorView) {
return;
}
if (!text) return;
dispatchPaste(view, text, "input.pastePlain");
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.pastePlain", scrollIntoView: true });
view.focus();
}
+1 -15
Переглянути файл
@@ -15,12 +15,6 @@ vi.mock("@/platform/ipc", async (orig) => {
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lspDoc } = await import("./lsp");
@@ -95,15 +89,7 @@ describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(
expect.any(Number),
7,
{ line: 0, col: 0 },
false,
false,
false,
expect.anything(),
);
expect(ipc.lspReferences).toHaveBeenCalledWith(expect.any(Number), 7, { line: 0, col: 0 }, false, false);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
+1 -10
Переглянути файл
@@ -5,7 +5,6 @@
* and symbol, and at most a few reference requests in flight. Beside each
* count, the declaration's last author from VCS blame (`authorLens`).
*/
import { Channel } from "@tauri-apps/api/core";
import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
@@ -196,15 +195,7 @@ class UsagesLensPlugin {
this.pending.add(request);
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
return commands.lspReferences(
request,
doc.doc,
{ line: t.line, col: t.col },
false,
false,
false,
new Channel(),
);
return commands.lspReferences(request, doc.doc, { line: t.line, col: t.col }, false, false);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete = true;
+8 -4
Переглянути файл
@@ -77,11 +77,15 @@ describe("Typo inspection", () => {
expect(diagnosticMarks(lint)).toEqual([]);
view.dispatch({ selection: { anchor: 5 } });
expect(spellingIntentions(view).map((i) => i.label)).toEqual(["Typo: Change to…", "Save 'mesage' to dictionary"]);
// IDEA's → menu: each dictionary level and the inspection's controls.
expect(spellingIntentions(view).map((i) => i.label)).toEqual([
"Typo: Change to…",
"Save 'mesage' to project-level dictionary",
"Save 'mesage' to application-level dictionary",
]);
// IDEA's → menu: the dictionaries and the inspection's controls.
expect(spellingIntentions(view)[0]!.submenu?.map((i) => ("label" in i ? i.label : "-"))).toEqual([
"Save to project-level dictionary",
"Save to application-level dictionary",
"Save 'mesage' to project-level dictionary",
"Save 'mesage' to application-level dictionary",
"-",
"Edit inspection profile setting",
"Disable inspection",
+12 -15
Переглянути файл
@@ -142,23 +142,26 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
const typo = typoAt(view.state, sel.head);
if (!typo) return [];
const hasProject = !!useProject.getState().project;
// One row saves to the project dictionary (application-level without a project);
// its submenu still offers each level, then the inspection controls.
const saveSubmenu: MenuItem[] = [
const saves: ListPopupItem[] = [
...(hasProject
? [
{
id: "spelling.saveProject",
label: "Save to project-level dictionary",
run: () => void saveToDictionary(typo.word, "project"),
label: tx`Save '${typo.word}' to project-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "project"),
},
]
: []),
{
id: "spelling.saveIde",
label: "Save to application-level dictionary",
run: () => void saveToDictionary(typo.word, "ide"),
label: tx`Save '${typo.word}' to application-level dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, "ide"),
},
];
const submenu: MenuItem[] = [
...saves.map((s) => ({ id: s.id, label: s.label, verbatim: true, run: () => void s.run() })),
{ kind: "separator" },
...intentionControls({ id: SPELLING_INSPECTION, name: "Typo" }),
];
@@ -169,15 +172,9 @@ export function spellingIntentions(view: EditorView): ListPopupItem[] {
icon: "bulb-fix",
emphasis: true,
run: () => changeTo(view, typo),
submenu: saveSubmenu,
},
{
id: "spelling.save",
label: tx`Save '${typo.word}' to dictionary`,
icon: "bulb-fix",
run: () => saveToDictionary(typo.word, hasProject ? "project" : "ide"),
submenu: saveSubmenu,
submenu,
},
...saves.map((s) => ({ ...s, submenu })),
];
}
-6
Переглянути файл
@@ -65,12 +65,6 @@ const showHint = vi.fn();
vi.mock("@/editor/lsp/hint", () => ({ showHint }));
const executeAction = vi.fn();
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
let answer = "cancel";
const ask = vi.fn(async (_request: MessageRequest) => ({ button: answer, checked: false }));
let confirmAnswer: { checked: boolean } | null = { checked: false };
+2 -11
Переглянути файл
@@ -10,7 +10,6 @@
* Files (project view): references to the file's top-level symbols from other
* files, when the language server can answer (`fileUsages`).
*/
import { Channel } from "@tauri-apps/api/core";
import type { EditorView } from "@codemirror/view";
import type { Text } from "@codemirror/state";
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
@@ -255,7 +254,7 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true, false, new Channel()),
commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true),
);
return refs.filter((l) => outside(l.path, l.range));
}
@@ -555,15 +554,7 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
// Every symbol of every file: the server's own scope (a project search each would be too slow).
refs = (
await lspRequest(() =>
commands.lspReferences(
nextRequestId(),
doc,
item.selection_range.start,
false,
false,
false,
new Channel(),
),
commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false),
)
).locations;
} catch (e) {
+1 -2
Переглянути файл
@@ -147,8 +147,7 @@ export function installMenuBridge(): () => void {
push();
pushEnablement(true);
};
// The menu bar is shared. A focused window re-pushes labels that can differ per window.
// An identical config does not replace the menu, so switching project tabs does not redraw it.
// The native menu bar is shared: a focused window re-pushes its own window-scoped labels.
window.addEventListener("focus", onFocus);
const unsubs = [
useI18n.subscribe((s, prev) => {
-10
Переглянути файл
@@ -15,16 +15,6 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.scope {
flex: none;
}
.searching {
flex: none;
display: flex;
align-items: center;
}
.title {
flex: 1;
min-width: 0;
+2 -22
Переглянути файл
@@ -11,17 +11,15 @@ import { Decoration, EditorView } from "@codemirror/view";
import { codePreviewExtensions } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
import { Icon, IconButton, List, Popup, fileIconName, listNavigate } from "@/ui";
import { openLocation, readFileLines } from "./ipc";
import {
dismissUsagesPopup,
setUsagesPopupScope,
showUsageResults,
usageCount,
useUsagesPopup,
type Usage,
type UsageGroup,
type UsageScope,
} from "./usages";
import { UsagePreview } from "./UsagesView";
import styles from "./UsagesPopup.module.css";
@@ -81,7 +79,7 @@ export function UsagesPopup() {
const ROW = 24;
function UsagesPopupInner() {
const { anchor, symbol, groups, note, loading, scope } = useUsagesPopup();
const { anchor, symbol, groups, note } = useUsagesPopup();
const preview = useUsagesPopupPreview((s) => s.preview);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const [filter, setFilter] = useState("");
@@ -154,24 +152,6 @@ function UsagesPopupInner() {
{filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`}
</span>
</span>
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
/>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={12} />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
-13
Переглянути файл
@@ -41,19 +41,6 @@
.error {
color: var(--danger);
}
.link {
flex: none;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration: underline;
}
.body {
flex: 1;
min-width: 0;
+2 -20
Переглянути файл
@@ -66,16 +66,8 @@ export function UsagesTabs() {
const tabs = useUsages((s) => s.tabs);
const search = useUsages(activeUsageSearch);
if (!search) return null;
const label = (t: (typeof tabs)[number]) => {
if (!t.symbol) return tx("Usages");
const text =
t.scope === "project"
? tx("Usages of '{symbol}' in Project Files")
: t.scope === "libraries"
? tx("Usages of '{symbol}' in Project and Libraries")
: tx("Usages of '{symbol}'");
return formatMessage(text, { symbol: t.symbol });
};
const label = (t: (typeof tabs)[number]) =>
t.symbol ? formatMessage(tx("Usages of '{symbol}'"), { symbol: t.symbol }) : tx("Usages");
return (
<Tabs
variant="compact"
@@ -276,16 +268,6 @@ export function UsagesView() {
</div>
<div className={styles.body} onKeyDown={onKeyDown}>
<UsageAccessFilter items={allUsages} />
{!search.loading && !search.error && search.scope === "project" && (
<div className={styles.summary}>
<T>Usages in Project Files</T>
{search.searchLibraries && (
<button type="button" className={styles.link} onClick={() => search.searchLibraries?.()}>
{tx("Search in Project and Libraries")}
</button>
)}
</div>
)}
{(search.loading || search.error) && (
<div className={styles.summary} role="status" aria-live="polite">
{search.loading ? (
+2 -8
Переглянути файл
@@ -23,12 +23,6 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, ...cmd } };
});
vi.mock("./candidates", () => ({ filesMentioning: () => filesMentioning() }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { _addEditor } = await import("@/editor/api");
const { fetchUsages } = await import("./usages");
@@ -48,7 +42,7 @@ beforeEach(() => {
describe("Find Usages fallback", () => {
it("uses the server when it answers, even with nothing", async () => {
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [], incomplete: null }));
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null, librariesSkipped: false });
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null });
expect(cmd.syntaxLocals).not.toHaveBeenCalled();
});
@@ -56,7 +50,7 @@ describe("Find Usages fallback", () => {
const usage = { path: "/p/a.ts", range: r(1, 0, 1) };
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [usage], incomplete: "indexing" }));
const res = await fetchUsages(caret, 42 as never);
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true, false, expect.anything());
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true);
expect(res.groups[0]!.usages.length).toBe(1);
expect(res.note).toBe(incompleteNote("indexing", "x"));
expect(incompleteNote("tooManyFiles", "x")).toBe(
+2 -77
Переглянути файл
@@ -5,33 +5,12 @@ vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
toolWindowService: () => ({ show }),
}));
const referenceResponse = vi.fn();
const lspReferences = vi.fn(async (..._args: unknown[]) => ({ status: "ok", data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, lspReferences } };
});
vi.mock("./ipc", async (orig) => ({
...(await orig<typeof import("./ipc")>()),
caretContext: () => ({ doc: 1, path: "/p/a.rs", line: 0, col: 0, word: "used", view: null }),
lspRequest: (request: () => unknown) => {
request();
return referenceResponse();
},
readManyFileLines: async () => new Map([["/p/b.rs", ["", " used();", " used();"]]]),
}));
const channels: { onmessage: (refs: unknown) => void }[] = [];
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
constructor() {
channels.push(this);
}
},
readManyFileLines: async () => new Map([["/p/b.rs", ["", " used();"]]]),
}));
const { activeUsageSearch, findUsages, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
const { activeUsageSearch, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
await import("./usages");
describe("showUsageResults", () => {
@@ -46,19 +25,6 @@ describe("showUsageResults", () => {
]);
});
it("shows the lines the server gave along for files it does not read", async () => {
const lib = {
path: "jdt://contents/lib/Lib.class",
range: { start: { line: 3, col: 4 }, end: { line: 3, col: 8 } },
};
await showUsageResults({
symbol: "used",
locations: [lib],
classified: [{ location: lib, kind: "unknown", text: " used();" }],
});
expect(activeUsageSearch(useUsages.getState())!.groups[0]!.usages[0]!.text).toBe(" used();");
});
it("ignores malformed arguments", async () => {
show.mockClear();
await showUsageResults({ symbol: "x" });
@@ -66,47 +32,6 @@ describe("showUsageResults", () => {
});
});
describe("findUsages", () => {
it("searches Project Files, then Project and Libraries on request", async () => {
const at = { path: "/p/b.rs", range: { start: { line: 1, col: 4 }, end: { line: 1, col: 8 } } };
lspReferences.mockClear();
referenceResponse.mockResolvedValueOnce({ locations: [at], incomplete: null, librariesSkipped: true });
await findUsages();
const project = activeUsageSearch(useUsages.getState())!;
expect(project).toMatchObject({ loading: false, scope: "project" });
expect(lspReferences.mock.lastCall![5]).toBe(false);
referenceResponse.mockResolvedValueOnce({ locations: [at], incomplete: null });
project.searchLibraries!();
await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())!.loading).toBe(false));
expect(lspReferences.mock.lastCall![5]).toBe(true);
const all = activeUsageSearch(useUsages.getState())!;
expect(all.scope).toBe("libraries");
// Rerun keeps the scope.
referenceResponse.mockResolvedValueOnce({ locations: [at], incomplete: null });
all.rerun!();
await vi.waitFor(() => expect(lspReferences).toHaveBeenCalledTimes(3));
expect(lspReferences.mock.lastCall![5]).toBe(true);
resetUsages();
});
it("shows the usages found first while it searches for the rest", async () => {
const at = (line: number) => ({ path: "/p/b.rs", range: { start: { line, col: 4 }, end: { line, col: 8 } } });
let resolve!: (refs: unknown) => void;
referenceResponse.mockReturnValueOnce(new Promise((r) => (resolve = r)));
const search = findUsages();
await vi.waitFor(() => expect(channels).not.toHaveLength(0));
channels.at(-1)!.onmessage({ locations: [at(1)], incomplete: null });
await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())!.groups).toHaveLength(1));
expect(activeUsageSearch(useUsages.getState())).toMatchObject({ loading: true, error: null });
resolve({ locations: [at(1), at(2)], incomplete: null });
await search;
const done = activeUsageSearch(useUsages.getState())!;
expect(done.loading).toBe(false);
expect(done.groups[0]!.usages.map((u) => u.line)).toEqual([1, 2]);
resetUsages();
});
});
describe("usage tabs", () => {
const search = (id: number) => ({
id,
+25 -159
Переглянути файл
@@ -1,11 +1,9 @@
/** Find Usages (⌥F7 → "usages" tool window) and Show Usages (⌥⌘F7 → popup). */
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import type { ClassifiedReference, ReferenceAccess, ReferenceKind, Location, References, RequestId } from "@/bindings";
import type { ClassifiedReference, ReferenceAccess, ReferenceKind, Location, RequestId } from "@/bindings";
import { clearLineTokens } from "@/editor/lineTokens";
import { incompleteNote } from "@/editor/lsp/lsp";
import { commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { toolWindowService } from "@/workbench/contributions";
import {
caretContext,
@@ -51,7 +49,7 @@ export function groupUsages(
const key = usageLocationKey(l);
if (seen.has(key)) continue;
seen.add(key);
const text = files.get(l.path)?.[l.range.start.line] ?? kinds.get(key)?.text ?? "";
const text = files.get(l.path)?.[l.range.start.line] ?? "";
const endCol = l.range.end.line === l.range.start.line ? l.range.end.col : Math.max(text.length, l.range.start.col);
let list = byPath.get(l.path);
if (!list) byPath.set(l.path, (list = []));
@@ -88,15 +86,6 @@ export function trimPreview(u: Usage): { text: string; textCol: number; from: nu
return { text, textCol: lead, from, to };
}
/** Project Files, or Project and Libraries (Java's dependency jars and JDK too). */
export type UsageScope = "project" | "libraries";
/** The scope a search ran in, when there was a choice (`null` when the server has none). */
function searchedScope(libraries: boolean, librariesSkipped: boolean, widenable: boolean): UsageScope | null {
if (librariesSkipped) return "project";
return libraries && widenable ? "libraries" : null;
}
export interface UsageSearch {
/** Identifies one search run (UI state such as expansion resets per run). */
id: number;
@@ -108,10 +97,6 @@ export interface UsageSearch {
note: string | null;
/** Re-runs the same query (rerun button). */
rerun: (() => void) | null;
/** Where it searched, when the server can search beyond Project Files (Java's jars and JDK). */
scope?: UsageScope | null;
/** Runs it again in Project and Libraries. */
searchLibraries?: (() => void) | null;
/** Kept when a new search runs (Pin Tab). */
pinned?: boolean;
}
@@ -178,10 +163,6 @@ interface UsagesPopupState {
symbol: string | null;
groups: UsageGroup[];
note: string | null;
/** Shows those found so far while the search goes on. */
loading: boolean;
/** Where it searched, when the server can search beyond Project Files. */
scope: UsageScope | null;
}
export const useUsagesPopup = create<UsagesPopupState>(() => ({
@@ -190,64 +171,31 @@ export const useUsagesPopup = create<UsagesPopupState>(() => ({
symbol: null,
groups: [],
note: null,
loading: false,
scope: null,
}));
interface FetchedUsages {
groups: UsageGroup[];
note: string | null;
librariesSkipped: boolean;
}
/** Paths whose lines are read to show these usages: not those the server gave along. */
function pathsToRead(locs: readonly Location[], classified: readonly ClassifiedReference[]): string[] {
const given = new Set(classified.filter((r) => r.text != null).map((r) => usageLocationKey(r.location)));
return locs.filter((l) => !given.has(usageLocationKey(l))).map((l) => l.path);
}
/**
* The server's references across the project (files outside its analysis scope
* included); when it is not ready or fails, the syntax fallback (an empty server
* answer is respected). Without a fallback the server error stands. Without
* `libraries`, Java's dependencies and JDK are not searched (Project Files); with it,
* those found in the sources go to `onPartial` before the slower search for the rest.
* answer is respected). Without a fallback the server error stands.
* Cancel with `commands.cancelRequest(request)`.
*/
export async function fetchUsages(
c: CaretContext,
request: RequestId = nextRequestId(),
onPartial?: (found: FetchedUsages) => void,
libraries = false,
): Promise<FetchedUsages> {
export async function fetchUsages(c: CaretContext, request: RequestId = nextRequestId()): Promise<FetchedUsages> {
// Usage lines are read afresh: so are the files their syntax colours come from.
clearLineTokens();
let locs: Location[];
let classified: ClassifiedReference[] = [];
let note: string | null = null;
let librariesSkipped = false;
let settled = false;
const channel = new Channel<References>();
channel.onmessage = (refs) => {
if (!onPartial) return;
void readManyFileLines(pathsToRead(refs.locations, refs.classified ?? [])).then((files) => {
if (settled) return;
onPartial({
groups: groupUsages(refs.locations, files, refs.classified ?? []),
note: refs.incomplete ? incompleteNote(refs.incomplete, c.word) : null,
librariesSkipped: false,
});
});
};
try {
const refs = await lspRequest(() =>
commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true, libraries, channel),
).finally(() => {
settled = true;
});
commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true),
);
locs = refs.locations;
classified = refs.classified ?? [];
librariesSkipped = refs.librariesSkipped ?? false;
if (refs.incomplete) note = incompleteNote(refs.incomplete, c.word);
} catch (e) {
if (isCancelled(e)) throw e;
@@ -262,8 +210,8 @@ export async function fetchUsages(
locs = fb.locs;
note = fb.note;
}
const files = await readManyFileLines(pathsToRead(locs, classified));
return { groups: groupUsages(locs, files, classified), note, librariesSkipped };
const files = await readManyFileLines(locs.map((l) => l.path));
return { groups: groupUsages(locs, files, classified), note };
}
/** In-flight server requests: of tool window searches by search id, and of the popup. */
@@ -283,8 +231,7 @@ export function resetUsages() {
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
popupRequest = null;
useUsages.setState({ tabs: [], active: null });
useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null, loading: false, scope: null });
popupTarget = null;
useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null });
}
export async function findUsages() {
@@ -293,15 +240,9 @@ export async function findUsages() {
hint("Open a file to find usages");
return;
}
// `widenable`: an earlier run of this search skipped the libraries.
const run = async (prev: number | null, libraries: boolean, widenable: boolean) => {
const run = async (prev: number | null) => {
const id = ++searchSeq;
const base = {
id,
symbol: c.word,
rerun: () => void run(id, libraries, widenable),
searchLibraries: () => void run(id, true, true),
};
const base = { id, symbol: c.word, rerun: () => void run(id) };
const loading = { ...base, loading: true, groups: [], error: null, note: null };
if (prev !== null) cancelSearch(prev);
if (prev === null || !replaceUsageTab(prev, loading)) openUsageTab(loading);
@@ -309,16 +250,8 @@ export async function findUsages() {
const request = nextRequestId();
inflight.set(id, request);
try {
const { groups, note, librariesSkipped } = await fetchUsages(
c,
request,
(found) => {
if (inflight.get(id) === request) replaceUsageTab(id, { ...loading, groups: found.groups, note: found.note });
},
libraries,
);
const scope = searchedScope(libraries, librariesSkipped, widenable);
replaceUsageTab(id, { ...base, loading: false, groups, error: null, note, scope });
const { groups, note } = await fetchUsages(c, request);
replaceUsageTab(id, { ...base, loading: false, groups, error: null, note });
} catch (e) {
// Cancelled here (closed tab, rerun): a newer state already replaced it.
if (isCancelled(e) && !inflight.has(id)) return;
@@ -329,7 +262,7 @@ export async function findUsages() {
if (inflight.get(id) === request) inflight.delete(id);
}
};
await run(null, false, false);
await run(null);
}
/**
@@ -367,101 +300,34 @@ export function dismissUsagesPopup() {
useUsagesPopup.setState({ open: false });
}
/** How long Show Usages waits for all usages before it shows those found first. */
const EARLY_POPUP_DELAY_MS = 300;
/** How long the hint after Show Usages stays (and invoking it again widens its search). */
const HINT_MS = 4000;
/**
* What the popup, or the hint after it, shows usages of: invoked again meanwhile, Show
* Usages searches it in Project and Libraries, wherever the caret is now.
*/
let popupTarget: { c: CaretContext; widenable: boolean; hintUntil: number } | null = null;
export async function showUsagesPopup() {
const target = popupTarget;
const popup = useUsagesPopup.getState();
if (target?.widenable && ((popup.open && popup.scope === "project") || Date.now() < target.hintUntil)) {
await searchPopup(target.c, true, true);
return;
}
const c = caretContext();
if (!c) {
hint("Open a file to show usages");
return;
}
await searchPopup(c, false, false);
}
/** The popup's scope chooser: searches its symbol again in `scope`. */
export function setUsagesPopupScope(scope: UsageScope) {
const target = popupTarget;
if (!target || scope === useUsagesPopup.getState().scope) return;
void searchPopup(target.c, scope === "libraries", target.widenable);
}
async function searchPopup(c: CaretContext, libraries: boolean, widenable: boolean) {
// Set from the start: the scope chooser can switch while this search goes on.
popupTarget = { c, widenable, hintUntil: 0 };
const reopened = useUsagesPopup.getState().open;
if (reopened) useUsagesPopup.setState({ loading: true, scope: libraries ? "libraries" : "project" });
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
const request = nextRequestId();
popupRequest = request;
// Opened with those found first when the rest take a while; it then stays open, even
// when they were all. A quick search still jumps to a single usage.
let early = false;
let found: FetchedUsages | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
const openEarly = () => {
if (popupRequest !== request || !found) return;
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word });
early = true;
useUsagesPopup.setState({ ...found, loading: true, scope: widenable ? "libraries" : null });
};
const again = shortcutLabel("find.showUsages");
try {
const { groups, note, librariesSkipped } = await fetchUsages(
c,
request,
(partial) => {
if (!usageCount(partial.groups)) return;
found = partial;
if (early) openEarly();
else timer ??= setTimeout(openEarly, EARLY_POPUP_DELAY_MS);
},
libraries,
).finally(() => clearTimeout(timer));
const { groups, note } = await fetchUsages(c, request);
if (popupRequest !== request) return;
const scope = searchedScope(libraries, librariesSkipped, widenable);
popupTarget = { c, widenable: widenable || scope !== null, hintUntil: 0 };
const total = usageCount(groups);
if (early || reopened || total > 1) {
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word });
useUsagesPopup.setState({ groups, note, loading: false, scope });
return;
}
// As in IDEA, the hint offers to widen the search, which Show Usages does while it shows.
const widen = scope === "project" && again !== "";
if (widen) popupTarget.hintUntil = Date.now() + HINT_MS;
if (!total) {
if (widen) hint(`No usages found in Project Files. Press ${again} again to search in 'Project and Libraries'`);
else if (scope === "project") hint("No usages found in Project Files");
else {
const none = c.word ? `No usages of '${c.word}' found` : "No usages found";
hint(note ? `${none}. ${note}` : none);
}
const none = c.word ? `No usages of '${c.word}' found` : "No usages found";
hint(note ? `${none}. ${note}` : none);
return;
}
// IDEA jumps to the only usage and says so in the target editor.
const u = groups[0]!.usages[0]!;
await openLocation(u.path, u.line, u.col);
if (widen) hint(`Only one usage in Project Files. Press ${again} again to search in 'Project and Libraries'`);
else if (scope === "libraries") hint("Only one usage in Project and Libraries");
else hint("Only one usage in Project Files");
if (total === 1) {
// IDEA jumps to the only usage and says so in the target editor.
const u = groups[0]!.usages[0]!;
await openLocation(u.path, u.line, u.col);
hint("Only one usage in Project Files");
return;
}
useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word, groups, note });
} catch (e) {
if (popupRequest !== request || isCancelled(e)) return;
if (early || reopened) useUsagesPopup.setState({ loading: false });
reportError(e);
} finally {
if (popupRequest === request) popupRequest = null;
+3 -152
Переглянути файл
@@ -2,44 +2,16 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const calls: string[] = [];
const referenceResponse = vi.fn(
async (): Promise<{ locations: (typeof loc)[]; incomplete: null; librariesSkipped?: boolean }> => ({
locations: [loc],
incomplete: null,
}),
);
const referenceResponse = vi.fn(async () => ({ locations: [loc], incomplete: null }));
const loc = { path: "/p/b.ts", range: { start: { line: 1, col: 4 }, end: { line: 1, col: 8 } } };
const lspReferences = vi.fn(async () => ({ status: "ok", data: null }));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, lspReferences } };
});
vi.mock("@/platform/keymap", async (orig) => ({
...(await orig<typeof import("@/platform/keymap")>()),
shortcutLabel: (id: string) => (id === "find.showUsages" ? "⌥⌘F7" : ""),
}));
vi.mock("./ipc", async (orig) => ({
...(await orig<typeof import("./ipc")>()),
caretContext: () => ({ doc: 1, path: "/p/a.ts", line: 0, col: 0, word: "used", view: null }),
lspRequest: (request: () => unknown) => {
request();
return referenceResponse();
},
lspRequest: () => referenceResponse(),
readManyFileLines: async () => new Map([["/p/b.ts", ["", " used();"]]]),
openLocation: async (path: string, line: number) => void calls.push(`open ${path}:${line}`),
hint: (text: string) => void calls.push(`hint ${text}`),
}));
/** The partial-results channels of the searches, newest last. */
const channels: { onmessage: (refs: unknown) => void }[] = [];
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
constructor() {
channels.push(this);
}
},
}));
const showUsageResults = vi.fn();
vi.mock("./usages", async (orig) => ({
...(await orig<typeof import("./usages")>()),
@@ -47,7 +19,7 @@ vi.mock("./usages", async (orig) => ({
}));
const { UsagesPopup, filterUsages, usageLocations } = await import("./UsagesPopup");
const { showUsagesPopup, useUsagesPopup, dismissUsagesPopup, setUsagesPopupScope } = await import("./usages");
const { showUsagesPopup, useUsagesPopup, dismissUsagesPopup } = await import("./usages");
const usage = (path: string, line: number, text: string) => ({ path, line, col: 0, endCol: 3, text });
const groups = [
@@ -226,127 +198,6 @@ it("keeps filter controls available when all classified rows are hidden", () =>
expect(screen.getAllByRole("option")).toHaveLength(2);
});
it("opens with the usages found first and fills in the rest", async () => {
render(<UsagesPopup />);
const at = (line: number) => ({ ...loc, range: { start: { line, col: 4 }, end: { line, col: 8 } } });
let resolve!: (value: { locations: (typeof loc)[]; incomplete: null }) => void;
referenceResponse.mockReturnValueOnce(
new Promise((r) => {
resolve = r;
}),
);
const before = calls.length;
const pending = showUsagesPopup();
await act(async () => channels.at(-1)!.onmessage({ locations: [at(1)], incomplete: null }));
// Not before the rest had a moment to arrive.
expect(useUsagesPopup.getState().open).toBe(false);
await act(() => new Promise((r) => setTimeout(r, 350)));
expect(useUsagesPopup.getState()).toMatchObject({ open: true, loading: true });
expect(screen.getByRole("status", { name: "Searching for more usages" })).toBeInTheDocument();
expect(screen.getAllByRole("option")).toHaveLength(1);
await act(async () => channels.at(-1)!.onmessage({ locations: [at(1), at(2)], incomplete: null }));
expect(screen.getAllByRole("option")).toHaveLength(2);
await act(async () => {
resolve({ locations: [at(1), at(2), at(3)], incomplete: null });
await pending;
});
expect(useUsagesPopup.getState()).toMatchObject({ open: true, loading: false });
expect(screen.queryByRole("status", { name: "Searching for more usages" })).toBeNull();
expect(screen.getAllByRole("option")).toHaveLength(3);
expect(calls.slice(before)).toEqual([]);
act(() => dismissUsagesPopup());
});
it("jumps to a single usage when all arrive quickly, and otherwise stays open", async () => {
render(<UsagesPopup />);
let resolve!: (value: { locations: (typeof loc)[]; incomplete: null }) => void;
const respond = () =>
referenceResponse.mockReturnValueOnce(
new Promise((r) => {
resolve = r;
}),
);
respond();
let before = calls.length;
let pending = showUsagesPopup();
await act(async () => channels.at(-1)!.onmessage({ locations: [loc], incomplete: null }));
await act(async () => {
resolve({ locations: [loc], incomplete: null });
await pending;
});
expect(useUsagesPopup.getState().open).toBe(false);
expect(calls.slice(before)).toEqual(["open /p/b.ts:1", "hint Only one usage in Project Files"]);
respond();
before = calls.length;
pending = showUsagesPopup();
await act(async () => channels.at(-1)!.onmessage({ locations: [loc], incomplete: null }));
await act(() => new Promise((r) => setTimeout(r, 350)));
await act(async () => {
resolve({ locations: [loc], incomplete: null });
await pending;
});
expect(useUsagesPopup.getState()).toMatchObject({ open: true, loading: false });
expect(screen.getAllByRole("option")).toHaveLength(1);
expect(calls.slice(before)).toEqual([]);
act(() => dismissUsagesPopup());
});
it("searches Project Files, and Project and Libraries when invoked again", async () => {
render(<UsagesPopup />);
const at = (line: number) => ({ ...loc, range: { start: { line, col: 4 }, end: { line, col: 8 } } });
const libraries = () => (lspReferences.mock.lastCall as unknown[])[5];
const widen = "Press ⌥⌘F7 again to search in 'Project and Libraries'";
// Nothing in Project Files: the hint offers the libraries, searched when invoked again meanwhile.
let before = calls.length;
referenceResponse.mockResolvedValueOnce({ locations: [], incomplete: null, librariesSkipped: true });
await showUsagesPopup();
expect(libraries()).toBe(false);
expect(calls.slice(before)).toEqual([`hint No usages found in Project Files. ${widen}`]);
referenceResponse.mockResolvedValueOnce({ locations: [at(1), at(2)], incomplete: null });
await act(() => showUsagesPopup());
expect(libraries()).toBe(true);
expect(useUsagesPopup.getState()).toMatchObject({ open: true, scope: "libraries" });
expect(screen.getByRole("button", { name: "Scope" })).toHaveTextContent("Project and Libraries");
// The scope chooser searches Project Files again.
referenceResponse.mockResolvedValueOnce({ locations: [at(1), at(2)], incomplete: null, librariesSkipped: true });
await act(async () => setUsagesPopupScope("project"));
await vi.waitFor(() => expect(useUsagesPopup.getState()).toMatchObject({ loading: false, scope: "project" }));
expect(libraries()).toBe(false);
expect(screen.getByRole("button", { name: "Scope" })).toHaveTextContent("Project Files");
// Switched while Project and Libraries are still searched: that search gives way.
let finish!: (value: { locations: (typeof loc)[]; incomplete: null }) => void;
referenceResponse.mockReturnValueOnce(new Promise((r) => (finish = r)));
await act(async () => setUsagesPopupScope("libraries"));
expect(libraries()).toBe(true);
expect(useUsagesPopup.getState()).toMatchObject({ loading: true, scope: "libraries" });
referenceResponse.mockResolvedValueOnce({ locations: [at(1), at(2)], incomplete: null, librariesSkipped: true });
await act(async () => setUsagesPopupScope("project"));
await vi.waitFor(() => expect(useUsagesPopup.getState()).toMatchObject({ loading: false, scope: "project" }));
expect(libraries()).toBe(false);
await act(async () => finish({ locations: [at(1), at(2), at(3), at(4)], incomplete: null }));
expect(screen.getAllByRole("option")).toHaveLength(2);
// Invoked again while it shows Project Files: Project and Libraries.
referenceResponse.mockResolvedValueOnce({ locations: [at(1), at(2), at(3)], incomplete: null });
await act(() => showUsagesPopup());
expect(libraries()).toBe(true);
expect(screen.getAllByRole("option")).toHaveLength(3);
act(() => dismissUsagesPopup());
// The only usage in Project Files is opened; the hint offers the libraries too.
before = calls.length;
referenceResponse.mockResolvedValueOnce({ locations: [at(1)], incomplete: null, librariesSkipped: true });
await showUsagesPopup();
expect(calls.slice(before)).toEqual(["open /p/b.ts:1", `hint Only one usage in Project Files. ${widen}`]);
referenceResponse.mockResolvedValueOnce({ locations: [at(1)], incomplete: null });
before = calls.length;
await showUsagesPopup();
expect(libraries()).toBe(true);
expect(calls.slice(before)).toEqual(["open /p/b.ts:1", "hint Only one usage in Project and Libraries"]);
// Without a hint showing, it searches the symbol at the caret in Project Files again.
referenceResponse.mockResolvedValueOnce({ locations: [at(1)], incomplete: null, librariesSkipped: true });
await showUsagesPopup();
expect(libraries()).toBe(false);
});
it("discards a pending response after the current popup is dismissed", async () => {
let resolve!: (value: { locations: (typeof loc)[]; incomplete: null }) => void;
referenceResponse.mockReturnValueOnce(
+1 -8
Переглянути файл
@@ -8,7 +8,7 @@ import { useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "r
import clsx from "clsx";
import { Button, Checkbox, Icon, IconButton, Input, Popup, SearchField, Select, Tabs, T, type MenuItem } from "@/ui";
import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "./export";
import { Grid, type CopyFormat, type GridColumn, type GridProps, type GridRange } from "./Grid";
import { Grid, type GridColumn, type GridProps, type GridRange } from "./Grid";
import type { Cell } from "./model";
import {
aggregates,
@@ -55,10 +55,6 @@ export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onCh
);
}
/** The copy format plain ⌘C uses under a toolbar extractor (cell copies stay cell-shaped). */
export const copyFormatOf = (extractor: ExportFormat): CopyFormat =>
extractor === "csv" ? "csv" : extractor === "onerow" ? "onerow" : "tsv";
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
return (
@@ -91,8 +87,6 @@ export interface DataViewProps extends Pick<
/** The side panel shown (`null`: hidden). */
panel: DataPanel | null;
onPanelChange: (panel: DataPanel | null) => void;
/** Plain ⌘C's copy format (the toolbar's extractor; TSV by default). */
copyFormat?: CopyFormat;
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
searchOpen?: boolean;
onSearchOpenChange?: (open: boolean) => void;
@@ -220,7 +214,6 @@ export function DataView(props: DataViewProps) {
onSort={onSort}
rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))}
rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)}
copyFormat={props.copyFormat}
onSelectionChange={setRange}
onFilter={(col, anchor) => setFilterAt({ col, anchor })}
filtered={(col) => filter.has(col)}
-67
Переглянути файл
@@ -53,73 +53,6 @@ describe("database grid", () => {
expect(writeText).toHaveBeenCalledWith("one\ttwo\nthree\tfour");
expect(globalCopy).not.toHaveBeenCalled();
});
it("copies the selection in the extractor's format for plain ⌘C", () => {
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
const data = [
["1", "Shanghai"],
["2", "Bei'jing"],
["3", null],
];
render(
<Grid
columns={[
{ name: "id", type: "INTEGER" },
{ name: "city", type: "TEXT" },
]}
rowCount={3}
value={(r, c) => data[r]![c]!}
copyFormat="onerow"
/>,
);
const cells = screen.getAllByRole("gridcell");
// A column of three cells: the values on one line.
fireEvent.mouseDown(cells[0]!, { button: 0 });
fireEvent.mouseEnter(cells[4]!);
fireEvent.mouseUp(window);
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", ctrlKey: true });
expect(writeText).toHaveBeenCalledWith("1, 2, 3");
// Text values are single-quoted with `'` doubled; nulls are NULL.
writeText.mockClear();
fireEvent.mouseDown(cells[1]!, { button: 0 });
fireEvent.mouseEnter(cells[5]!);
fireEvent.mouseUp(window);
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", ctrlKey: true });
expect(writeText).toHaveBeenCalledWith("'Shanghai', 'Bei''jing', NULL");
// Several columns join in reading order, all on one line.
writeText.mockClear();
fireEvent.mouseDown(cells[0]!, { button: 0 });
fireEvent.mouseEnter(cells[3]!);
fireEvent.mouseUp(window);
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", ctrlKey: true });
expect(writeText).toHaveBeenCalledWith("1, 'Shanghai', 2, 'Bei''jing'");
});
it("copies a selection as CSV with ⌘C when the extractor is csv", () => {
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
render(
<Grid
columns={[
{ name: "a", type: "text" },
{ name: "b", type: "text" },
]}
rowCount={2}
value={(r, c) =>
[
["one", "two"],
["three", "four"],
][r]![c]!
}
copyFormat="csv"
/>,
);
const cells = screen.getAllByRole("gridcell");
fireEvent.mouseDown(cells[0]!, { button: 0 });
fireEvent.mouseEnter(cells[3]!);
fireEvent.mouseUp(window);
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", ctrlKey: true });
expect(writeText).toHaveBeenCalledWith("one,two\r\nthree,four");
});
it("pastes a rectangle as pending edits and skips deleted rows", () => {
const onEdit = vi.fn();
render(
+8 -37
Переглянути файл
@@ -1,13 +1,13 @@
/**
* Result / table data grid: virtualised rows, resizable columns, rectangular
* cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV / One-Row,
* `<null>` rendering, sortable headers and in-place editing (table editor).
* cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV, `<null>`
* rendering, sortable headers and in-place editing (table editor).
*/
import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type KeyboardEvent, type MouseEvent } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import clsx from "clsx";
import { Dialog, Icon, showContextMenu, type MenuItem } from "@/ui";
import { parseDelimited, toCsv, toOneRow, toTsv, type Cell } from "./model";
import { parseDelimited, toCsv, toTsv, type Cell } from "./model";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { CELL_PREVIEW_LIMIT, cellPreview, hasLineBreak } from "./cellPreview";
@@ -29,16 +29,11 @@ export function isNumericColumn(type: string, sample: readonly Cell[]): boolean
return values.length > 0 && values.every((v) => NUMBER.test(v));
}
/** The grid's own copy formats (the extractor drop-down chooses one for plain ⌘C). */
export type CopyFormat = "tsv" | "csv" | "onerow";
export interface GridProps {
columns: readonly GridColumn[];
rowCount: number;
/** Displayed value (pending edits applied). */
value: (row: number, col: number) => Cell;
/** The format plain ⌘C copies in (the toolbar's extractor; TSV by default). */
copyFormat?: CopyFormat;
rowState?: (row: number) => "deleted" | "inserted" | null;
isModified?: (row: number, col: number) => boolean;
editable?: boolean;
@@ -122,18 +117,7 @@ function norm(s: Sel) {
}
export function Grid(props: GridProps) {
const {
columns,
rowCount,
value,
editable,
onEdit,
sort,
onSort,
rowMenu,
firstRowNumber = 1,
copyFormat = "tsv",
} = props;
const { columns, rowCount, value, editable, onEdit, sort, onSort, rowMenu, firstRowNumber = 1 } = props;
const scrollRef = useRef<HTMLDivElement>(null);
const [sel, setSel] = useState<Sel | null>(null);
const dragging = useRef(false);
@@ -224,7 +208,7 @@ export function Grid(props: GridProps) {
return Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i);
};
const copy = (format: CopyFormat, header: boolean, wholeRows = false) => {
const copy = (format: "tsv" | "csv", header: boolean, wholeRows = false) => {
if (!sel) return;
const n = norm(sel);
const cols = wholeRows
@@ -232,12 +216,7 @@ export function Grid(props: GridProps) {
: Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i);
const rows = selectedRows().map((r) => cols.map((c) => value(r, c)));
const head = header ? cols.map((c) => columns[c]!.name) : null;
const text =
format === "onerow"
? toOneRow(rows, (c) => !!numeric[cols[c]!])
: format === "tsv"
? toTsv(head, rows)
: toCsv(head, rows);
const text = format === "tsv" ? toTsv(head, rows) : toCsv(head, rows);
void navigator.clipboard?.writeText(text);
};
@@ -268,7 +247,7 @@ export function Grid(props: GridProps) {
const mod = e.metaKey || e.ctrlKey;
if (mod && e.key.toLowerCase() === "c") {
e.preventDefault();
copy(copyFormat, false);
copy("tsv", false);
return;
}
if (mod && e.key.toLowerCase() === "f" && props.onFind) {
@@ -347,15 +326,7 @@ export function Grid(props: GridProps) {
e.preventDefault();
if (!sel) return;
const items: MenuItem[] = [
{ label: "Copy", shortcut: "⌘C", run: () => copy(copyFormat, false) },
{
label: "Copy as",
submenu: [
{ label: "TSV", verbatim: true, run: () => copy("tsv", false) },
{ label: "CSV", verbatim: true, run: () => copy("csv", false) },
{ label: "One-Row", run: () => copy("onerow", false) },
],
},
{ label: "Copy", shortcut: "⌘C", run: () => copy("tsv", false) },
{ label: "Copy with Header", run: () => copy("tsv", true) },
{ label: "Copy Rows as TSV", run: () => copy("tsv", true, true) },
{ label: "Copy Rows as CSV", run: () => copy("csv", true, true) },
+1 -2
Переглянути файл
@@ -10,7 +10,7 @@ import type { DbPlanNode } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { EmptyState, Icon, IconButton, Select, Spinner, Tabs, Tree, showContextMenu, T } from "@/ui";
import { ChartView } from "./ChartView";
import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type DataPanel } from "./DataView";
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
import type { ExportData, ExportFormat } from "./export";
import { pageWindow } from "./resultView";
import { analyze } from "./sql/analyze";
@@ -215,7 +215,6 @@ function Result({ tab }: { tab: ResultTab }) {
value={value}
panel={panel}
onPanelChange={setPanel}
copyFormat={copyFormatOf(extractor)}
searchOpen={searchOpen}
onSearchOpenChange={setSearchOpen}
firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1}
+1 -2
Переглянути файл
@@ -17,7 +17,7 @@ import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMe
import { notifications, type EditorInput } from "@/workbench/contributions";
import { SqlFilterInput } from "./SqlFilterInput";
import { ColumnsPopup } from "./ColumnsPopup";
import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type DataPanel } from "./DataView";
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
import type { ExportFormat } from "./export";
import {
buildRowEdits,
@@ -355,7 +355,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
value={value}
panel={panel}
onPanelChange={setPanel}
copyFormat={copyFormatOf(extractor)}
searchOpen={searchOpen}
onSearchOpenChange={setSearchOpen}
firstRowNumber={offset + 1}
+4 -8
Переглянути файл
@@ -1,15 +1,14 @@
/**
* Result-set export formats (IDEA's data extractors): CSV, TSV, JSON, SQL
* INSERT statements, a Markdown table and One-Row (all values on one `, ` list).
* Values arrive as text; numeric columns are written unquoted where the format
* distinguishes them.
* INSERT statements and a Markdown table. Values arrive as text; numeric
* columns are written unquoted where the format distinguishes them.
*/
import type { DbDriver } from "@/platform/ipc";
import { isNumericColumn } from "./Grid";
import { toCsv, toOneRow, toTsv, type Cell } from "./model";
import { toCsv, toTsv, type Cell } from "./model";
import { quoteIdent } from "./sql/complete";
export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown" | "onerow";
export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown";
export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; extension: string }> = [
{ id: "csv", label: "CSV", extension: "csv" },
@@ -17,7 +16,6 @@ export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; ex
{ id: "json", label: "JSON", extension: "json" },
{ id: "sql", label: "SQL Inserts", extension: "sql" },
{ id: "markdown", label: "Markdown", extension: "md" },
{ id: "onerow", label: "One-Row", extension: "txt" },
];
export interface ExportData {
@@ -101,7 +99,5 @@ export function exportData(
: [...(options.rowHeader ? ["--:"] : []), ...numeric.map((n) => (n ? "--:" : "---"))];
return [head.map(cell), align, ...t.rows.map((r) => r.map(cell))].map((r) => `| ${r.join(" | ")} |`).join("\n");
}
case "onerow":
return toOneRow(d.rows, (c) => numeric[c]!);
}
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more