дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
Порівняти коміти
2
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f43b43aadd | ||
|
|
8ca7efc411 |
No files matched your search
@@ -1,69 +0,0 @@
|
||||
name: Bug report
|
||||
description: Something in OpenIDEA doesn't work as expected
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for reporting! Keep logs and error messages exactly as they appear.
|
||||
|
||||
One problem per issue, please. If you have several, open one issue for each.
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before you start
|
||||
options:
|
||||
- label: I searched [existing issues](https://github.com/l0ng-ai/openidea/issues?q=is%3Aissue) and this hasn't been reported yet.
|
||||
required: true
|
||||
- label: I'm on the [latest release](https://github.com/l0ng-ai/openidea/releases/latest), or I noted below that I can't update.
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: |
|
||||
Open **About OpenIDEA** (macOS: OpenIDEA menu; Windows/Linux: Help menu), click **Copy Info**, and paste it here. Also mention the project type if it matters (e.g. Gradle multi-module, Spring Boot, Go workspace) and whether you use remote development.
|
||||
render: text
|
||||
placeholder: |
|
||||
About OpenIDEA
|
||||
Version: 0.1.33
|
||||
Build: ...
|
||||
Platform: macOS aarch64
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Start from opening OpenIDEA or a project. A small sample project or snippet helps a lot.
|
||||
placeholder: |
|
||||
1. Open a Gradle project whose settings.gradle includes modules in a loop
|
||||
2. Open the Gradle tool window
|
||||
3. ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
description: What happened instead. Screenshots or a recording are welcome.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs
|
||||
description: |
|
||||
Use **Help → Show Log in Finder / Explorer / Files** to find `openidea.log` and paste the lines around the problem, or attach the file. Include console output or error messages too. Check for tokens or passwords before posting.
|
||||
render: text
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Anything else, such as whether it worked in an earlier version.
|
||||
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Download the latest release
|
||||
url: https://github.com/l0ng-ai/openidea/releases/latest
|
||||
about: Many problems are already fixed. Please check the latest version before reporting.
|
||||
@@ -1,38 +0,0 @@
|
||||
name: Feature request
|
||||
description: Suggest a new feature or an improvement
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
One request per issue, please.
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before you start
|
||||
options:
|
||||
- label: I searched [existing issues](https://github.com/l0ng-ai/openidea/issues?q=is%3Aissue) and this hasn't been requested yet.
|
||||
required: true
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: What are you trying to do, and what gets in the way today?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: How you'd like it to work. Mockups or examples from other tools are welcome.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives and workarounds
|
||||
description: Other approaches you considered, or what you do now instead.
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: Additional context
|
||||
Створено
+38
-37
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4061,7 +4061,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4075,11 +4075,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4090,7 +4091,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4099,11 +4100,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4116,7 +4116,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4130,7 +4130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4148,7 +4148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4170,9 +4170,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4183,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4195,10 +4196,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4208,7 +4210,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4255,7 +4257,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4273,7 +4275,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4295,7 +4297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4311,7 +4313,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4366,7 +4368,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4391,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4414,7 +4416,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4428,12 +4430,11 @@ dependencies = [
|
||||
"tracing",
|
||||
"wasmtime",
|
||||
"wasmtime-wasi",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4446,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4464,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4486,7 +4487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4505,7 +4506,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4525,7 +4526,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4538,7 +4539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4557,7 +4558,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4572,7 +4573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4585,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4597,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4618,7 +4619,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4637,7 +4638,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4659,7 +4660,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4675,7 +4676,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6147,7 +6148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"block2 0.6.2",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.34"
|
||||
version = "0.1.33"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -314,23 +314,8 @@ impl AgentManager {
|
||||
source: p.source.clone(),
|
||||
})
|
||||
.collect();
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
let old = prev.iter().find(|p| &p.id == id);
|
||||
let new = specs.iter().find(|p| &p.id == id);
|
||||
matches!((old, new), (Some(a), Some(b)) if a.command == b.command && a.args == b.args && a.env == b.env)
|
||||
});
|
||||
*prev = specs;
|
||||
list
|
||||
}
|
||||
|
||||
/// Re-reads configured/installed agents, drops cached probes, and notifies subscribers.
|
||||
pub fn reload_providers(&self) {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
|
||||
*self.shared.providers.write() = specs;
|
||||
self.shared.probes.lock().clear();
|
||||
self.shared.emit(AgentEvent::Providers);
|
||||
list
|
||||
}
|
||||
|
||||
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
|
||||
@@ -823,8 +808,7 @@ impl AgentManager {
|
||||
// A copy of the task (a fork) may work in the same worktree.
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
if remove_worktree && !shared && isolation == Isolation::Worktree && cwd.exists() {
|
||||
let worktrees = self.shared.paths.worktrees_dir.clone();
|
||||
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
|
||||
blocking(move || worktree::remove(&root, &cwd)).await?;
|
||||
}
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
|
||||
@@ -413,6 +413,4 @@ pub enum AgentEvent {
|
||||
index: u32,
|
||||
entry: AgentEntry,
|
||||
},
|
||||
/// The installed or configured agent providers changed.
|
||||
Providers,
|
||||
}
|
||||
@@ -169,7 +169,7 @@ impl Translator {
|
||||
Some("tool_use") => {
|
||||
// The input streams after this: shown by name until the message has it.
|
||||
let (id, name) = (str_of(&block, "id"), str_of(&block, "name"));
|
||||
if !(id.is_empty() || tools::is_plan(&name) || tools::is_agent(&name) && self.subagents) {
|
||||
if !id.is_empty() && !tools::is_plan(&name) && !(tools::is_agent(&name) && self.subagents) {
|
||||
out.extend(self.ensure_call(&id, &name, &json!({}), &session));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,16 +80,9 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `id` names a built-in agent that needs no registry install (native drivers
|
||||
/// and `npx -y` adapters). CLI built-ins (`copilot`, `gemini`, …) can be installed and
|
||||
/// updated from the ACP Registry into `<config>/agents/<id>.toml`.
|
||||
/// Whether `id` names a built-in agent.
|
||||
pub(crate) fn is_builtin(id: &str) -> bool {
|
||||
BUILTIN.iter().any(|&(bid, _, driver, cmd, _)| bid == id && (driver != Driver::Acp || cmd.first() == Some(&"npx")))
|
||||
}
|
||||
|
||||
/// Display name of a built-in agent, when `id` is one.
|
||||
pub(crate) fn builtin_name(id: &str) -> Option<&'static str> {
|
||||
BUILTIN.iter().find(|&&(bid, _, _, _, _)| bid == id).map(|&(_, name, _, _, _)| name)
|
||||
BUILTIN.iter().any(|b| b.0 == id)
|
||||
}
|
||||
|
||||
/// An agent file, `<config>/agents/<id>.toml`.
|
||||
@@ -169,7 +162,7 @@ pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
None => AgentSource::Custom,
|
||||
};
|
||||
let mut spec = ProviderSpec {
|
||||
let spec = ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
@@ -180,10 +173,7 @@ pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
Some(existing) => {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
*existing = spec;
|
||||
}
|
||||
Some(existing) => *existing = spec,
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,13 +165,6 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
.into_iter()
|
||||
.filter_map(|v| serde_json::from_value::<Entry>(v).ok())
|
||||
.filter(|e| safe_segment(&e.id) && safe_segment(&e.version))
|
||||
.map(|mut e| {
|
||||
e.id = canonical_id(&e.id).to_owned();
|
||||
if let Some(name) = provider::builtin_name(&e.id) {
|
||||
e.name = name.to_owned();
|
||||
}
|
||||
e
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -239,16 +232,11 @@ fn choose<'a>(entry: &'a Entry, platform: Platform, on_path: &dyn Fn(&str) -> bo
|
||||
None
|
||||
}
|
||||
|
||||
/// Registry ids that map to a shorter built-in provider id (`<config>/agents/<id>.toml`).
|
||||
const BUILTIN_ALIASES: &[(&str, &str)] =
|
||||
&[("github-copilot-cli", "copilot"), ("qwen-code", "qwen"), ("mistral-vibe", "vibe")];
|
||||
|
||||
fn canonical_id(id: &str) -> &str {
|
||||
BUILTIN_ALIASES.iter().find_map(|&(alias, canonical)| (alias == id).then_some(canonical)).unwrap_or(id)
|
||||
}
|
||||
/// Registry agents that are built-in ones under another id.
|
||||
const BUILTIN_ALIASES: &[&str] = &["github-copilot-cli", "qwen-code", "mistral-vibe"];
|
||||
|
||||
fn is_builtin(id: &str) -> bool {
|
||||
provider::is_builtin(canonical_id(id))
|
||||
provider::is_builtin(id) || BUILTIN_ALIASES.contains(&id)
|
||||
}
|
||||
|
||||
fn on_path(command: &str) -> bool {
|
||||
@@ -399,7 +387,6 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
Ok(text) => text,
|
||||
@@ -631,7 +618,6 @@ fn install_uv(
|
||||
|
||||
/// Deletes a registry agent's file and installed files.
|
||||
pub fn remove(paths: &RegistryPaths, id: &str) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
if !safe_segment(id) {
|
||||
return Err(IdeError::invalid(format!("invalid agent id {id}")));
|
||||
}
|
||||
@@ -960,64 +946,4 @@ mod tests {
|
||||
assert!(remove(&p, "amp-acp").is_err());
|
||||
assert!(p.agent_file("amp-acp").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_github_copilot_cli_to_builtin_copilot_and_tracks_updates() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let p = paths(dir.path());
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.105",
|
||||
"description":"GitHub's AI pair programmer",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let entries = parse(index).unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!((entries[0].id.as_str(), entries[0].name.as_str()), ("copilot", "GitHub Copilot"));
|
||||
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(
|
||||
(shown[0].id.as_str(), shown[0].name.as_str(), shown[0].installed.as_deref()),
|
||||
("copilot", "GitHub Copilot", None)
|
||||
);
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
|
||||
}
|
||||
.write(&p.agent_file("copilot"))
|
||||
.unwrap();
|
||||
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
assert_eq!((shown[0].installed.as_deref(), shown[0].update), (Some("1.0.104"), true));
|
||||
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir)).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![AgentProvider {
|
||||
id: spec.id,
|
||||
name: spec.name,
|
||||
command: spec.command,
|
||||
installed: true,
|
||||
config: vec![],
|
||||
commands: vec![],
|
||||
source: spec.source,
|
||||
}];
|
||||
mark_updates(&p, &mut providers);
|
||||
assert_eq!(
|
||||
providers[0].source,
|
||||
AgentSource::Registry { version: "1.0.104".into(), update: Some("1.0.105".into()) }
|
||||
);
|
||||
|
||||
remove(&p, "github-copilot-cli").unwrap();
|
||||
let fallback = provider::load(Some(&p.agents_dir)).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(fallback.source, AgentSource::Builtin);
|
||||
}
|
||||
}
|
||||
@@ -942,78 +942,3 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
|
||||
}
|
||||
assert_eq!(git(&["worktree", "list", "--porcelain"]).matches("worktree ").count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reload_providers_updates_registry_install_clears_stale_probes_and_notifies_subscribers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agents_dir = tmp.path().join("agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
let fake_bin = tmp.path().join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&fake_bin, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&fake_bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let connector: Connector = {
|
||||
let agent = agent.clone();
|
||||
Arc::new(move |_spec, _cwd, client, _stderr| {
|
||||
let (a, b) = duplex(1 << 20);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let server = Peer::connect_framed(br, bw, agent.clone(), Framing::Lines);
|
||||
agent.servers.lock().push(server);
|
||||
Ok(Peer::connect_framed(ar, aw, client, Framing::Lines))
|
||||
})
|
||||
};
|
||||
let mgr = AgentManager::with_connector(
|
||||
AgentPaths {
|
||||
project_root: tmp.path().to_path_buf(),
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
custom_agents_dir: Some(agents_dir.clone()),
|
||||
home_dir: None,
|
||||
},
|
||||
tokio::runtime::Handle::current(),
|
||||
connector,
|
||||
);
|
||||
|
||||
// Seed a stale failed probe for copilot before installing its custom TOML.
|
||||
mgr.shared.probes.lock().insert(
|
||||
"copilot".into(),
|
||||
AgentProbe {
|
||||
provider: "copilot".into(),
|
||||
name: None,
|
||||
version: None,
|
||||
protocol: "ACP".into(),
|
||||
capabilities: AgentCapabilities::default(),
|
||||
auth_methods: Vec::new(),
|
||||
error: Some("copilot --acp was not found on PATH.".into()),
|
||||
},
|
||||
);
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let events_sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |ev| events_sink.lock().push(ev)));
|
||||
|
||||
let toml = format!(
|
||||
"name = \"GitHub Copilot\"\ncommand = {:?}\nargs = [\"--acp\", \"--stdio\"]\n",
|
||||
fake_bin.to_string_lossy()
|
||||
);
|
||||
std::fs::write(agents_dir.join("copilot.toml"), toml).unwrap();
|
||||
|
||||
mgr.reload_providers();
|
||||
|
||||
assert!(events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)));
|
||||
assert!(!mgr.shared.probes.lock().contains_key("copilot"));
|
||||
|
||||
let copilot = mgr.providers().into_iter().find(|p| p.id == "copilot").unwrap();
|
||||
assert!(copilot.installed);
|
||||
assert!(copilot.command.contains(&*fake_bin.to_string_lossy()));
|
||||
|
||||
let probe = mgr.probe("copilot", false).await.unwrap();
|
||||
assert!(probe.error.is_none());
|
||||
}
|
||||
@@ -48,24 +48,8 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
Ok(Created { path, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
|
||||
/// worktree (a pruned registration, a moved repository, a deleted `.git` file)
|
||||
/// it fails with "is not a working tree". A folder under `worktrees_dir` is still
|
||||
/// ours, so it is removed directly to keep the task deletable (a stale
|
||||
/// registration prunes later); anything else keeps git's error.
|
||||
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
|
||||
let repo = repo_at(project_root)?;
|
||||
let err = match repo.remove_worktree(path, true) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
|
||||
return Err(err);
|
||||
}
|
||||
std::fs::remove_dir_all(path).map_err(|e| IdeError::internal(e.to_string()))
|
||||
pub(crate) fn remove(project_root: &Path, path: &Path) -> IdeResult<()> {
|
||||
repo_at(project_root)?.remove_worktree(path, true)
|
||||
}
|
||||
|
||||
/// Files under `cwd` that differ from `base` (untracked files included), with line counts.
|
||||
@@ -169,7 +153,7 @@ mod tests {
|
||||
assert!(snapshot(&dir).unwrap().is_empty());
|
||||
assert_eq!(file_at(&dir, &dir.join("a.txt"), "HEAD").unwrap(), None);
|
||||
assert!(create(&dir, &tmp.path().join("wt"), "Edit A", None).is_err());
|
||||
assert!(remove(&dir, tmp.path(), &dir).is_err());
|
||||
assert!(remove(&dir, &dir).is_err());
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
@@ -218,38 +202,7 @@ mod tests {
|
||||
|
||||
// A second task with the same title gets its own worktree.
|
||||
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
|
||||
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
|
||||
remove(&repo, &created.path).unwrap();
|
||||
assert!(!created.path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_worktree_registration_still_leaves_a_deletable_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
// A pruned registration (the repository moved, `git worktree prune` ran).
|
||||
let created = create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap();
|
||||
let registration = repo.join(".git/worktrees").join(created.path.file_name().unwrap());
|
||||
std::fs::remove_dir_all(registration).unwrap();
|
||||
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// A deleted `.git` file in the worktree itself.
|
||||
let created = create(&repo, &tmp.path().join("wt"), "Edit B", None).unwrap();
|
||||
std::fs::remove_file(created.path.join(".git")).unwrap();
|
||||
remove(&repo, &tmp.path().join("wt"), &created.path).unwrap();
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// A folder outside the worktrees directory is never deleted by hand.
|
||||
let elsewhere = tmp.path().join("elsewhere");
|
||||
std::fs::create_dir(&elsewhere).unwrap();
|
||||
std::fs::write(elsewhere.join("keep.txt"), "x\n").unwrap();
|
||||
assert!(remove(&repo, &tmp.path().join("wt"), &elsewhere).is_err());
|
||||
assert!(elsewhere.join("keep.txt").exists());
|
||||
}
|
||||
}
|
||||
@@ -15,5 +15,8 @@ specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -2,12 +2,11 @@
|
||||
//! line to a callback, and cancellation kills the whole process group (the
|
||||
//! `mvnw` / `gradlew` wrapper scripts start the JVM as a child).
|
||||
|
||||
use ide_core::process::kill_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -23,6 +22,18 @@ pub(crate) struct Output {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
fn kill_tree(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
if let Ok(pid) = i32::try_from(child.id()) {
|
||||
// SAFETY: plain syscall; the group was created by `process_group(0)` at spawn.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// `program` as spawnable: a bare name (`mvn`, `mvn.cmd`) resolves on the IDE's
|
||||
/// search path — the login shell's `PATH` plus version-manager shims — since the
|
||||
/// app's own `PATH` can be minimal and `Command` would not see `mvn` there.
|
||||
@@ -69,8 +80,12 @@ pub(crate) fn run_with_env(
|
||||
let mut command = Command::new(&program);
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
// Its own group: `mvnw` / `gradlew` start the JVM as a child, and cancelling kills both.
|
||||
ide_core::process::prepare(ide_core::process::own_group(&mut command));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(&mut command);
|
||||
if clear_env {
|
||||
command.env_clear().envs(env).envs(encoding.env);
|
||||
}
|
||||
|
||||
@@ -18,8 +18,5 @@ tokio-util.workspace = true
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_Security", "Win32_System_Registry", "Win32_Foundation"] }
|
||||
@@ -36,21 +36,12 @@ pub enum IdeEvent {
|
||||
base_version: u32,
|
||||
version: u32,
|
||||
changes: Vec<TextChange>,
|
||||
/// Part of a grouped transaction; the editor must not record a file-local undo.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
workspace_edit: bool,
|
||||
},
|
||||
/// A document's dirty flag changed (saved / modified externally).
|
||||
DocDirty {
|
||||
doc: DocId,
|
||||
dirty: bool,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
paths: Vec<crate::IpcPath>,
|
||||
},
|
||||
/// An open document's language changed (Settings › File Types, Override File
|
||||
/// Type), or its UI mode (a framework's root marker appeared or went).
|
||||
DocLanguage {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
//! Child-process helpers shared by every crate that spawns tools.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
#[cfg(windows)]
|
||||
use std::process::Stdio;
|
||||
use std::process::{Child, Command};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
|
||||
/// with other flags (and then call [`host_env`] themselves). Prefer [`prepare`] otherwise.
|
||||
@@ -28,70 +25,6 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
host_env(cmd)
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
|
||||
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
|
||||
pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
/// - Windows: `taskkill /T /F`, which walks the tree from the child's process id.
|
||||
pub fn kill_tree(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
signal_group(child, libc::SIGKILL);
|
||||
#[cfg(windows)]
|
||||
taskkill_tree(child);
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// [`kill_tree`] that first asks the group to exit: `SIGTERM`, then `grace`, then `SIGKILL`.
|
||||
/// Git removes its `index.lock` on `SIGTERM`, where `SIGKILL` leaves it behind and the next
|
||||
/// git command fails. Windows has no such signal to send from outside the child's console,
|
||||
/// so there it is [`kill_tree`].
|
||||
pub fn terminate_tree(child: &mut Child, grace: Duration) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
signal_group(child, libc::SIGTERM);
|
||||
// Sleep rather than `try_wait`: the child stays unreaped, so its process id (and the
|
||||
// group id) cannot be reused before the `SIGKILL` below.
|
||||
std::thread::sleep(grace);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = grace;
|
||||
kill_tree(child);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
if let Ok(pid) = libc::pid_t::try_from(child.id()) {
|
||||
// SAFETY: plain syscall. The child is not reaped yet, so `-pid` is still its group (or
|
||||
// no group at all when it was not spawned with `own_group`, and the call fails).
|
||||
unsafe {
|
||||
libc::kill(-pid, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn taskkill_tree(child: &Child) {
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &child.id().to_string()])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
}
|
||||
|
||||
/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and
|
||||
/// its hooks point `LD_LIBRARY_PATH`, `PATH`, `XDG_DATA_DIRS`, `GIO_MODULE_DIR`, `GTK_PATH`,
|
||||
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
|
||||
@@ -664,71 +597,3 @@ mod tests {
|
||||
assert_eq!(find_executable("nope", &search), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod kill_tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Runs `script` in `sh` as its own group's leader and waits for it to write `ready`.
|
||||
fn start(script: &str, ready: &Path) -> Child {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.arg("-c").arg(script);
|
||||
let child = own_group(&mut cmd).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !ready.exists() {
|
||||
assert!(Instant::now() < deadline, "the script never got ready");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
child
|
||||
}
|
||||
|
||||
fn assert_gone(pid: libc::pid_t) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
// SAFETY: signal 0 only checks that the process exists.
|
||||
while unsafe { libc::kill(pid, 0) } == 0 {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_tree_kills_what_the_child_started() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let script = format!("sleep 30 & echo $! > '{0}.tmp' && mv '{0}.tmp' '{0}'; wait", pid_file.display());
|
||||
let mut child = start(&script, &pid_file);
|
||||
let grandchild: libc::pid_t = std::fs::read_to_string(&pid_file).unwrap().trim().parse().unwrap();
|
||||
kill_tree(&mut child);
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
assert_gone(grandchild);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_tree_lets_the_child_clean_up() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (ready, cleaned) = (dir.path().join("ready"), dir.path().join("cleaned"));
|
||||
let script = format!(
|
||||
"trap 'touch \"{}\"; exit 0' TERM; touch \"{}\"; sleep 30 & wait",
|
||||
cleaned.display(),
|
||||
ready.display()
|
||||
);
|
||||
let mut child = start(&script, &ready);
|
||||
terminate_tree(&mut child, Duration::from_millis(500));
|
||||
assert!(cleaned.exists(), "the SIGTERM handler ran before the SIGKILL");
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_tree_still_kills_a_child_that_ignores_sigterm() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ready = dir.path().join("ready");
|
||||
let script = format!("trap '' TERM; touch \"{}\"; while :; do sleep 1; done", ready.display());
|
||||
let mut child = start(&script, &ready);
|
||||
let started = Instant::now();
|
||||
terminate_tree(&mut child, Duration::from_millis(50));
|
||||
assert!(child.try_wait().unwrap().is_some(), "the child is reaped");
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
@@ -548,7 +548,6 @@ pub struct LanguagesSettings {
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub prettier: PrettierSettings,
|
||||
pub java: JavaSettings,
|
||||
pub ruby: RubySettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -606,13 +605,6 @@ impl Default for PythonSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RubySettings {
|
||||
/// Project interpreter executable; empty = auto-detect (`.ruby-version`, mise / asdf, else `ruby` on PATH).
|
||||
pub interpreter: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct NodeSettings {
|
||||
|
||||
@@ -97,16 +97,6 @@ pub struct TextEdit {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct WorkspaceEdit {
|
||||
pub files: Vec<FileEdit>,
|
||||
/// Content fingerprints captured before presenting an edit for confirmation.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub preconditions: Vec<WorkspaceEditPrecondition>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct WorkspaceEditPrecondition {
|
||||
pub path: crate::IpcPath,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
impl WorkspaceEdit {
|
||||
@@ -118,26 +108,17 @@ impl WorkspaceEdit {
|
||||
let mut resolve_aliases = true;
|
||||
for file in std::mem::take(&mut self.files) {
|
||||
match file {
|
||||
FileEdit::Edit { path, edits, version } => {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
let path = if resolve_aliases {
|
||||
dunce::canonicalize(&path).unwrap_or_else(|_| path.to_path_buf())
|
||||
} else {
|
||||
path.to_path_buf()
|
||||
};
|
||||
let index = *batch.entry(path.clone()).or_insert_with(|| {
|
||||
files.push(FileEdit::Edit { path: path.clone().into(), edits: Vec::new(), version });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits: Vec::new() });
|
||||
files.len() - 1
|
||||
});
|
||||
let FileEdit::Edit { edits: own, version: expected, .. } = &mut files[index] else {
|
||||
unreachable!()
|
||||
};
|
||||
if expected.is_some() && version.is_some() && *expected != version {
|
||||
// Keep incompatible constraints so application rejects them
|
||||
// before changing any file instead of silently losing one.
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version });
|
||||
continue;
|
||||
}
|
||||
*expected = expected.or(version);
|
||||
let FileEdit::Edit { edits: own, .. } = &mut files[index] else { unreachable!() };
|
||||
for edit in edits {
|
||||
if !own.contains(&edit) {
|
||||
own.push(edit);
|
||||
@@ -159,26 +140,10 @@ impl WorkspaceEdit {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum FileEdit {
|
||||
Edit {
|
||||
path: crate::IpcPath,
|
||||
edits: Vec<TextEdit>,
|
||||
/// LSP TextDocumentEdit version; null/unversioned edits use content preconditions.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
version: Option<i32>,
|
||||
},
|
||||
Create {
|
||||
path: crate::IpcPath,
|
||||
overwrite: bool,
|
||||
},
|
||||
Rename {
|
||||
from: crate::IpcPath,
|
||||
to: crate::IpcPath,
|
||||
},
|
||||
Delete {
|
||||
path: crate::IpcPath,
|
||||
recursive: bool,
|
||||
},
|
||||
Edit { path: crate::IpcPath, edits: Vec<TextEdit> },
|
||||
Create { path: crate::IpcPath, overwrite: bool },
|
||||
Rename { from: crate::IpcPath, to: crate::IpcPath },
|
||||
Delete { path: crate::IpcPath, recursive: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
@@ -289,7 +254,7 @@ mod workspace_edit_tests {
|
||||
std::fs::write(&real, "add()").unwrap();
|
||||
std::os::unix::fs::symlink(&real, &alias).unwrap();
|
||||
let change = TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() };
|
||||
let edit = |path: PathBuf| FileEdit::Edit { path: path.into(), edits: vec![change.clone()], version: None };
|
||||
let edit = |path: PathBuf| FileEdit::Edit { path: path.into(), edits: vec![change.clone()] };
|
||||
let mut workspace = WorkspaceEdit {
|
||||
files: vec![
|
||||
edit(real.clone()),
|
||||
@@ -297,7 +262,6 @@ mod workspace_edit_tests {
|
||||
FileEdit::Create { path: dir.path().join("other").into(), overwrite: false },
|
||||
edit(real),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 3);
|
||||
|
||||
@@ -18,7 +18,6 @@ pub enum Tool {
|
||||
Go,
|
||||
Maven,
|
||||
Gradle,
|
||||
Ruby,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
@@ -31,7 +30,6 @@ impl Tool {
|
||||
Tool::Go => &["go", "golang"],
|
||||
Tool::Maven => &["maven"],
|
||||
Tool::Gradle => &["gradle"],
|
||||
Tool::Ruby => &["ruby"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,5 +13,8 @@ specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1,16 +1,11 @@
|
||||
//! Child processes of the docker CLI: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (CLI plugins such as compose)
|
||||
/// gets to exit on `SIGTERM`, and clean up, before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
@@ -25,13 +20,36 @@ pub(crate) enum Stream {
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}")))
|
||||
}
|
||||
|
||||
/// Kills the child and, on Unix, its whole process group (CLI plugins such as compose).
|
||||
pub(crate) fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child leads its own process group (`prepare`).
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
@@ -70,11 +88,11 @@ pub(crate) fn run_with_input(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::unavailable("docker did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -148,7 +166,7 @@ pub(crate) fn stream(
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
@@ -171,7 +189,7 @@ pub(crate) fn stream(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -13,3 +13,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
@@ -1,16 +1,11 @@
|
||||
//! Child processes of the gh CLI: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (gh spawns git and helpers)
|
||||
/// gets to exit on `SIGTERM` before `SIGKILL`: git removes its lock files on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
@@ -25,13 +20,36 @@ pub(crate) enum Stream {
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}")))
|
||||
}
|
||||
|
||||
/// Kills the child and, on Unix, its whole process group (gh spawns git and helpers).
|
||||
pub(crate) fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child leads its own process group (`prepare`).
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
@@ -74,11 +92,11 @@ pub(crate) fn run_with_input(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::unavailable("gh did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -152,7 +170,7 @@ pub(crate) fn stream(
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
@@ -175,7 +193,7 @@ pub(crate) fn stream(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -57,7 +57,6 @@ fn migrate_entries(data: &Path, local: &Path) {
|
||||
"notebook-runtime",
|
||||
"server",
|
||||
"java-usages-1.1.1.jar",
|
||||
"java-usages-1.2.0.jar",
|
||||
"agents/registry.json",
|
||||
]
|
||||
.into_iter()
|
||||
@@ -299,7 +298,6 @@ mod tests {
|
||||
"agents/tools",
|
||||
"agents/registry.json",
|
||||
"java-usages-1.1.1.jar",
|
||||
"java-usages-1.2.0.jar",
|
||||
] {
|
||||
assert!(is_local(Path::new(entry)), "{entry}");
|
||||
assert_eq!(
|
||||
|
||||
@@ -174,7 +174,6 @@ impl Host {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.shutdown();
|
||||
project.notebooks.stop_admission();
|
||||
// What the closing window started goes with it — the builds and searches it
|
||||
@@ -252,13 +251,6 @@ impl Host {
|
||||
);
|
||||
}
|
||||
|
||||
/// Called before desktop exit, which may bypass document destructors.
|
||||
pub fn clear_workspace_edit_history_on_exit(&self) {
|
||||
for project in self.projects() {
|
||||
project.documents.clear_workspace_edit_history();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops what this host started: notebook kernels, language servers, agents, runs and terminals.
|
||||
/// For a process that exits without dropping the host (the remote server).
|
||||
pub async fn shutdown(&self) {
|
||||
@@ -270,7 +262,6 @@ impl Host {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
}
|
||||
|
||||
@@ -63,21 +63,13 @@ pub async fn registry_install(
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result??;
|
||||
for project in host.projects() {
|
||||
project.agents.reload_providers();
|
||||
}
|
||||
Ok(())
|
||||
result?
|
||||
}
|
||||
|
||||
/// Removes a registry agent: its agent file and installed files.
|
||||
pub async fn registry_remove(host: &Host, _window: &str, id: String) -> IdeResult<()> {
|
||||
let paths = registry_paths(host);
|
||||
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)??;
|
||||
for project in host.projects() {
|
||||
project.agents.reload_providers();
|
||||
}
|
||||
Ok(())
|
||||
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
|
||||
@@ -210,10 +210,8 @@ pub async fn maven_exclude_dependency(
|
||||
let (path, text, range) = declaring_pom(&project, &pom, &dependency)?;
|
||||
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
|
||||
Some(Exclusion::Edit(edit)) => {
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit { path: path.clone().into(), edits: vec![edit], version: None }],
|
||||
..Default::default()
|
||||
};
|
||||
let edit =
|
||||
WorkspaceEdit { files: vec![FileEdit::Edit { path: path.clone().into(), edits: vec![edit] }] };
|
||||
apply_workspace_edit(&project.documents, &edit)?;
|
||||
}
|
||||
Some(Exclusion::Present) => {}
|
||||
|
||||
@@ -127,7 +127,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?).await
|
||||
});
|
||||
d.add("doc_set_line_ending", |c| async move {
|
||||
blocking(move || doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)).await
|
||||
doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)
|
||||
});
|
||||
d.add("doc_outline", |c| async move { doc_outline(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_folding", |c| async move { doc_folding(&c.host, &c.window, c.arg("doc")?).await });
|
||||
|
||||
@@ -56,16 +56,14 @@ pub async fn copy_merge(
|
||||
if overwrite {
|
||||
project.history.record_deletion(&to, DELETE_SNAPSHOT_LIMIT);
|
||||
}
|
||||
project.with_disk_sync(|| {
|
||||
ide_vfs::copy_merge(
|
||||
&from,
|
||||
&to,
|
||||
overwrite,
|
||||
Some(&project.root),
|
||||
&project.exclude_globs(),
|
||||
(&source_root, &destination_root),
|
||||
)
|
||||
})
|
||||
ide_vfs::copy_merge(
|
||||
&from,
|
||||
&to,
|
||||
overwrite,
|
||||
Some(&project.root),
|
||||
&project.exclude_globs(),
|
||||
(&source_root, &destination_root),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -73,28 +71,24 @@ pub async fn copy_merge(
|
||||
/// Files of a deleted folder snapshotted in Local History.
|
||||
const DELETE_SNAPSHOT_LIMIT: usize = 2000;
|
||||
|
||||
/// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
|
||||
pub async fn read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<FileEntry>> {
|
||||
let project = host.project(window);
|
||||
host.blocking(move || {
|
||||
let excludes = project
|
||||
.map(|p| {
|
||||
let globs = p.exclude_globs();
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// project-root patterns (`/build`) when the project is a repo subfolder.
|
||||
let repo = p.root.ancestors().find(|d| d.join(".git").exists());
|
||||
match repo.and_then(|r| p.root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
None => globs,
|
||||
pub fn read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<FileEntry>> {
|
||||
let excludes = host
|
||||
.project(window)
|
||||
.map(|p| {
|
||||
let globs = p.exclude_globs();
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// project-root patterns (`/build`) when the project is a repo subfolder.
|
||||
let repo = p.root.ancestors().find(|d| d.join(".git").exists());
|
||||
match repo.and_then(|r| p.root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ide_vfs::read_dir(&path, &excludes)
|
||||
})
|
||||
.await
|
||||
None => globs,
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ide_vfs::read_dir(&path, &excludes)
|
||||
}
|
||||
|
||||
/// Creates an empty file; inside a project, honours the EditorConfig
|
||||
|
||||
@@ -59,7 +59,7 @@ async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
let external_build = if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
let mut info = project.lsp.java_launch(&module, test, build && !delegated, delegated, cancel).await?;
|
||||
let mut info = project.lsp.java_launch(&module, test, build && !delegated, cancel).await?;
|
||||
let lsp_ms = started.elapsed().as_millis();
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
|
||||
@@ -1,33 +1,9 @@
|
||||
use super::doc::blocking;
|
||||
use crate::Host;
|
||||
use crate::apply_workspace_edit as apply_edit;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::{DocId, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
|
||||
use ide_lsp::types::*;
|
||||
|
||||
async fn prepare_actions(
|
||||
project: std::sync::Arc<crate::Project>,
|
||||
doc: DocId,
|
||||
version: u32,
|
||||
mut actions: Vec<CodeAction>,
|
||||
) -> IdeResult<Vec<CodeAction>> {
|
||||
blocking(move || {
|
||||
if project.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
ide_core::error::ErrorKind::OutOfSync,
|
||||
"document changed while computing code actions; request them again",
|
||||
));
|
||||
}
|
||||
for action in &mut actions {
|
||||
if let Some(edit) = &mut action.edit {
|
||||
project.documents.prepare_workspace_edit(edit)?;
|
||||
}
|
||||
}
|
||||
Ok(actions)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn lsp_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -162,11 +138,7 @@ pub async fn lsp_code_actions(
|
||||
range: Range,
|
||||
only: Vec<String>,
|
||||
) -> IdeResult<Vec<CodeAction>> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let actions = project.lsp.code_actions(doc, range, only).await?;
|
||||
prepare_actions(project, doc, version, actions).await
|
||||
host.project(window)?.lsp.code_actions(doc, range, only).await
|
||||
}
|
||||
|
||||
/// Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability).
|
||||
@@ -178,15 +150,11 @@ pub async fn lsp_code_action_query(
|
||||
range: Range,
|
||||
only: Vec<String>,
|
||||
) -> IdeResult<CodeActionQuery> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.code_action_query(doc, range, only, cancel).await;
|
||||
let result = lsp.code_action_query(doc, range, only, cancel).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
result.actions = prepare_actions(project, doc, version, result.actions).await?;
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
/// Resolves a code action's edit without applying it (intention preview).
|
||||
@@ -199,28 +167,19 @@ pub async fn lsp_resolve_code_action(
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
Ok(prepare_actions(project, doc, version, vec![action]).await?.remove(0))
|
||||
host.project(window)?.lsp.resolve_code_action(doc, action).await
|
||||
}
|
||||
|
||||
/// Resolves (if needed), applies the edit, then runs the command of a code action.
|
||||
pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action: CodeAction) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
let action = if action.edit.is_none() && action.command.is_none() {
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = project.lsp.resolve_code_action(doc, action).await?;
|
||||
prepare_actions(project.clone(), doc, version, vec![action]).await?.remove(0)
|
||||
project.lsp.resolve_code_action(doc, action).await?
|
||||
} else {
|
||||
action
|
||||
};
|
||||
if let Some(edit) = &action.edit {
|
||||
let documents = project.documents.clone();
|
||||
let edit = edit.clone();
|
||||
blocking(move || apply_edit(&documents, &edit)).await?;
|
||||
apply_edit(&project.documents, edit)?;
|
||||
}
|
||||
if let Some(command) = action.command {
|
||||
project.lsp.execute_command(doc, command).await?;
|
||||
@@ -241,24 +200,11 @@ pub async fn lsp_rename(
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
) -> IdeResult<Renamed> {
|
||||
let project = host.project(window)?;
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.rename(doc, pos, new_name, cancel).await;
|
||||
let result = lsp.rename(doc, pos, new_name, cancel).await;
|
||||
host.end_request(request);
|
||||
let mut renamed = result?;
|
||||
blocking(move || {
|
||||
if project.documents.version(doc)? != version {
|
||||
return Err(ide_core::IdeError::new(
|
||||
ide_core::error::ErrorKind::OutOfSync,
|
||||
"document changed while computing rename; request it again",
|
||||
));
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
|
||||
Ok(renamed)
|
||||
})
|
||||
.await
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn lsp_format(
|
||||
@@ -333,43 +279,21 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu
|
||||
}
|
||||
|
||||
/// Applies a (previewed) workspace edit, e.g. after rename confirmation.
|
||||
pub async fn apply_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
pub fn apply_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
// Multi-file refactorings leave a Local History point to go back to.
|
||||
let paths: Vec<&std::path::Path> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if edit.files.len() > 1 {
|
||||
project.record_before_refactoring(&paths, "Apply changes");
|
||||
}
|
||||
apply_edit(&project.documents, &edit)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn prepare_workspace_edit(host: &Host, window: &str, mut edit: WorkspaceEdit) -> IdeResult<WorkspaceEdit> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn undo_workspace_edit(host: &Host, window: &str, id: u32) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.documents.undo_workspace_edit(id)).await
|
||||
}
|
||||
|
||||
pub async fn redo_workspace_edit(host: &Host, window: &str, id: u32) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.documents.redo_workspace_edit(id)).await
|
||||
// Multi-file refactorings leave a Local History point to go back to.
|
||||
let paths: Vec<&std::path::Path> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if edit.files.len() > 1 {
|
||||
project.record_before_refactoring(&paths, "Apply changes");
|
||||
}
|
||||
apply_edit(&project.documents, &edit)
|
||||
}
|
||||
|
||||
/// Runs a server command (`workspace/executeCommand`), e.g. a completion item's
|
||||
@@ -517,7 +441,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
|
||||
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
|
||||
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?) });
|
||||
d.add("lsp_resolve_command", |c| async move {
|
||||
lsp_resolve_command(
|
||||
&c.host,
|
||||
@@ -541,12 +465,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"prepare_workspace_edit",
|
||||
|c| async move { prepare_workspace_edit(&c.host, &c.window, c.arg("edit")?).await },
|
||||
);
|
||||
d.add("redo_workspace_edit", |c| async move { redo_workspace_edit(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("undo_workspace_edit", |c| async move { undo_workspace_edit(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("lsp_execute_command", |c| async move {
|
||||
lsp_execute_command(&c.host, &c.window, c.arg("doc")?, c.arg("command")?).await
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ pub mod notebook;
|
||||
pub mod project;
|
||||
mod python;
|
||||
pub mod refactor;
|
||||
pub mod routes;
|
||||
pub mod run;
|
||||
pub mod sdk;
|
||||
pub mod search;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! File move / rename refactoring: reference updates from the language
|
||||
//! servers, the move itself (one undoable step) and its undo.
|
||||
use crate::Host;
|
||||
use crate::apply_workspace_edit;
|
||||
use crate::rpc::Dispatcher;
|
||||
|
||||
use ide_core::{IdeResult, RequestId, WorkspaceEdit};
|
||||
@@ -25,12 +26,7 @@ pub async fn refactor_file_move_edits(
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
blocking(move || {
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
result
|
||||
}
|
||||
|
||||
/// Applies `edit` (from [`refactor_file_move_edits`], possibly empty), moves the
|
||||
@@ -46,7 +42,7 @@ pub async fn refactor_move_files(
|
||||
let p = project.clone();
|
||||
let moved = moves.clone();
|
||||
let id = blocking(move || {
|
||||
let apply = |e: &WorkspaceEdit| p.documents.apply_file_move_edits(e);
|
||||
let apply = |e: &WorkspaceEdit| apply_workspace_edit(&p.documents, e);
|
||||
p.moves.perform(&p.documents, Some(&p.history), &moved, &edit, &label, &apply)
|
||||
})
|
||||
.await?;
|
||||
@@ -81,17 +77,13 @@ pub async fn refactor_file_move_text_edits(
|
||||
let cancel = token.clone();
|
||||
let result = blocking(move || {
|
||||
let replacements = ide_workspace::text_refs::move_replacements(&project.root, &project.roots(), &moves);
|
||||
let mut edit = ide_workspace::text_refs::find_text_occurrences(
|
||||
let edit = ide_workspace::text_refs::find_text_occurrences(
|
||||
&project.root,
|
||||
&project.exclude_globs(),
|
||||
&replacements,
|
||||
&|| cancel.is_cancelled(),
|
||||
);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
if cancel.is_cancelled() { Err(ide_core::IdeError::cancelled()) } else { Ok(edit) }
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
//! Spring Web mappings, source side: the project's Java and Kotlin files that could
|
||||
//! declare a route, with their text. The UI owns the annotation parser and the index
|
||||
//! it feeds, so this side stays a cheap scan.
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::IdeResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Files handed out at most, and bytes in total: a project's controllers fit well
|
||||
/// inside these, and the UI indexes them once.
|
||||
const MAX_FILES: usize = 1024;
|
||||
const MAX_BYTES: usize = 48 << 20;
|
||||
/// A single source bigger than this is not a controller.
|
||||
const MAX_FILE_BYTES: u64 = 4 << 20;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RouteSource {
|
||||
pub path: String,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The files Spring mappings can live in: Java and Kotlin sources.
|
||||
fn declares_mappings(path: &Path) -> bool {
|
||||
matches!(path.extension().and_then(|e| e.to_str()), Some("java" | "kt" | "kts"))
|
||||
}
|
||||
|
||||
/// Files under `root` whose text names a mapping: `ignore` rules and `excludes`
|
||||
/// decide what counts, and the UI ranks the matches itself.
|
||||
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<RouteSource> {
|
||||
let found: Mutex<Vec<RouteSource>> = Mutex::new(Vec::new());
|
||||
let bytes = AtomicUsize::new(0);
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if !declares_mappings(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
// Only a file that names a mapping annotation is worth parsing.
|
||||
if !text.contains("Mapping") {
|
||||
return;
|
||||
}
|
||||
let Ok(mut found) = found.lock() else { return };
|
||||
if found.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
bytes.fetch_add(text.len(), Ordering::Relaxed);
|
||||
found.push(RouteSource { path: path.to_string_lossy().into_owned(), text });
|
||||
});
|
||||
let mut files = found.into_inner().unwrap_or_default();
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
files
|
||||
}
|
||||
|
||||
/// The folders to scan: the project folder itself first, then content roots outside it
|
||||
/// (`content_roots` lists only the ones outside, so the project folder is never implied —
|
||||
/// forgetting it scans nothing).
|
||||
fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots);
|
||||
roots
|
||||
}
|
||||
|
||||
/// Every mapping source of the project, for the request-path index.
|
||||
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
let excludes = project.search_excludes();
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &excludes));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?} (excludes: {})", project.root, excludes.len()),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_project_folder_is_scanned_even_without_other_content_roots() {
|
||||
let root = Path::new("/p/demo");
|
||||
assert_eq!(scan_roots(root, Vec::new()), [PathBuf::from("/p/demo")]);
|
||||
assert_eq!(
|
||||
scan_roots(root, vec![PathBuf::from("/p/elsewhere")]),
|
||||
[PathBuf::from("/p/demo"), PathBuf::from("/p/elsewhere")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_java_and_kotlin_sources_are_read() {
|
||||
for (name, expected) in
|
||||
[("A.java", true), ("B.kt", true), ("C.kts", true), ("D.txt", false), ("pom.xml", false), ("noext", false)]
|
||||
{
|
||||
assert_eq!(declares_mappings(Path::new(name)), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_name_no_mapping_are_left_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
|
||||
std::fs::write(tmp.path().join("src/Ctl.java"), "class Ctl { @GetMapping(\"/a\") void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Plain.java"), "class Plain { void a() {} }").unwrap();
|
||||
std::fs::write(tmp.path().join("src/Notes.txt"), "@GetMapping(\"/a\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &[]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(Path::new(&files[0].path).ends_with("src/Ctl.java"), "{}", files[0].path);
|
||||
assert!(files[0].text.contains("@GetMapping"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_folders_are_skipped() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("module/src")).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("build")).unwrap();
|
||||
std::fs::write(tmp.path().join("module/src/A.java"), "@RequestMapping(\"/a\")").unwrap();
|
||||
std::fs::write(tmp.path().join("build/B.java"), "@RequestMapping(\"/b\")").unwrap();
|
||||
let files = sources_in(tmp.path(), &["build/**".to_owned()]);
|
||||
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
|
||||
assert!(Path::new(&files[0].path).ends_with("module/src/A.java"), "{}", files[0].path);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +1,6 @@
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::Path;
|
||||
|
||||
const LIFETIME: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
|
||||
const DIRECTORY: &str = "terminal-images";
|
||||
|
||||
fn extension(mime: &str) -> IdeResult<&str> {
|
||||
match mime {
|
||||
"image/png" => Ok("png"),
|
||||
"image/jpeg" => Ok("jpg"),
|
||||
"image/gif" => Ok("gif"),
|
||||
"image/webp" => Ok("webp"),
|
||||
"image/bmp" => Ok("bmp"),
|
||||
"image/svg+xml" => Ok("svg"),
|
||||
"image/tiff" => Ok("tiff"),
|
||||
"image/x-icon" => Ok("ico"),
|
||||
"audio/wav" | "audio/x-wav" => Ok("wav"),
|
||||
"audio/mpeg" => Ok("mp3"),
|
||||
"audio/mp4" => Ok("m4a"),
|
||||
"audio/ogg" => Ok("ogg"),
|
||||
"audio/webm" | "video/webm" => Ok("webm"),
|
||||
"audio/flac" => Ok("flac"),
|
||||
"audio/aac" => Ok("aac"),
|
||||
"video/mp4" => Ok("mp4"),
|
||||
"video/ogg" => Ok("ogv"),
|
||||
"video/quicktime" => Ok("mov"),
|
||||
_ => Err(IdeError::invalid("unsupported clipboard media type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn owned_name(name: &str) -> bool {
|
||||
let name = name.strip_prefix(".partial-").unwrap_or(name);
|
||||
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
|
||||
id.len() == 32
|
||||
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
&& matches!(
|
||||
ext,
|
||||
"png"
|
||||
| "jpg"
|
||||
| "gif"
|
||||
| "webp"
|
||||
| "bmp"
|
||||
| "svg"
|
||||
| "tiff"
|
||||
| "ico"
|
||||
| "wav"
|
||||
| "mp3"
|
||||
| "m4a"
|
||||
| "ogg"
|
||||
| "webm"
|
||||
| "flac"
|
||||
| "aac"
|
||||
| "mp4"
|
||||
| "ogv"
|
||||
| "mov"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use super::*;
|
||||
@@ -63,7 +8,24 @@ mod unix {
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::time::SystemTime;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
const LIFETIME: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
const DIRECTORY: &str = "terminal-images";
|
||||
|
||||
fn extension(mime: &str) -> IdeResult<&str> {
|
||||
match mime {
|
||||
"image/png" => Ok("png"),
|
||||
"image/jpeg" => Ok("jpg"),
|
||||
"image/gif" => Ok("gif"),
|
||||
"image/webp" => Ok("webp"),
|
||||
"image/bmp" => Ok("bmp"),
|
||||
"image/svg+xml" => Ok("svg"),
|
||||
"image/tiff" => Ok("tiff"),
|
||||
"image/x-icon" => Ok("ico"),
|
||||
_ => Err(IdeError::invalid("unsupported image type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_directory(data_dir: &Path) -> io::Result<File> {
|
||||
if !data_dir.is_absolute() {
|
||||
@@ -93,6 +55,14 @@ mod unix {
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
fn owned_name(name: &str) -> bool {
|
||||
let name = name.strip_prefix(".partial-").unwrap_or(name);
|
||||
let Some((id, ext)) = name.strip_prefix("image-").and_then(|s| s.split_once('.')) else { return false };
|
||||
id.len() == 32
|
||||
&& id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
&& matches!(ext, "png" | "jpg" | "gif" | "webp" | "bmp" | "svg" | "tiff" | "ico")
|
||||
}
|
||||
|
||||
fn cleanup(dir: &File, now: SystemTime) -> io::Result<()> {
|
||||
for entry in Dir::read_from(dir)? {
|
||||
let entry = entry?;
|
||||
@@ -170,7 +140,6 @@ mod unix {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn stores_bytes_with_private_modes_and_unpredictable_names() {
|
||||
@@ -242,292 +211,10 @@ mod unix {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
|
||||
use std::time::SystemTime;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
|
||||
FILE_SHARE_WRITE,
|
||||
};
|
||||
|
||||
fn open_directory(path: &Path) -> io::Result<File> {
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "data directory must be absolute"));
|
||||
}
|
||||
let dir = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
let meta = dir.metadata()?;
|
||||
if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"terminal media directory must not be a reparse point",
|
||||
));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
fn cleanup(path: &Path, now: SystemTime) -> io::Result<()> {
|
||||
for entry in fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
if !entry.file_name().to_str().is_some_and(owned_name) {
|
||||
continue;
|
||||
}
|
||||
let file = match OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(entry.path())
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let meta = file.metadata()?;
|
||||
if meta.is_file()
|
||||
&& meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| now.duration_since(time).ok())
|
||||
.is_some_and(|age| age >= LIFETIME)
|
||||
{
|
||||
match fs::remove_file(entry.path()) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_with(
|
||||
data_dir: &Path,
|
||||
data: &[u8],
|
||||
mime: &str,
|
||||
now: SystemTime,
|
||||
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
|
||||
) -> IdeResult<String> {
|
||||
let ext = extension(mime)?;
|
||||
let _parent = open_directory(data_dir)?;
|
||||
let path = data_dir.join(DIRECTORY);
|
||||
match fs::create_dir(&path) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => (),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
let _dir = open_directory(&path)?;
|
||||
cleanup(&path, now)?;
|
||||
let name = format!("image-{}.{}", uuid::Uuid::new_v4().simple(), ext);
|
||||
let target = path.join(&name);
|
||||
let temporary = path.join(format!(".partial-{name}"));
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
|
||||
let result = write(&mut file, data);
|
||||
drop(file);
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
return Err(error.into());
|
||||
}
|
||||
if let Err(error) = fs::hard_link(&temporary, &target) {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
return Err(error.into());
|
||||
}
|
||||
let _ = fs::remove_file(&temporary);
|
||||
Ok(target.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
pub(in crate::ops::term) fn store(data_dir: &Path, data: &[u8], mime: &str) -> IdeResult<String> {
|
||||
store_with(data_dir, data, mime, SystemTime::now(), |file, bytes| file.write_all(bytes))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
fn junction(path: &Path, target: &Path) {
|
||||
let output = std::process::Command::new("powershell.exe")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"New-Item -ItemType Junction -Path $env:OPENIDEA_TEST_JUNCTION -Target $env:OPENIDEA_TEST_TARGET -ErrorAction Stop | Out-Null",
|
||||
])
|
||||
.env("OPENIDEA_TEST_JUNCTION", path)
|
||||
.env("OPENIDEA_TEST_TARGET", target)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_reparse_data_and_storage_directories() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let link = root.path().join("data");
|
||||
junction(&link, outside.path());
|
||||
assert!(store(&link, b"x", "image/png").is_err());
|
||||
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
|
||||
fs::remove_dir(&link).unwrap();
|
||||
let link = root.path().join(DIRECTORY);
|
||||
junction(&link, outside.path());
|
||||
assert!(store(root.path(), b"x", "image/png").is_err());
|
||||
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
|
||||
fs::remove_dir(&link).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expiry_only_removes_owned_regular_media_at_boundary() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join(DIRECTORY);
|
||||
fs::create_dir(&path).unwrap();
|
||||
let _dir = open_directory(&path).unwrap();
|
||||
let now = SystemTime::now();
|
||||
let names = [
|
||||
"image-00000000000000000000000000000001.png",
|
||||
"image-00000000000000000000000000000002.mp3",
|
||||
".partial-image-00000000000000000000000000000003.mp4",
|
||||
"image-00000000000000000000000000000004.webm",
|
||||
"image-00000000000000000000000000000005.wav",
|
||||
"unrelated.png",
|
||||
"image-00000000000000000000000000000006.exe",
|
||||
];
|
||||
for (name, time) in names.iter().zip([
|
||||
now - LIFETIME,
|
||||
now - LIFETIME,
|
||||
now - LIFETIME,
|
||||
now - LIFETIME + Duration::from_secs(1),
|
||||
now + Duration::from_secs(1),
|
||||
now - LIFETIME,
|
||||
now - LIFETIME,
|
||||
]) {
|
||||
let file = File::create(path.join(name)).unwrap();
|
||||
file.set_times(fs::FileTimes::new().set_modified(time)).unwrap();
|
||||
}
|
||||
let link = path.join("image-00000000000000000000000000000007.png");
|
||||
junction(&link, outside.path());
|
||||
let directory = path.join("image-00000000000000000000000000000008.png");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
cleanup(&path, now).unwrap();
|
||||
for name in &names[..3] {
|
||||
assert!(!path.join(name).exists());
|
||||
}
|
||||
for name in &names[3..] {
|
||||
assert!(path.join(name).exists());
|
||||
}
|
||||
assert!(directory.is_dir());
|
||||
assert!(fs::symlink_metadata(&link).unwrap().file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0);
|
||||
fs::remove_dir(link).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_write_removes_partial_file() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let result = store_with(root.path(), b"partial", "audio/ogg", SystemTime::now(), |file, bytes| {
|
||||
file.write_all(bytes)?;
|
||||
Err(io::Error::other("simulated failure"))
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publication_preserves_existing_target() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join(DIRECTORY);
|
||||
let result = store_with(root.path(), b"new", "video/mp4", SystemTime::now(), |file, bytes| {
|
||||
file.write_all(bytes)?;
|
||||
let temporary = fs::read_dir(&path)?.next().unwrap()?.file_name();
|
||||
let target = temporary.to_str().unwrap().strip_prefix(".partial-").unwrap();
|
||||
fs::write(path.join(target), b"existing")
|
||||
});
|
||||
assert!(result.is_err());
|
||||
let files: Vec<_> = fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().path()).collect();
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(fs::read(&files[0]).unwrap(), b"existing");
|
||||
assert!(!files[0].file_name().unwrap().to_str().unwrap().starts_with(".partial-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_handles_prevent_directory_replacement() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join(DIRECTORY);
|
||||
let result = store_with(root.path(), b"x", "image/png", SystemTime::now(), |file, bytes| {
|
||||
assert!(fs::rename(&path, root.path().join("replaced")).is_err());
|
||||
file.write_all(bytes)
|
||||
});
|
||||
assert_eq!(fs::read(result.unwrap()).unwrap(), b"x");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) use unix::store;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) use windows::store;
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
#[cfg(not(unix))]
|
||||
pub(super) fn store(_data_dir: &Path, _data: &[u8], _mime: &str) -> IdeResult<String> {
|
||||
Err(IdeError::internal("private terminal image storage is unsupported on this platform"))
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(unix, windows)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stores_supported_media_with_expected_extensions_and_unique_names() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let types = [
|
||||
("image/png", "png"),
|
||||
("image/jpeg", "jpg"),
|
||||
("image/gif", "gif"),
|
||||
("image/webp", "webp"),
|
||||
("image/bmp", "bmp"),
|
||||
("image/svg+xml", "svg"),
|
||||
("image/tiff", "tiff"),
|
||||
("image/x-icon", "ico"),
|
||||
("audio/wav", "wav"),
|
||||
("audio/x-wav", "wav"),
|
||||
("audio/mpeg", "mp3"),
|
||||
("audio/mp4", "m4a"),
|
||||
("audio/ogg", "ogg"),
|
||||
("audio/webm", "webm"),
|
||||
("audio/flac", "flac"),
|
||||
("audio/aac", "aac"),
|
||||
("video/mp4", "mp4"),
|
||||
("video/webm", "webm"),
|
||||
("video/ogg", "ogv"),
|
||||
("video/quicktime", "mov"),
|
||||
];
|
||||
let mut paths = std::collections::HashSet::new();
|
||||
for (mime, ext) in types {
|
||||
let path = store(root.path(), mime.as_bytes(), mime).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), mime.as_bytes());
|
||||
assert_eq!(Path::new(&path).extension().unwrap(), ext);
|
||||
assert!(owned_name(Path::new(&path).file_name().unwrap().to_str().unwrap()));
|
||||
assert!(paths.insert(path));
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(root.path().join(DIRECTORY)).unwrap().count(), types.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsupported_mime_before_creating_storage() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
for mime in ["text/plain", "application/octet-stream", "image/unknown", "audio/unknown", "video/unknown", ""] {
|
||||
let error = store(root.path(), b"x", mime).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(error.message, "unsupported clipboard media type");
|
||||
}
|
||||
assert!(!root.path().join(DIRECTORY).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_relative_data_directory() {
|
||||
assert!(store(Path::new("relative-data"), b"x", "image/png").is_err());
|
||||
}
|
||||
}
|
||||
@@ -123,18 +123,18 @@ fn per_repo(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A shelf is one patch for one owning repository. Validate the whole selection before reverting files.
|
||||
fn shelf_repository(project: &Project, paths: &[PathBuf]) -> IdeResult<PathBuf> {
|
||||
/// Shelf and patches work in the primary repository only: changes of a nested one
|
||||
/// fail instead of being left out silently.
|
||||
fn in_primary_repo(project: &Project, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let repos = project.repos();
|
||||
let root = paths
|
||||
.first()
|
||||
.and_then(|p| repos.for_path(p))
|
||||
.map(|r| r.root())
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("select files in a git repository to shelve"))?;
|
||||
if paths.iter().any(|p| repos.for_path(p).map(|r| r.root()) != Some(root)) {
|
||||
return Err(ide_core::IdeError::invalid("select files from a single git repository to shelve"));
|
||||
let primary = repos.primary().map(|r| r.root());
|
||||
match paths.iter().find(|p| repos.for_path(p).map(|r| r.root()) != primary) {
|
||||
Some(p) => Err(ide_core::IdeError::invalid(format!(
|
||||
"{} is in another git repository; shelving and patches support the project's main repository only",
|
||||
p.display()
|
||||
))),
|
||||
None => Ok(()),
|
||||
}
|
||||
Ok(root.to_path_buf())
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
@@ -281,7 +281,7 @@ pub async fn vcs_add_to_ignore(
|
||||
}
|
||||
}
|
||||
apply_git_executable(&project.settings.effective());
|
||||
let result = project.with_disk_sync(|| ide_vcs::add_to_ignore(&paths, destination));
|
||||
let result = ide_vcs::add_to_ignore(&paths, destination);
|
||||
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
|
||||
project.watcher.reload_ignore_rules();
|
||||
for (_, watcher) in project.content_watchers.lock().iter() {
|
||||
@@ -322,7 +322,7 @@ pub async fn vcs_commit(
|
||||
// Commit hooks may run for a long time.
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), None, |r| {
|
||||
project.with_repo_at(repo.as_deref(), |r| {
|
||||
r.commit_with(&message, &options, &|path| project.vcs_encoding(path, None))
|
||||
})
|
||||
})
|
||||
@@ -729,13 +729,7 @@ pub async fn vcs_add_worktree(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let result = project
|
||||
.with_repo_recorded(repo.as_deref(), None, |r| r.add_worktree(&path, &commitish, new_branch.as_deref()));
|
||||
// A worktree below the project is a new repository: rescan so its files
|
||||
// join the status and gutter queries (the watcher picks the gitfile up
|
||||
// too, but only as a debounced event later).
|
||||
project.refresh_repositories();
|
||||
result
|
||||
project.with_repo_at(repo.as_deref(), |r| r.add_worktree(&path, &commitish, new_branch.as_deref()))
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -749,12 +743,7 @@ pub async fn vcs_remove_worktree(
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force));
|
||||
project.refresh_repositories();
|
||||
result
|
||||
})
|
||||
.await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_compare_scope(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<CompareScope> {
|
||||
@@ -857,7 +846,7 @@ pub async fn vcs_apply_patch(
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), None, |r| r.apply_patch(&patch))).await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.apply_patch(&patch))).await
|
||||
}
|
||||
|
||||
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
|
||||
@@ -865,23 +854,16 @@ pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec<Path
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let repo = shelf_repository(&project, &paths)?;
|
||||
in_primary_repo(&project, &paths)?;
|
||||
keep_private(&project.root);
|
||||
project.with_repo_recorded(Some(&repo), Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
|
||||
project.with_repo_recorded(None, Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn vcs_shelves(host: &Host, window: &str) -> IdeResult<Vec<ShelvedChangeList>> {
|
||||
let project = host.project(window)?;
|
||||
let mut shelves = ide_vcs::shelf::list(&shelf_dir(&project.root))?;
|
||||
let primary = project.repos().primary().map(|r| ide_core::IpcPath::from(r.root().to_path_buf()));
|
||||
for entry in &mut shelves {
|
||||
if entry.repo.is_none() {
|
||||
entry.repo = primary.clone();
|
||||
}
|
||||
}
|
||||
Ok(shelves)
|
||||
ide_vcs::shelf::list(&shelf_dir(&project.root))
|
||||
}
|
||||
|
||||
/// Unshelve: applies the shelved patch (3-way merging; conflicts are left for the
|
||||
@@ -896,8 +878,7 @@ pub async fn vcs_unshelve(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?;
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Unshelve"), |r| {
|
||||
project.with_repo_recorded(None, Some("Unshelve"), |r| {
|
||||
ide_vcs::shelf::unshelve_path(r, &shelf_dir(&project.root), &id, remove, path.as_deref())
|
||||
})
|
||||
})
|
||||
@@ -921,30 +902,12 @@ pub fn vcs_shelf_patch(host: &Host, window: &str, id: String, path: Option<Strin
|
||||
|
||||
pub async fn vcs_shelf_diff(host: &Host, window: &str, id: String) -> IdeResult<Vec<ide_vcs::shelf::ShelfDiffFile>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let repo = ide_vcs::shelf::repository(&shelf_dir(&project.root), &id)?;
|
||||
project.with_repo_at(repo.as_deref(), |r| ide_vcs::shelf::diff_files(r, &shelf_dir(&project.root), &id))
|
||||
})
|
||||
.await
|
||||
blocking(move || project.with_repo(|r| ide_vcs::shelf::diff_files(r, &shelf_dir(&project.root), &id))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_shelf_import(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
patch: String,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_shelf_import(host: &Host, window: &str, name: String, patch: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
if repo.is_none() && project.repos().is_empty() {
|
||||
return ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch, None);
|
||||
}
|
||||
project.with_repo_at(repo.as_deref(), |r| {
|
||||
ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch, Some(r.root()))
|
||||
})
|
||||
})
|
||||
.await
|
||||
blocking(move || ide_vcs::shelf::import_patch(&shelf_dir(&project.root), &name, &patch)).await
|
||||
}
|
||||
|
||||
pub fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
|
||||
@@ -959,20 +922,13 @@ pub fn vcs_changelists_save(host: &Host, window: &str, changelists: ChangelistSt
|
||||
}
|
||||
|
||||
/// Create Patch › Save to file.
|
||||
pub async fn vcs_write_patch(host: &Host, window: &str, path: PathBuf, patch: String) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
pub async fn vcs_write_patch(_host: &Host, _window: &str, path: PathBuf, patch: String) -> IdeResult<()> {
|
||||
blocking(move || {
|
||||
let write = || {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(&path, patch)?;
|
||||
Ok(())
|
||||
};
|
||||
match project {
|
||||
Some(project) => project.with_disk_sync(write),
|
||||
None => write(),
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(&path, patch)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1151,7 +1107,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_shelf_rename", |c| async move { vcs_shelf_rename(&c.host, &c.window, c.arg("id")?, c.arg("name")?) });
|
||||
d.add("vcs_shelf_diff", |c| async move { vcs_shelf_diff(&c.host, &c.window, c.arg("id")?).await });
|
||||
d.add("vcs_shelf_import", |c| async move {
|
||||
vcs_shelf_import(&c.host, &c.window, c.arg("repo")?, c.arg("name")?, c.arg("patch")?).await
|
||||
vcs_shelf_import(&c.host, &c.window, c.arg("name")?, c.arg("patch")?).await
|
||||
});
|
||||
d.add("vcs_shelf_patch", |c| async move { vcs_shelf_patch(&c.host, &c.window, c.arg("id")?, c.arg("path")?) });
|
||||
d.add("vcs_changelists_load", |c| async move { vcs_changelists_load(&c.host, &c.window) });
|
||||
|
||||
@@ -325,35 +325,15 @@ impl Host {
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
// A repository was cloned / initialised / removed below the project:
|
||||
// its `.git/HEAD` appeared or went. A linked worktree's `.git` is a
|
||||
// plain gitfile, and that file is the only marker written inside the
|
||||
// worktree itself, so the `.git` path counts too.
|
||||
// A repository was cloned / initialised / removed below the project: its
|
||||
// `.git/HEAD` (the watcher reports nothing else of `.git`) appeared or went.
|
||||
let known = repos.read().roots();
|
||||
let mut git_dirs = changed.iter().chain(&batch.removed).chain(&batch.vcs).any(|p| {
|
||||
let dir = if p.ends_with(".git/HEAD") {
|
||||
p.parent().and_then(Path::parent)
|
||||
} else if p.ends_with(".git") {
|
||||
p.parent()
|
||||
} else {
|
||||
None
|
||||
let git_dirs = changed.iter().chain(&batch.removed).chain(&batch.vcs).any(|p| {
|
||||
let Some(dir) = p.ends_with(".git/HEAD").then(|| p.parent().and_then(Path::parent)).flatten()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(dir) = dir else { return false };
|
||||
known.iter().any(|r| r == dir) != p.exists()
|
||||
});
|
||||
// A linked worktree was registered or unregistered in the main
|
||||
// gitdir: `git worktree add` / `remove` creates or deletes
|
||||
// `.git/worktrees/<name>`. Its own gitfile is written before the
|
||||
// watcher can watch the new directory, so this entry is what
|
||||
// Linux per-directory watchers see.
|
||||
git_dirs |= batch.vcs.iter().any(|p| {
|
||||
let rest: Vec<_> = p
|
||||
.components()
|
||||
.skip_while(|c| c.as_os_str() != ".git")
|
||||
.skip(1) // the `.git` component itself
|
||||
.map(|c| c.as_os_str().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
|
||||
known.iter().any(|r| r == dir) != p.is_file()
|
||||
});
|
||||
if git_dirs {
|
||||
scan_repositories(&root, &repos, &settings, &sink);
|
||||
@@ -702,24 +682,17 @@ impl Project {
|
||||
self.with_repo_at(None, f)
|
||||
}
|
||||
|
||||
pub(crate) fn with_disk_sync<T>(&self, f: impl FnOnce() -> IdeResult<T>) -> IdeResult<T> {
|
||||
let result = f();
|
||||
// Failed operations can also leave changed files (for example merge conflicts).
|
||||
self.documents.sync_after_disk_change();
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs a VCS operation that rewrites the working tree (checkout, merge,
|
||||
/// rebase, pull, reset, stash, rollback): Local History gets a label and a
|
||||
/// snapshot of every locally changed file before, and a label after.
|
||||
/// Clean buffers follow the resulting files before returning; `None` omits the history labels.
|
||||
/// `None` runs `f` like [`with_repo`](Self::with_repo) (operations that keep the working tree).
|
||||
pub fn with_repo_recorded<T>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
|
||||
let Some(name) = operation else { return self.with_repo_at(at, f) };
|
||||
self.history_label(&format!("Before {name}"));
|
||||
if let Ok(changed) = self.with_repo_at(at, |r| r.status()) {
|
||||
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
|
||||
@@ -728,7 +701,7 @@ impl Project {
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = self.with_disk_sync(|| self.with_repo_at(at, f));
|
||||
let result = self.with_repo_at(at, f);
|
||||
self.history_label(&format!("After {name}"));
|
||||
result
|
||||
}
|
||||
@@ -908,7 +881,37 @@ impl Project {
|
||||
|
||||
/// Applies a multi-file edit through the document layer so open editors update live.
|
||||
pub fn apply_workspace_edit(documents: &Documents, edit: &ide_core::WorkspaceEdit) -> IdeResult<()> {
|
||||
documents.apply_workspace_edit(edit)
|
||||
use ide_core::FileEdit;
|
||||
let mut edit = edit.clone();
|
||||
edit.deduplicate();
|
||||
for file in &edit.files {
|
||||
match file {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
// Files not open in an editor are opened transiently and closed again.
|
||||
let (doc, transient) = match documents.by_path(path) {
|
||||
Some(doc) => (doc, false),
|
||||
None => (documents.open(path)?.id, true),
|
||||
};
|
||||
let result = documents.apply_edits(doc, edits).and_then(|_| documents.save(doc));
|
||||
if transient {
|
||||
documents.close(doc);
|
||||
}
|
||||
result?;
|
||||
}
|
||||
FileEdit::Create { path, overwrite } => {
|
||||
if path.exists() {
|
||||
if *overwrite {
|
||||
ide_vfs::save_text(path, "", "utf-8", false)?;
|
||||
}
|
||||
} else {
|
||||
ide_vfs::create_file(path)?;
|
||||
}
|
||||
}
|
||||
FileEdit::Rename { from, to } => ide_vfs::rename(from, to)?,
|
||||
FileEdit::Delete { path, .. } => ide_vfs::delete(path)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Files the watcher reports per batch that Local History snapshots.
|
||||
@@ -1250,14 +1253,10 @@ mod workspace_edit_tests {
|
||||
let doc = documents.open(&alias).unwrap();
|
||||
let changes = |path: PathBuf| FileEdit::Edit {
|
||||
path: path.into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() }],
|
||||
};
|
||||
apply_workspace_edit(
|
||||
&documents,
|
||||
&WorkspaceEdit { files: vec![changes(real.clone()), changes(alias)], ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
apply_workspace_edit(&documents, &WorkspaceEdit { files: vec![changes(real.clone()), changes(alias)] })
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(real).unwrap(), "sum_values();\n");
|
||||
assert_eq!(documents.snapshot(doc.id).unwrap().text, "sum_values();\n");
|
||||
}
|
||||
|
||||
@@ -178,7 +178,7 @@ impl Dispatcher {
|
||||
Ok(())
|
||||
})
|
||||
.add("cancel_task", |c| async move { Ok(ide_core::task::cancel(c.arg::<TaskId>("id")?)) })
|
||||
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_entry_kind", |c| async move { ops::fs::entry_kind(&c.host, c.arg("path")?).await })
|
||||
.add("fs_create_file", |c| async move { ops::fs::create_file(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_create_file_bytes", |c| async move {
|
||||
@@ -215,14 +215,9 @@ impl Dispatcher {
|
||||
})
|
||||
.add("fs_read_text", |c| async move { ops::fs::read_text(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_open", |c| async move { ops::doc::open(&c.host, &c.window, c.arg("path")?).await })
|
||||
.add("doc_close", |c| async move {
|
||||
ops::doc::blocking(move || ops::doc::close(&c.host, &c.window, c.arg("doc")?)).await
|
||||
})
|
||||
.add("doc_close", |c| async move { ops::doc::close(&c.host, &c.window, c.arg("doc")?) })
|
||||
.add("doc_edit", |c| async move {
|
||||
ops::doc::blocking(move || {
|
||||
ops::doc::edit(&c.host, &c.window, c.arg("doc")?, c.arg("baseVersion")?, c.arg("changes")?)
|
||||
})
|
||||
.await
|
||||
ops::doc::edit(&c.host, &c.window, c.arg("doc")?, c.arg("baseVersion")?, c.arg("changes")?)
|
||||
})
|
||||
.add("doc_save", |c| async move { ops::doc::save(&c.host, &c.window, c.arg("doc")?).await })
|
||||
.add("doc_save_all", |c| async move { ops::doc::save_all(&c.host, &c.window).await })
|
||||
|
||||
@@ -209,10 +209,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "menu_model"
|
||||
| "menu_configure"
|
||||
| "menu_set_disabled"
|
||||
| "prepare_workspace_edit"
|
||||
| "apply_workspace_edit"
|
||||
| "undo_workspace_edit"
|
||||
| "redo_workspace_edit"
|
||||
| "lsp_servers"
|
||||
| "lsp_resend_diagnostics"
|
||||
| "recent_projects"
|
||||
|
||||
@@ -88,40 +88,6 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
assert!(peer.request::<_, Value>("invoke", call, None).await.is_err());
|
||||
// Manual workspace edits remain available in Restricted Mode, like doc/fs
|
||||
// editing. They do not ask a language server to execute project commands.
|
||||
let manual = project.join("src/manual.txt");
|
||||
std::fs::write(&manual, "old").unwrap();
|
||||
let edit = json!({ "files": [{ "kind": "edit", "path": manual, "edits": [{
|
||||
"range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } },
|
||||
"new_text": "new"
|
||||
}] }] });
|
||||
let edit = invoke(&peer, "prepare_workspace_edit", json!({ "edit": edit })).await.unwrap();
|
||||
assert_eq!(edit["preconditions"].as_array().unwrap().len(), 1);
|
||||
invoke(&peer, "apply_workspace_edit", json!({ "edit": edit })).await.unwrap();
|
||||
until("workspace edit history", || {
|
||||
client.events.lock().iter().any(|event| matches!(event.event, ide_core::IdeEvent::WorkspaceEditApplied { .. }))
|
||||
})
|
||||
.await;
|
||||
let undo_id = client
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match &event.event {
|
||||
ide_core::IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "new");
|
||||
invoke(&peer, "undo_workspace_edit", json!({ "id": undo_id })).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "old");
|
||||
invoke(&peer, "redo_workspace_edit", json!({ "id": undo_id })).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&manual).unwrap(), "new");
|
||||
assert_eq!(invoke(&peer, "project_current", json!({})).await.unwrap()["trusted"], false);
|
||||
for command in ["lsp_execute_command", "lsp_apply_code_action"] {
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
invoke(&peer, "project_trust_set", json!({"path": project, "trusted": true, "folder": false})).await.unwrap();
|
||||
let current = invoke(&peer, "project_current", json!({})).await.unwrap();
|
||||
assert_eq!(current["name"], "demo");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#![cfg(any(unix, windows))]
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::{NullSink, TerminalId};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
@@ -28,8 +28,8 @@ async fn storage_requires_a_registered_terminal() {
|
||||
.spawn(
|
||||
TerminalOptions {
|
||||
cwd: root.path().into(),
|
||||
shell: Some(if cfg!(windows) { "powershell.exe" } else { "/bin/sh" }.into()),
|
||||
args: if cfg!(windows) { vec!["-NoLogo".into(), "-NoProfile".into()] } else { vec![] },
|
||||
shell: Some("/bin/sh".into()),
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
@@ -40,12 +40,9 @@ async fn storage_requires_a_registered_terminal() {
|
||||
Box::new(|_| {}),
|
||||
)
|
||||
.unwrap();
|
||||
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
|
||||
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
|
||||
}
|
||||
assert!(ops::term::store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
|
||||
let path = ops::term::store_image(&host, terminal.id, vec![1, 2, 3], "image/png".into()).await.unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
|
||||
host.terminals.kill(terminal.id).unwrap();
|
||||
assert!(ops::term::store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
|
||||
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
|
||||
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 1);
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
use ide_core::{ChangeSet, NullSink, TextChange};
|
||||
use ide_host::{Host, HostConfig, Project, ops::vcs};
|
||||
use std::{path::Path, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
const ORIGINAL: &str = "SELECT *\nFROM patients\n\tLIMIT 10 OFFSET 0";
|
||||
const OTHER: &str = "SELECT id\nFROM patients\n\tLIMIT 20 OFFSET 0";
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8(out.stdout).unwrap()
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
host: Host,
|
||||
project: Arc<Project>,
|
||||
path: std::path::PathBuf,
|
||||
doc: ide_core::DocId,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
// The command must synchronize documents even when watcher delivery is excluded.
|
||||
let path = root.join("node_modules/query.sql");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["config", "user.name", "Test"]);
|
||||
git(&root, &["config", "user.email", "[email protected]"]);
|
||||
git(&root, &["config", "commit.gpgsign", "false"]);
|
||||
git(&root, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(&path, ORIGINAL).unwrap();
|
||||
git(&root, &["add", "-f", "node_modules/query.sql"]);
|
||||
git(&root, &["commit", "-m", "original"]);
|
||||
git(&root, &["switch", "-c", "other"]);
|
||||
std::fs::write(&path, OTHER).unwrap();
|
||||
git(&root, &["commit", "-am", "other"]);
|
||||
git(&root, &["switch", "main"]);
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if !project.repos().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let doc = project.documents.open(&path).unwrap().id;
|
||||
Self { host, project, path, doc, _temp: temp }
|
||||
}
|
||||
|
||||
fn saved_edit(&self, text: &str) {
|
||||
self.project.documents.replace_all(self.doc, text).unwrap();
|
||||
self.project.documents.save(self.doc).unwrap();
|
||||
}
|
||||
|
||||
fn assert_clean(&self, text: &str) {
|
||||
let snapshot = self.project.documents.snapshot(self.doc).unwrap();
|
||||
assert_eq!(snapshot.text, text);
|
||||
assert!(!snapshot.dirty);
|
||||
self.project.documents.save_all().unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&self.path).unwrap(), text);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn checkout_reloads_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap();
|
||||
f.assert_clean(OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn rollback_reloads_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
f.saved_edit(&format!("{ORIGINAL}\n"));
|
||||
vcs::vcs_discard(&f.host, "main", vec![f.path.clone()]).await.unwrap();
|
||||
f.assert_clean(ORIGINAL);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn stash_and_unstash_reload_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
let edited = format!("{ORIGINAL}\n");
|
||||
f.saved_edit(&edited);
|
||||
vcs::vcs_stash_push(&f.host, "main", None, None, false, false).await.unwrap();
|
||||
f.assert_clean(ORIGINAL);
|
||||
vcs::vcs_stash_apply(&f.host, "main", None, 0, true, false, None).await.unwrap();
|
||||
f.assert_clean(&edited);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn applying_patch_reloads_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
std::fs::write(&f.path, OTHER).unwrap();
|
||||
let patch = git(&f.project.root, &["diff"]);
|
||||
git(&f.project.root, &["restore", "."]);
|
||||
vcs::vcs_apply_patch(&f.host, "main", None, patch).await.unwrap();
|
||||
f.assert_clean(OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn writing_patch_file_reloads_its_clean_open_document() {
|
||||
let f = Fixture::new().await;
|
||||
vcs::vcs_write_patch(&f.host, "main", f.path.clone(), OTHER.into()).await.unwrap();
|
||||
f.assert_clean(OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn directory_compare_overwrite_reloads_clean_open_documents() {
|
||||
let f = Fixture::new().await;
|
||||
let base = f.project.root.parent().unwrap();
|
||||
let source = base.join("source");
|
||||
let destination = base.join("destination");
|
||||
std::fs::create_dir_all(&source).unwrap();
|
||||
std::fs::create_dir_all(&destination).unwrap();
|
||||
std::fs::write(source.join("query.sql"), OTHER).unwrap();
|
||||
let path = destination.join("query.sql");
|
||||
std::fs::write(&path, ORIGINAL).unwrap();
|
||||
let doc = f.project.documents.open(&path).unwrap();
|
||||
ide_host::ops::fs::copy_merge(&f.host, "main", source, destination, "query.sql".into(), true).await.unwrap();
|
||||
let snapshot = f.project.documents.snapshot(doc.id).unwrap();
|
||||
assert_eq!(snapshot.text, OTHER);
|
||||
assert!(!snapshot.dirty);
|
||||
f.project.documents.save_all().unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn failed_working_tree_operation_synchronizes_partial_disk_changes() {
|
||||
let f = Fixture::new().await;
|
||||
let result: ide_core::IdeResult<()> = f.project.with_repo_recorded(None, Some("Git merge"), |_| {
|
||||
std::fs::write(&f.path, OTHER).unwrap();
|
||||
Err(ide_core::IdeError::invalid("merge stopped with conflicts"))
|
||||
});
|
||||
assert!(result.is_err());
|
||||
f.assert_clean(OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn working_tree_operation_reloads_same_size_same_timestamp_changes() {
|
||||
let f = Fixture::new().await;
|
||||
let modified = std::fs::metadata(&f.path).unwrap().modified().unwrap();
|
||||
let replacement = ORIGINAL.replace("LIMIT 10", "LIMIT 20");
|
||||
f.project
|
||||
.with_repo_recorded(None, Some("Git checkout"), |_| {
|
||||
std::fs::write(&f.path, &replacement).unwrap();
|
||||
std::fs::File::options()
|
||||
.write(true)
|
||||
.open(&f.path)
|
||||
.unwrap()
|
||||
.set_times(std::fs::FileTimes::new().set_modified(modified))
|
||||
.unwrap();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
f.assert_clean(&replacement);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn working_tree_operation_does_not_discard_unsaved_edits() {
|
||||
let f = Fixture::new().await;
|
||||
let version = f.project.documents.snapshot(f.doc).unwrap().version;
|
||||
f.project
|
||||
.documents
|
||||
.edit(f.doc, version, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "-- local\n".into() }] })
|
||||
.unwrap();
|
||||
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None).await.unwrap();
|
||||
let snapshot = f.project.documents.snapshot(f.doc).unwrap();
|
||||
assert_eq!(snapshot.text, format!("-- local\n{ORIGINAL}"));
|
||||
assert!(snapshot.dirty);
|
||||
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), OTHER);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn adding_local_exclude_reloads_open_ignore_document() {
|
||||
let f = Fixture::new().await;
|
||||
let path = f.project.root.join(".git/info/exclude");
|
||||
let doc = f.project.documents.open(&path).unwrap();
|
||||
let ignored = f.project.root.join("generated.txt");
|
||||
std::fs::write(&ignored, "generated\n").unwrap();
|
||||
vcs::vcs_add_to_ignore(&f.host, "main", vec![ignored], ide_vcs::IgnoreDestination::LocalExclude).await.unwrap();
|
||||
let disk = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(disk.contains("/generated.txt"));
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().text, disk);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn commit_hook_reloads_clean_open_documents() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let f = Fixture::new().await;
|
||||
f.saved_edit(&format!("{ORIGINAL}\n"));
|
||||
git(&f.project.root, &["add", "-u"]);
|
||||
let hook = f.project.root.join(".git/hooks/pre-commit");
|
||||
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > node_modules/query.sql\n").unwrap();
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
vcs::vcs_commit(
|
||||
&f.host,
|
||||
"main",
|
||||
None,
|
||||
"commit with hook".into(),
|
||||
ide_vcs::CommitOptions { run_hooks: true, ..Default::default() },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
f.assert_clean("SELECT hook;");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn worktree_checkout_hook_reloads_clean_open_documents() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let f = Fixture::new().await;
|
||||
let hook = f.project.root.join(".git/hooks/post-checkout");
|
||||
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > ../project/node_modules/query.sql\n").unwrap();
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let linked = f.project.root.parent().unwrap().join("linked");
|
||||
vcs::vcs_add_worktree(&f.host, "main", None, linked, "other".into(), None).await.unwrap();
|
||||
f.assert_clean("SELECT hook;");
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
//! Shelves retain their repository even when the project root is above or below it.
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops::vcs};
|
||||
use std::{path::Path, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
fn git(root: &Path, args: &[&str]) {
|
||||
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
async fn check_shelves(layout: &str) {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let roots = match layout {
|
||||
"same" => vec![project_root.clone()],
|
||||
"below" => vec![base.clone()],
|
||||
"two" => vec![project_root.join("项目A"), project_root.join("repoB")],
|
||||
_ => vec![project_root.join("项目A")],
|
||||
};
|
||||
std::fs::create_dir_all(project_root.join("dirB")).unwrap();
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("src/same.txt"), format!("base {i}\n")).unwrap();
|
||||
git(root, &["add", "src"]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
std::fs::write(root.join("src/same.txt"), format!("shelved {i}\n")).unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == roots.len() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), roots.len());
|
||||
let primary = project.repos().primary().unwrap().root().to_path_buf();
|
||||
if roots.len() == 2 {
|
||||
assert!(
|
||||
vcs::vcs_shelve(&host, "main", "mixed".into(), roots.iter().map(|r| r.join("src/same.txt")).collect())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(vcs::vcs_shelves(&host, "main").unwrap().is_empty());
|
||||
}
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
let entry = vcs::vcs_shelve(&host, "main", "work".into(), vec![root.join("src/same.txt")]).await.unwrap();
|
||||
assert_eq!(entry.repo.as_deref(), Some(root.as_path()));
|
||||
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("base {i}\n"));
|
||||
let listed = vcs::vcs_shelves(&host, "main").unwrap();
|
||||
assert_eq!(listed.iter().find(|s| s.id == entry.id).unwrap().repo, entry.repo);
|
||||
let diffs = vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.unwrap();
|
||||
assert_eq!(diffs[0].before.as_deref(), Some(format!("base {i}\n").as_str()));
|
||||
assert_eq!(diffs[0].after.as_deref(), Some(format!("shelved {i}\n").as_str()));
|
||||
vcs::vcs_shelf_rename(&host, "main", entry.id.clone(), "renamed".into()).unwrap();
|
||||
let patch = vcs::vcs_shelf_patch(&host, "main", entry.id.clone(), None).unwrap();
|
||||
vcs::vcs_shelf_import(&host, "main", Some(root.clone()), "imported".into(), patch).await.unwrap();
|
||||
let imported = vcs::vcs_shelves(&host, "main").unwrap().into_iter().find(|s| s.name == "imported").unwrap();
|
||||
assert_eq!(imported.repo, entry.repo);
|
||||
vcs::vcs_shelf_delete(&host, "main", imported.id, None).unwrap();
|
||||
if root != &primary {
|
||||
let info = ide_core::project_dir::path(&project_root, "shelf").join(&entry.id).join("shelf.json");
|
||||
let original = std::fs::read(&info).unwrap();
|
||||
let mut metadata: serde_json::Value = serde_json::from_slice(&original).unwrap();
|
||||
metadata["repo"] = serde_json::json!(base.join("missing-repository"));
|
||||
std::fs::write(&info, serde_json::to_vec(&metadata).unwrap()).unwrap();
|
||||
assert!(vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.is_err());
|
||||
assert!(vcs::vcs_unshelve(&host, "main", entry.id.clone(), false, None).await.is_err());
|
||||
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("base {i}\n"));
|
||||
std::fs::write(info, original).unwrap();
|
||||
}
|
||||
vcs::vcs_unshelve(&host, "main", entry.id.clone(), false, Some("src/same.txt".into())).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("src/same.txt")).unwrap(), format!("shelved {i}\n"));
|
||||
// Old shelves were always made in the primary repository; missing ownership keeps that meaning.
|
||||
if root == &primary {
|
||||
let info = ide_core::project_dir::path(&project_root, "shelf").join(&entry.id).join("shelf.json");
|
||||
let mut metadata: serde_json::Value = serde_json::from_slice(&std::fs::read(&info).unwrap()).unwrap();
|
||||
metadata.as_object_mut().unwrap().remove("repo");
|
||||
std::fs::write(info, serde_json::to_vec(&metadata).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
vcs::vcs_shelves(&host, "main").unwrap().into_iter().find(|s| s.id == entry.id).unwrap().repo,
|
||||
entry.repo
|
||||
);
|
||||
assert_eq!(
|
||||
vcs::vcs_shelf_diff(&host, "main", entry.id).await.unwrap()[0].after.as_deref(),
|
||||
Some(format!("shelved {i}\n").as_str())
|
||||
);
|
||||
}
|
||||
}
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shelf_at_repo_root() {
|
||||
check_shelves("same").await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shelf_in_non_git_project() {
|
||||
check_shelves("above").await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shelves_in_two_repositories() {
|
||||
check_shelves("two").await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shelf_in_project_below_repository() {
|
||||
check_shelves("below").await;
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, Project, ops::vcs};
|
||||
use std::{path::PathBuf, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
fn git(root: &std::path::Path, args: &[&str]) {
|
||||
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
async fn wait_for_repos(project: &Arc<Project>, count: usize) {
|
||||
for _ in 0..200 {
|
||||
if project.repos().all().len() >= count {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
panic!("expected {} repositories, found {}", count, project.repos().all().len());
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
host: Host,
|
||||
project: Arc<Project>,
|
||||
root: PathBuf,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["config", "user.name", "Test"]);
|
||||
git(&root, &["config", "user.email", "[email protected]"]);
|
||||
git(&root, &["config", "commit.gpgsign", "false"]);
|
||||
git(&root, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(root.join("file.txt"), "original\n").unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "original"]);
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
wait_for_repos(&project, 1).await;
|
||||
Self { host, project, root, _temp: temp }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn command_added_worktree_joins_the_repository_set() {
|
||||
let f = Fixture::new().await;
|
||||
let linked = f.root.join("linked");
|
||||
vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap();
|
||||
let roots = f.project.repos().roots();
|
||||
assert!(roots.contains(&linked), "worktree below the project did not join the repository set: {roots:?}");
|
||||
assert_eq!(roots.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn removed_worktree_leaves_the_repository_set() {
|
||||
let f = Fixture::new().await;
|
||||
let linked = f.root.join("linked");
|
||||
vcs::vcs_add_worktree(&f.host, "main", None, linked.clone(), "main".into(), Some("topic".into())).await.unwrap();
|
||||
assert_eq!(f.project.repos().all().len(), 2);
|
||||
vcs::vcs_remove_worktree(&f.host, "main", None, linked, false).await.unwrap();
|
||||
assert_eq!(f.project.repos().all().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn watcher_picks_up_a_worktree_added_below_the_project() {
|
||||
let f = Fixture::new().await;
|
||||
let linked = f.root.join("watched");
|
||||
git(&f.root, &["worktree", "add", "watched", "-b", "watched"]);
|
||||
wait_for_repos(&f.project, 2).await;
|
||||
let roots = f.project.repos().roots();
|
||||
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
use ide_core::{IdeEvent, SharedSink, WorkspaceEdit, error::ErrorKind};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn preview_apply_and_grouped_undo_use_the_shared_host_commands() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let second = tmp.path().join("second.txt");
|
||||
for path in [&first, &second] {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
}
|
||||
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
};
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("local-data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |_| sink.clone()),
|
||||
owner: |window| window,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.open_light("main", &first).unwrap();
|
||||
let info = ops::doc::open(&host, "main", first.clone()).await.unwrap();
|
||||
let edit: WorkspaceEdit = serde_json::from_value(json!({ "files": [
|
||||
{ "kind": "edit", "path": first, "version": info.version, "edits": [{ "range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } }, "new_text": "new" }] },
|
||||
{ "kind": "edit", "path": second, "edits": [{ "range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } }, "new_text": "new" }] }
|
||||
] })).unwrap();
|
||||
let preview = ops::lsp::prepare_workspace_edit(&host, "main", edit.clone()).await.unwrap();
|
||||
assert_eq!(preview.preconditions.len(), 2);
|
||||
std::fs::write(&second, "own\n").unwrap();
|
||||
let error = ops::lsp::apply_workspace_edit(&host, "main", preview).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
|
||||
let preview = ops::lsp::prepare_workspace_edit(&host, "main", edit).await.unwrap();
|
||||
ops::lsp::apply_workspace_edit(&host, "main", preview).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "new\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "new\n");
|
||||
let id = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "own\n");
|
||||
assert_eq!(ops::doc::snapshot(&host, "main", info.id).await.unwrap().text, "old\n");
|
||||
ops::lsp::redo_workspace_edit(&host, "main", id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "new\n");
|
||||
assert_eq!(std::fs::read_to_string(&second).unwrap(), "new\n");
|
||||
host.clear_workspace_edit_history_on_exit();
|
||||
assert_eq!(ops::lsp::undo_workspace_edit(&host, "main", id).await.unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn contended_version_reads_do_not_block_the_async_worker() {
|
||||
use ide_core::{LanguageId, Pos, Range, RequestId};
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct PausedWrite {
|
||||
entered: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
|
||||
release: Mutex<mpsc::Receiver<()>>,
|
||||
}
|
||||
impl DocumentObserver for PausedWrite {
|
||||
fn changed(
|
||||
&self,
|
||||
_: ide_core::DocId,
|
||||
_: &std::path::Path,
|
||||
_: u32,
|
||||
_: &[ide_text::AppliedChange],
|
||||
_: &dyn Fn() -> String,
|
||||
) {
|
||||
if let Some(entered) = self.entered.lock().take() {
|
||||
let _ = entered.send(());
|
||||
self.release.lock().recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for request_kind in 0..5 {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("main.txt");
|
||||
std::fs::write(&file, "old").unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("local-data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |window| window,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
let project = host.open_light("main", &file).unwrap();
|
||||
let doc = project.documents.open(&file).unwrap().id;
|
||||
assert_eq!(project.documents.snapshot(doc).unwrap().language, LanguageId::plain_text());
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
project.documents.add_observer(Arc::new(PausedWrite {
|
||||
entered: Mutex::new(Some(entered_tx)),
|
||||
release: Mutex::new(release_rx),
|
||||
}));
|
||||
let documents = project.documents.clone();
|
||||
let writer = std::thread::spawn(move || {
|
||||
documents
|
||||
.apply_workspace_edit(
|
||||
&serde_json::from_value(json!({ "files": [{
|
||||
"kind": "edit", "path": file, "edits": [{ "range": {
|
||||
"start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 }
|
||||
}, "new_text": "new" }]
|
||||
}] }))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
entered_rx.await.unwrap();
|
||||
let (heartbeat_tx, heartbeat_rx) = mpsc::channel();
|
||||
// Always release the writer, even on the old blocking implementation.
|
||||
let watchdog = std::thread::spawn(move || {
|
||||
let responsive = heartbeat_rx.recv_timeout(Duration::from_secs(2)).is_ok();
|
||||
release_tx.send(()).unwrap();
|
||||
responsive
|
||||
});
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
let _ = started_tx.send(());
|
||||
let action =
|
||||
|| serde_json::from_value(json!({ "title": "test", "isPreferred": false, "server": 1 })).unwrap();
|
||||
match request_kind {
|
||||
0 => {
|
||||
let _ = ops::lsp::lsp_code_actions(&host, "main", doc, Range::point(Pos::new(0, 0)), vec![]).await;
|
||||
}
|
||||
1 => {
|
||||
let _ = ops::lsp::lsp_code_action_query(
|
||||
&host,
|
||||
"main",
|
||||
RequestId(1),
|
||||
doc,
|
||||
Range::point(Pos::new(0, 0)),
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
2 => {
|
||||
let _ = ops::lsp::lsp_resolve_code_action(&host, "main", doc, action()).await;
|
||||
}
|
||||
3 => {
|
||||
let _ = ops::lsp::lsp_apply_code_action(&host, "main", doc, action()).await;
|
||||
}
|
||||
_ => {
|
||||
let _ =
|
||||
ops::lsp::lsp_rename(&host, "main", RequestId(1), doc, Pos::new(0, 0), "other".into()).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
let _ = heartbeat_tx.send(());
|
||||
task.await.unwrap();
|
||||
writer.join().unwrap();
|
||||
assert!(watchdog.join().unwrap(), "request {request_kind} blocked the only async worker");
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ mod syntax;
|
||||
pub use markers::marked_root;
|
||||
pub use registry::{FileTypes, LanguageRegistry};
|
||||
pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, FileReference, Literal, LiteralKind, MAX_CACHED_TREES,
|
||||
MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats,
|
||||
SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
|
||||
ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
|
||||
SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
@@ -96,9 +96,7 @@ pub struct LanguageServerConfig {
|
||||
pub args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`;
|
||||
/// `file#table` requires the TOML file to contain that dotted table, e.g.
|
||||
/// `pyproject.toml#tool.ruff`.
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`.
|
||||
#[serde(default)]
|
||||
pub root_markers: Vec<String>,
|
||||
/// Serve only files below a root marker, not the whole project: a framework's
|
||||
|
||||
@@ -19,13 +19,9 @@ pub fn marked_root(project_root: Option<&Path>, file: &Path, markers: &[String])
|
||||
best
|
||||
}
|
||||
|
||||
/// `dir` contains `marker`: a relative path, a file name pattern with one
|
||||
/// `*` (`*.csproj`), or a TOML file name (no pattern) and a dotted table it
|
||||
/// must contain (`pyproject.toml#tool.ruff`).
|
||||
/// `dir` contains `marker`: a relative path, or a file name pattern with one
|
||||
/// `*` (`*.csproj`).
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
if let Some((file, table)) = marker.split_once('#') {
|
||||
return has_toml_table(&dir.join(file), table);
|
||||
}
|
||||
let Some((prefix, suffix)) = marker.split_once('*') else {
|
||||
return dir.join(marker).exists();
|
||||
};
|
||||
@@ -34,23 +30,9 @@ fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// `file` parses as TOML and has the dotted `table` (`tool.ruff`).
|
||||
fn has_toml_table(file: &Path, table: &str) -> bool {
|
||||
let Ok(text) = std::fs::read_to_string(file) else { return false };
|
||||
let value = match toml::from_str::<toml::Value>(&text) {
|
||||
Ok(value) => value,
|
||||
Err(e) => {
|
||||
tracing::debug!("root marker {}: {e}", file.display());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
/// directory above it.
|
||||
pub(crate) fn is_marker_path(path: &Path, marker: &str) -> bool {
|
||||
let marker = marker.split_once('#').map_or(marker, |(file, _)| file);
|
||||
match marker.split_once('*') {
|
||||
None => path.ends_with(marker),
|
||||
Some((prefix, suffix)) => {
|
||||
@@ -92,29 +74,6 @@ mod tests {
|
||||
assert_eq!(marked_root(None, &file, &markers), Some(home.to_path_buf()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toml_markers_need_their_table() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("svc/app/main.py");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["ruff.toml".to_string(), "pyproject.toml#tool.ruff".to_string()];
|
||||
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"x\"\n[tool.black]\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), None);
|
||||
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff.lint]\nselect = [\"E\"]\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
// Outermost wins: an inline table counts; a value that is no table, or a
|
||||
// file that does not parse, does not.
|
||||
std::fs::write(root.join("pyproject.toml"), "tool = { ruff = { line-length = 100 } }\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.to_path_buf()));
|
||||
std::fs::write(root.join("pyproject.toml"), "tool = { ruff = 1 }\n").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.ruff]\n[broken").unwrap();
|
||||
assert_eq!(marked_root(Some(root), &file, &markers), Some(root.join("svc")));
|
||||
assert!(is_marker_path(&root.join("svc/pyproject.toml"), "pyproject.toml#tool.ruff"));
|
||||
assert!(!is_marker_path(&root.join("svc/setup.cfg"), "pyproject.toml#tool.ruff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_match_file_names() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -22,7 +22,6 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("dockerfile", include_str!("../../../languages/dockerfile.toml")),
|
||||
("dotenv", include_str!("../../../languages/dotenv.toml")),
|
||||
("elixir", include_str!("../../../languages/elixir.toml")),
|
||||
("erb", include_str!("../../../languages/erb.toml")),
|
||||
("erlang", include_str!("../../../languages/erlang.toml")),
|
||||
("fsharp", include_str!("../../../languages/fsharp.toml")),
|
||||
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
|
||||
@@ -521,7 +520,6 @@ mod tests {
|
||||
"MsGenny",
|
||||
"Vue",
|
||||
"Angular Template",
|
||||
"ERB",
|
||||
];
|
||||
|
||||
fn reg() -> LanguageRegistry {
|
||||
@@ -555,7 +553,7 @@ mod tests {
|
||||
fn alternative_servers_are_fallbacks() {
|
||||
let reg = reg();
|
||||
for (lang, servers) in [
|
||||
("python", vec!["basedpyright", "pyright", "ty", "pyrefly"]),
|
||||
("python", vec!["basedpyright", "pyright", "ty"]),
|
||||
("typescript", vec!["vtsls", "typescript-language-server"]),
|
||||
] {
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
@@ -606,32 +604,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_serves_python_files_only_below_its_config() {
|
||||
let reg = reg();
|
||||
let cfg = reg.get(&LanguageId::new("python")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallbacks: hover, rename and symbols stay with the type checker.
|
||||
assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff"]);
|
||||
let ruff = cfg.language_servers.iter().find(|s| s.name == "ruff").unwrap();
|
||||
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", ["server".to_string()].as_slice()));
|
||||
assert!(ruff.require_root_marker && !ruff.fallback);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["lint", "dot", "pyproject", "plain"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("lint/ruff.toml"), "").unwrap();
|
||||
std::fs::write(root.join("dot/.ruff.toml"), "").unwrap();
|
||||
std::fs::write(root.join("pyproject/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
|
||||
std::fs::write(root.join("plain/pyproject.toml"), "[project]\nname = \"plain\"\n").unwrap();
|
||||
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &ruff.root_markers);
|
||||
for dir in ["lint", "dot", "pyproject"] {
|
||||
assert_eq!(served(&format!("{dir}/pkg/main.py")), Some(root.join(dir)), "{dir}");
|
||||
}
|
||||
assert_eq!(served("plain/main.py"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_of_angular_projects_is_an_angular_template() {
|
||||
let reg = reg();
|
||||
@@ -778,7 +750,6 @@ mod tests {
|
||||
("AppDelegate.m", "objective-c"),
|
||||
("a.rb", "ruby"),
|
||||
("Gemfile", "ruby"),
|
||||
("show.html.erb", "erb"),
|
||||
("index.php", "php"),
|
||||
("init.lua", "lua"),
|
||||
("main.dart", "dart"),
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
//! Source ranges for Spring-style configuration keys. This is a syntax index,
|
||||
//! not a YAML evaluator: aliases, merge keys and runtime profile precedence are
|
||||
//! intentionally left to the YAML server / application.
|
||||
use super::lines::{LineIndex, byte_at};
|
||||
use super::{ParsedTree, Syntax, TreeError};
|
||||
use ide_core::{LanguageId, Pos, Range};
|
||||
use tree_sitter::Node;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConfigurationKey {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
pub fn configuration_keys(
|
||||
&self,
|
||||
language: &LanguageId,
|
||||
text: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Vec<ConfigurationKey>, TreeError> {
|
||||
if language.as_str() == "properties" {
|
||||
return Ok(properties(text));
|
||||
}
|
||||
self.with_parsed(language, text, cancelled, |tree| tree.configuration_keys(cancelled))
|
||||
}
|
||||
}
|
||||
|
||||
/// Spring's property lookups whose first argument names a configuration key.
|
||||
const PROPERTY_LOOKUPS: [&str; 2] = ["getProperty", "getRequiredProperty"];
|
||||
|
||||
impl Syntax {
|
||||
/// Whether `pos` in Java `text` lies where a configuration key can be written:
|
||||
/// inside the arguments of a `@Value` annotation or of a `getProperty` /
|
||||
/// `getRequiredProperty` call. Everywhere else Go to Definition is ordinary
|
||||
/// Java navigation and need not consult the configuration index. A file the
|
||||
/// grammar cannot parse answers false.
|
||||
pub fn java_configuration_site(&self, text: &str, pos: Pos, cancelled: &dyn Fn() -> bool) -> bool {
|
||||
let Some(at) = byte_at(text, pos) else { return false };
|
||||
self.with_parsed(&LanguageId::new("java"), text, cancelled, |tree| {
|
||||
let mut node = tree.tree.root_node().descendant_for_byte_range(at, at);
|
||||
while let Some(n) = node {
|
||||
let Some(parent) = n.parent() else { break };
|
||||
let callee = parent.child_by_field_name("name").map(|name| &text[name.byte_range()]);
|
||||
match (n.kind(), parent.kind(), callee) {
|
||||
("annotation_argument_list", "annotation", Some(name)) => {
|
||||
return name.rsplit('.').next() == Some("Value");
|
||||
}
|
||||
("argument_list", "method_invocation", Some(name)) if PROPERTY_LOOKUPS.contains(&name) => {
|
||||
return true;
|
||||
}
|
||||
// Keys are expressions; nothing above a body or declaration can hold one.
|
||||
(_, "block" | "class_body" | "interface_body" | "program", _) => return false,
|
||||
_ => node = Some(parent),
|
||||
}
|
||||
}
|
||||
false
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParsedTree<'_> {
|
||||
pub fn configuration_keys(&self, cancelled: &dyn Fn() -> bool) -> Vec<ConfigurationKey> {
|
||||
let mut out = Vec::new();
|
||||
if self.grammar == "yaml" {
|
||||
yaml(self.tree.root_node(), "", self.text, &LineIndex::new(self.text), &mut out, cancelled, 0);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn yaml(
|
||||
node: Node<'_>,
|
||||
prefix: &str,
|
||||
text: &str,
|
||||
lines: &LineIndex<'_>,
|
||||
out: &mut Vec<ConfigurationKey>,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
depth: usize,
|
||||
) {
|
||||
if depth > 64 || cancelled() || out.len() >= 20_000 {
|
||||
return;
|
||||
}
|
||||
match node.kind() {
|
||||
"block_mapping_pair" | "flow_pair" => {
|
||||
let Some(key) = node.child_by_field_name("key") else { return };
|
||||
let raw = &text[key.byte_range()];
|
||||
if raw.contains('\n') {
|
||||
return;
|
||||
}
|
||||
let name = if raw.starts_with('\'') && raw.ends_with('\'') {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else if raw.starts_with('"') {
|
||||
// JSON escapes cover ordinary quoted configuration keys. Unsupported
|
||||
// YAML-only escapes are skipped rather than indexed under a wrong key.
|
||||
let Ok(name) = serde_json::from_str::<String>(raw) else { return };
|
||||
name
|
||||
} else {
|
||||
if raw.contains(['\n', '{', '[', '*', '&', '!']) || raw == "<<" {
|
||||
return;
|
||||
}
|
||||
raw.to_owned()
|
||||
};
|
||||
if name.is_empty() {
|
||||
return;
|
||||
}
|
||||
let name = if prefix.is_empty() {
|
||||
name
|
||||
} else if name.starts_with('[') {
|
||||
format!("{prefix}{name}")
|
||||
} else {
|
||||
format!("{prefix}.{name}")
|
||||
};
|
||||
if name.len() > 1024 {
|
||||
return;
|
||||
}
|
||||
out.push(ConfigurationKey { name: name.clone(), range: lines.range(key.start_byte(), key.end_byte()) });
|
||||
if let Some(value) = node.child_by_field_name("value") {
|
||||
yaml(value, &name, text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
"block_sequence" | "flow_sequence" => {
|
||||
let mut cursor = node.walk();
|
||||
for (i, child) in node.named_children(&mut cursor).filter(|n| n.kind() != "comment").enumerate() {
|
||||
yaml(child, &format!("{prefix}[{i}]"), text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
// Do not descend into scalars, anchors or aliases.
|
||||
"stream"
|
||||
| "document"
|
||||
| "block_node"
|
||||
| "flow_node"
|
||||
| "block_mapping"
|
||||
| "flow_mapping"
|
||||
| "block_sequence_item" => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
yaml(child, prefix, text, lines, out, cancelled, depth + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn properties(text: &str) -> Vec<ConfigurationKey> {
|
||||
let lines = LineIndex::new(text);
|
||||
let mut out = Vec::new();
|
||||
let mut logical = String::new();
|
||||
let mut offsets = Vec::new();
|
||||
let mut base = 0;
|
||||
for line in text.split_inclusive('\n') {
|
||||
let physical = line.trim_end_matches(['\r', '\n']);
|
||||
let start = physical.len() - physical.trim_start_matches([' ', '\t', '\u{c}']).len();
|
||||
let slice = &physical[start..];
|
||||
if logical.is_empty() && (slice.is_empty() || slice.starts_with(['#', '!'])) {
|
||||
base += line.len();
|
||||
continue;
|
||||
}
|
||||
let continued = slice.bytes().rev().take_while(|b| *b == b'\\').count() % 2 == 1;
|
||||
let end = physical.len() - usize::from(continued);
|
||||
for (i, ch) in physical[start..end].char_indices() {
|
||||
offsets.extend((0..ch.len_utf8()).map(|byte| base + start + i + byte));
|
||||
logical.push(ch);
|
||||
}
|
||||
if !continued || base + line.len() == text.len() {
|
||||
let mut escaped = false;
|
||||
let key_end = logical
|
||||
.char_indices()
|
||||
.find_map(|(i, ch)| {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
return None;
|
||||
}
|
||||
if ch == '\\' {
|
||||
escaped = true;
|
||||
return None;
|
||||
}
|
||||
matches!(ch, '=' | ':' | ' ' | '\t' | '\u{c}').then_some(i)
|
||||
})
|
||||
.unwrap_or(logical.len());
|
||||
if key_end > 0
|
||||
&& key_end <= 1024
|
||||
&& let Some(name) = unescape_property(&logical[..key_end])
|
||||
{
|
||||
out.push(ConfigurationKey { name, range: lines.range(offsets[0], offsets[key_end - 1] + 1) });
|
||||
}
|
||||
logical.clear();
|
||||
offsets.clear();
|
||||
}
|
||||
base += line.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn unescape_property(raw: &str) -> Option<String> {
|
||||
let mut chars = raw.chars();
|
||||
let mut out = String::new();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch != '\\' {
|
||||
out.push(ch);
|
||||
continue;
|
||||
}
|
||||
match chars.next()? {
|
||||
'u' => {
|
||||
let hex: String = chars.by_ref().take(4).collect();
|
||||
if hex.len() != 4 {
|
||||
return None;
|
||||
}
|
||||
out.push(char::from_u32(u32::from_str_radix(&hex, 16).ok()?)?);
|
||||
}
|
||||
't' => out.push('\t'),
|
||||
'n' => out.push('\n'),
|
||||
'r' => out.push('\r'),
|
||||
'f' => out.push('\u{c}'),
|
||||
ch => out.push(ch),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn java_configuration_sites() {
|
||||
let text = r#"package a;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
class A {
|
||||
@Value("${app.port:80}") int port;
|
||||
@org.springframework.beans.factory.annotation.Value(value = Keys.NAME) String name;
|
||||
@Values("x") int other;
|
||||
@Override public String toString() {
|
||||
String v = env.getProperty("app.host", "h") + env.getRequiredProperty(Keys.USER);
|
||||
return helper.getValue("😀 app.port") + String.valueOf(port) + env.getProperty("k").trim();
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let syntax = Syntax::new();
|
||||
let at = |needle: &str, offset: u32| {
|
||||
let line = text.lines().position(|l| l.contains(needle)).unwrap();
|
||||
let byte = text.lines().nth(line).unwrap().find(needle).unwrap();
|
||||
let col = text.lines().nth(line).unwrap()[..byte].encode_utf16().count() as u32 + offset;
|
||||
syntax.java_configuration_site(text, Pos::new(line as u32, col), &|| false)
|
||||
};
|
||||
// @Value arguments (literal, qualified annotation, constant key).
|
||||
assert!(at("${app.port", 2));
|
||||
assert!(at("Keys.NAME", 6));
|
||||
// Lookup arguments, including a constant and the default value.
|
||||
assert!(at("\"app.host\"", 3));
|
||||
assert!(at("\"h\"", 1));
|
||||
assert!(at("Keys.USER", 1));
|
||||
assert!(at("\"k\"", 1));
|
||||
// Ordinary Java: names, other annotations, other calls, the lookup's own name and receiver.
|
||||
assert!(!at("@Value(\"$", 2));
|
||||
assert!(!at("int port", 4));
|
||||
assert!(!at("@Values", 9));
|
||||
assert!(!at("@Override", 2));
|
||||
assert!(!at("getProperty(\"app", 3));
|
||||
assert!(!at("env.getProperty(\"app", 1));
|
||||
assert!(!at("app.port\")", 1));
|
||||
assert!(!at("valueOf", 2));
|
||||
assert!(!at(".trim", 2));
|
||||
// Out of range and non-Java input.
|
||||
assert!(!syntax.java_configuration_site(text, Pos::new(99, 0), &|| false));
|
||||
assert!(!syntax.java_configuration_site("", Pos::new(0, 0), &|| false));
|
||||
}
|
||||
#[test]
|
||||
fn yaml_structures_and_utf16() {
|
||||
let text = "app:\n 'time-out': 1\n hosts:\n - url: a\n - {url: b}\n map: {east: {size: 2}}\n---\n\"app.name\": ok\n'😀': {port: 3}\n";
|
||||
let keys = Syntax::new().configuration_keys(&LanguageId::new("yaml"), text, &|| false).unwrap();
|
||||
let names: Vec<_> = keys.iter().map(|k| k.name.as_str()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"app",
|
||||
"app.time-out",
|
||||
"app.hosts",
|
||||
"app.hosts[0].url",
|
||||
"app.hosts[1].url",
|
||||
"app.map",
|
||||
"app.map.east",
|
||||
"app.map.east.size",
|
||||
"app.name",
|
||||
"😀",
|
||||
"😀.port"
|
||||
]
|
||||
);
|
||||
assert_eq!(keys.last().unwrap().range.start.col, 7);
|
||||
}
|
||||
#[test]
|
||||
fn aliases_and_values_are_not_configuration_keys() {
|
||||
let keys = Syntax::new()
|
||||
.configuration_keys(
|
||||
&LanguageId::new("yaml"),
|
||||
"base: &base {size: 1}\napp:\n <<: *base\n text: |\n fake: key\n",
|
||||
&|| false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(keys.iter().map(|k| k.name.as_str()).collect::<Vec<_>>(), ["base", "base.size", "app", "app.text"]);
|
||||
}
|
||||
#[test]
|
||||
fn properties_unicode_ranges_and_eof_continuation() {
|
||||
let keys = properties("app.中文=1\nlast\\\n");
|
||||
assert_eq!(keys[0].range.end.col, 6);
|
||||
assert_eq!(keys[1].name, "last");
|
||||
}
|
||||
#[test]
|
||||
fn properties_escapes_continuations_and_comments() {
|
||||
let keys = properties(
|
||||
"# comment\r\napp.time\\\n -out : 1\napp\\.name=ok\napp.\\u0061=2\nspace\\ key value\n!ignored=x\n",
|
||||
);
|
||||
assert_eq!(
|
||||
keys.iter().map(|k| k.name.as_str()).collect::<Vec<_>>(),
|
||||
["app.time-out", "app.name", "app.a", "space key"]
|
||||
);
|
||||
assert_eq!(keys[0].range.end.line, 2);
|
||||
}
|
||||
}
|
||||
@@ -86,16 +86,6 @@ pub(crate) fn utf16_len(s: &str) -> u32 {
|
||||
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
|
||||
}
|
||||
|
||||
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
|
||||
pub(crate) fn byte_at(text: &str, pos: Pos) -> Option<usize> {
|
||||
let mut start = 0;
|
||||
for _ in 0..pos.line {
|
||||
start += text[start..].find('\n')? + 1;
|
||||
}
|
||||
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
|
||||
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_to_byte(s: &str, offset: usize) -> usize {
|
||||
let mut units = 0;
|
||||
for (i, c) in s.char_indices() {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting.
|
||||
|
||||
mod cache;
|
||||
mod configuration;
|
||||
mod folding;
|
||||
mod grammars;
|
||||
mod highlight;
|
||||
@@ -13,7 +12,6 @@ mod web;
|
||||
|
||||
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
|
||||
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
|
||||
pub use configuration::ConfigurationKey;
|
||||
use grammars::{SPECS, Spec};
|
||||
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
|
||||
use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! `<style>` elements of HTML documents and feed the symbol index (see
|
||||
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
|
||||
|
||||
use super::lines::{LineIndex, byte_at};
|
||||
use super::lines::{LineIndex, utf16_to_byte};
|
||||
use super::{Grammar, parse};
|
||||
use crate::SymbolTag;
|
||||
use ide_core::{Pos, Range, SymbolKind};
|
||||
@@ -130,6 +130,15 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text:
|
||||
out
|
||||
}
|
||||
|
||||
fn byte_at(text: &str, pos: Pos) -> Option<usize> {
|
||||
let mut start = 0;
|
||||
for _ in 0..pos.line {
|
||||
start += text[start..].find('\n')? + 1;
|
||||
}
|
||||
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
|
||||
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
|
||||
}
|
||||
|
||||
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
|
||||
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
|
||||
let rel = at.checked_sub(base)?;
|
||||
|
||||
@@ -621,7 +621,7 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
})
|
||||
.map(|e| conv.text_edit(&path, e))
|
||||
.collect();
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version: e.text_document.version });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits });
|
||||
};
|
||||
if let Some(changes) = e.document_changes {
|
||||
match changes {
|
||||
@@ -657,11 +657,11 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
for (uri, edits) in changes {
|
||||
if let Some(path) = uri_path(&uri) {
|
||||
let edits = conv.text_edits(&path, edits);
|
||||
files.push(FileEdit::Edit { path: path.into(), edits, version: None });
|
||||
files.push(FileEdit::Edit { path: path.into(), edits });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edit = WorkspaceEdit { files, ..Default::default() };
|
||||
let mut edit = WorkspaceEdit { files };
|
||||
edit.deduplicate();
|
||||
edit
|
||||
}
|
||||
@@ -670,36 +670,28 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
/// `edit` where they leave its own alone: what only the other server sees
|
||||
/// (Angular templates next to vtsls's TypeScript).
|
||||
pub fn merge_workspace_edit(edit: &mut WorkspaceEdit, extra: WorkspaceEdit) {
|
||||
edit.preconditions.extend(extra.preconditions);
|
||||
let overlap =
|
||||
|a: &TextEdit, b: &TextEdit| a.range == b.range || (a.range.start < b.range.end && b.range.start < a.range.end);
|
||||
for file in extra.files {
|
||||
let FileEdit::Edit { path, edits, version } = file else {
|
||||
let FileEdit::Edit { path, edits } = file else {
|
||||
if !edit.files.contains(&file) {
|
||||
edit.files.push(file);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let own = edit.files.iter_mut().find_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits, version } if *p == path => Some((edits, version)),
|
||||
FileEdit::Edit { path: p, edits } if *p == path => Some(edits),
|
||||
_ => None,
|
||||
});
|
||||
match own {
|
||||
Some((own, own_version)) => {
|
||||
// Conflicting versions cannot describe one consistent edit. Keep both
|
||||
// operations so transaction preflight rejects them instead of dropping a guard.
|
||||
if own_version.is_some() && version.is_some() && *own_version != version {
|
||||
edit.files.push(FileEdit::Edit { path, edits, version });
|
||||
continue;
|
||||
}
|
||||
*own_version = own_version.or(version);
|
||||
Some(own) => {
|
||||
let added: Vec<TextEdit> = edits.into_iter().filter(|e| !own.iter().any(|o| overlap(o, e))).collect();
|
||||
if !added.is_empty() {
|
||||
own.extend(added);
|
||||
own.sort_by_key(|e| e.range.start);
|
||||
}
|
||||
}
|
||||
None => edit.files.push(FileEdit::Edit { path, edits, version }),
|
||||
None => edit.files.push(FileEdit::Edit { path, edits }),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1044,20 +1036,16 @@ mod tests {
|
||||
range: Range::new(Pos::new(l, c), Pos::new(l, c + 5)),
|
||||
new_text: text.into(),
|
||||
};
|
||||
let file =
|
||||
|p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits, version: None };
|
||||
let file = |p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits };
|
||||
// vtsls renames a shorthand property with an alias; the Angular server
|
||||
// renames it plainly and adds the template.
|
||||
let mut merged = WorkspaceEdit {
|
||||
files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])],
|
||||
..Default::default()
|
||||
};
|
||||
let mut merged =
|
||||
WorkspaceEdit { files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])] };
|
||||
let angular = WorkspaceEdit {
|
||||
files: vec![
|
||||
file("/a.ts", vec![edit(9, 4, "entries"), edit(3, 2, "entries"), edit(1, 14, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
merge_workspace_edit(&mut merged, angular);
|
||||
assert_eq!(
|
||||
@@ -1318,7 +1306,7 @@ mod tests {
|
||||
assert_eq!(w.files.len(), 4);
|
||||
assert_eq!(w.files[0], FileEdit::Create { path: "/n.rs".into(), overwrite: true });
|
||||
match &w.files[1] {
|
||||
FileEdit::Edit { path, edits, .. } => {
|
||||
FileEdit::Edit { path, edits } => {
|
||||
assert_eq!(path, Path::new("/n.rs"));
|
||||
assert_eq!(edits.len(), 2);
|
||||
assert_eq!(edits[1].new_text, "y");
|
||||
@@ -1334,26 +1322,6 @@ mod tests {
|
||||
assert!(matches!(&workspace_edit(&conv, e).files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "q"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_edits_preserve_document_versions_and_merge_guards() {
|
||||
let conv = Conv::utf16();
|
||||
let incoming = |version| {
|
||||
serde_json::from_value(json!({
|
||||
"documentChanges": [{
|
||||
"textDocument": { "uri": "file:///a.rs", "version": version },
|
||||
"edits": [{ "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } }, "newText": "x" }]
|
||||
}]
|
||||
})).unwrap()
|
||||
};
|
||||
let mut edit = workspace_edit(&conv, incoming(Some(7)));
|
||||
assert!(matches!(edit.files[0], FileEdit::Edit { version: Some(7), .. }));
|
||||
merge_workspace_edit(&mut edit, workspace_edit(&conv, incoming(None::<i32>)));
|
||||
assert!(matches!(edit.files[0], FileEdit::Edit { version: Some(7), .. }));
|
||||
merge_workspace_edit(&mut edit, workspace_edit(&conv, incoming(Some(8))));
|
||||
assert_eq!(edit.files.len(), 2, "inconsistent version guards must not be discarded");
|
||||
assert!(matches!(edit.files[1], FileEdit::Edit { version: Some(8), .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_token_decoding() {
|
||||
let data = [1, 2, 3, 0, 1, 0, 5, 2, 1, 0, 2, 0, 4, 2, 3];
|
||||
|
||||
@@ -18,7 +18,6 @@ use std::time::{Duration, Instant};
|
||||
|
||||
const SERVER: &str = "jdtls";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
mod formatter;
|
||||
pub use formatter::configure_formatter;
|
||||
/// First start imports the Maven / Gradle model, which can take minutes.
|
||||
@@ -521,15 +520,11 @@ impl LspManager {
|
||||
}
|
||||
|
||||
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
|
||||
/// The classpath queries take the module's workspace scheduling rule like the build
|
||||
/// commands do, so they run under the build lock; pass `build_lock_held` when the caller
|
||||
/// already holds it (the delegated external build), or the wait would deadlock.
|
||||
pub async fn java_launch(
|
||||
&self,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
build: bool,
|
||||
build_lock_held: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let build = if build { Some(self.java_build(module, cancel).await?) } else { None };
|
||||
@@ -542,23 +537,14 @@ impl LspManager {
|
||||
}
|
||||
_ => (Vec::new(), 0),
|
||||
};
|
||||
let (cp, java_home) = {
|
||||
let (server, _) = self.jdtls(module, cancel).await?;
|
||||
let _lock = if build_lock_held {
|
||||
let cp = self.java_classpath(module, test, cancel).await?;
|
||||
let java_home = match self.java_vm_location(module, cancel).await {
|
||||
Ok(home) => home,
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("java.project.getSettings: {e}");
|
||||
None
|
||||
} else {
|
||||
Some(cancellable_wait(cancel, server.java_build_lock.lock()).await?)
|
||||
};
|
||||
let cp = self.java_classpath(module, test, cancel).await?;
|
||||
let java_home = match self.java_vm_location(module, cancel).await {
|
||||
Ok(home) => home,
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("java.project.getSettings: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
(cp, java_home)
|
||||
}
|
||||
};
|
||||
Ok(JavaLaunchInfo {
|
||||
build,
|
||||
|
||||
@@ -1,428 +0,0 @@
|
||||
//! Bridges configuration syntax to the app-owned JDT extension. No additional
|
||||
//! language server, build, or network request is needed. Disk parsing runs on a
|
||||
//! blocking worker; open buffers always win over cached disk contents.
|
||||
use super::*;
|
||||
use crate::text::Encoding;
|
||||
use crate::types::{References, ReferencesIncomplete};
|
||||
use crate::{DocSnap, Target};
|
||||
use ide_core::{Location, Pos};
|
||||
use ide_language::{ConfigurationKey, Syntax};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::SystemTime;
|
||||
|
||||
const COMMAND: &str = "openidea.java.configuration";
|
||||
const MAX_BYTES: u64 = 2 * 1024 * 1024;
|
||||
const MAX_FILES: usize = 2000;
|
||||
const MAX_CACHED_KEYS: usize = 100_000;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ConfigurationCache {
|
||||
files: HashMap<PathBuf, CachedFile>,
|
||||
}
|
||||
struct CachedFile {
|
||||
stamp: (SystemTime, u64),
|
||||
keys: Vec<ConfigurationKey>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Pattern {
|
||||
name: String,
|
||||
relaxed: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
locations: Vec<lsp_types::Location>,
|
||||
#[serde(default)]
|
||||
keys: Vec<Pattern>,
|
||||
#[serde(default)]
|
||||
roots: Vec<String>,
|
||||
#[serde(default)]
|
||||
incomplete: bool,
|
||||
}
|
||||
fn syntax() -> &'static Syntax {
|
||||
static SYNTAX: OnceLock<Syntax> = OnceLock::new();
|
||||
SYNTAX.get_or_init(Syntax::new)
|
||||
}
|
||||
fn language(path: &Path) -> Option<LanguageId> {
|
||||
match path.extension()?.to_str()? {
|
||||
"yaml" | "yml" => Some(LanguageId::new("yaml")),
|
||||
"properties" => Some(LanguageId::new("properties")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn parts(key: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut part = String::new();
|
||||
let mut chars = key.chars().peekable();
|
||||
let mut bracket = false;
|
||||
while let Some(ch) = chars.next() {
|
||||
match ch {
|
||||
'[' => {
|
||||
if !part.is_empty() {
|
||||
out.push(std::mem::take(&mut part));
|
||||
}
|
||||
for ch in chars.by_ref() {
|
||||
if ch == ']' {
|
||||
break;
|
||||
}
|
||||
if !matches!(ch, '-' | '_') {
|
||||
part.extend(ch.to_lowercase());
|
||||
}
|
||||
}
|
||||
out.push(std::mem::take(&mut part));
|
||||
bracket = true;
|
||||
}
|
||||
'.' => {
|
||||
if !bracket {
|
||||
out.push(std::mem::take(&mut part));
|
||||
}
|
||||
bracket = false;
|
||||
}
|
||||
'-' | '_' => {}
|
||||
ch => {
|
||||
part.extend(ch.to_lowercase());
|
||||
bracket = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !part.is_empty() {
|
||||
out.push(part);
|
||||
}
|
||||
out
|
||||
}
|
||||
fn matches(pattern: &Pattern, key: &str) -> bool {
|
||||
if !pattern.relaxed {
|
||||
return pattern.name == key;
|
||||
}
|
||||
let (a, b) = (parts(&pattern.name), parts(key));
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a == "*" || *a == b)
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
pub(crate) async fn configuration_navigation(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
pos: Pos,
|
||||
usages: bool,
|
||||
include_declaration: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<References>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let config = language(&snap.path).is_some();
|
||||
if !config && snap.language.as_str() != "java" {
|
||||
return Ok(None);
|
||||
}
|
||||
// Definition in ordinary Java code remains JDT's definition. Reverse
|
||||
// configuration navigation is offered only inside `@Value` / property
|
||||
// lookup arguments: the command builds a project-wide index, and every
|
||||
// Ctrl+click and Ctrl+hover probe would otherwise wait on it before JDT
|
||||
// answers. Field/config accessor usages are merged into Find Usages.
|
||||
if !config && !usages {
|
||||
let text = snap.text.as_str();
|
||||
if !text.contains("Value") && !text.contains("getProperty") && !text.contains("getRequiredProperty") {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = text.to_owned();
|
||||
let cancelled = cancel.clone();
|
||||
let site = tokio::task::spawn_blocking(move || {
|
||||
syntax().java_configuration_site(&text, pos, &|| cancelled.is_cancelled())
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !site {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let key = if config {
|
||||
let text = snap.text.as_str().to_owned();
|
||||
if text.len() as u64 > MAX_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
let lang = language(&snap.path).expect("configuration language");
|
||||
let cancelled = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
syntax()
|
||||
.configuration_keys(&lang, &text, &|| cancelled.is_cancelled())
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.find(|key| key.range.start <= pos && pos < key.range.end)
|
||||
.map(|key| key.name)
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if config && key.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
if config {
|
||||
// Avoid starting a JVM for unrelated YAML (CI, Kubernetes, etc.).
|
||||
let path = snap.path.clone();
|
||||
let root = self.project_root.clone();
|
||||
let java_project = tokio::task::spawn_blocking(move || {
|
||||
path.ancestors().take_while(|p| p.starts_with(&root)).any(|p| {
|
||||
["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"]
|
||||
.iter()
|
||||
.any(|name| p.join(name).is_file())
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !java_project {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let result = self.configuration_query(snap, pos, key, usages, include_declaration, cancel).await;
|
||||
match result {
|
||||
Err(e) if cancel.is_cancelled() || e.kind == ErrorKind::Cancelled => Err(IdeError::cancelled()),
|
||||
Err(e) => {
|
||||
tracing::debug!("Configuration navigation unavailable; retaining native language navigation: {e}");
|
||||
Ok(None)
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn configuration_query(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
pos: Pos,
|
||||
key: Option<String>,
|
||||
usages: bool,
|
||||
include_declaration: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<References>> {
|
||||
let (server, run) = self.jdtls(&snap.path, cancel).await?;
|
||||
if !run.caps.read().commands().iter().any(|command| command == COMMAND) {
|
||||
return Ok(None);
|
||||
}
|
||||
let target = Target { server: server.clone(), run };
|
||||
let position = snap.text.ide_to_lsp(Encoding::Utf16, pos);
|
||||
let response: Response = self
|
||||
.call(
|
||||
&target,
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"command": COMMAND, "arguments": [snap.uri, key, position.line, position.character, usages, include_declaration]
|
||||
}),
|
||||
Some(cancel),
|
||||
crate::LONG_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if response.keys.is_empty() {
|
||||
return Ok(response
|
||||
.incomplete
|
||||
.then(|| References { incomplete: Some(ReferencesIncomplete::FilesSkipped), ..Default::default() }));
|
||||
}
|
||||
let mut result = References {
|
||||
locations: response.locations.iter().filter_map(|l| self.conv(Encoding::Utf16).location(l)).collect(),
|
||||
incomplete: response.incomplete.then_some(ReferencesIncomplete::FilesSkipped),
|
||||
..Default::default()
|
||||
};
|
||||
self.note_virtual(&server, result.locations.iter().map(|l| l.uri.as_deref()));
|
||||
if key.is_none() || usages {
|
||||
let roots: Vec<PathBuf> = response.roots.iter().filter_map(|uri| super::project_path(uri)).collect();
|
||||
let overlays: HashMap<PathBuf, String> = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.filter(|d| language(&d.path).is_some() && d.text.as_str().len() as u64 <= MAX_BYTES)
|
||||
.map(|d| (d.canonical.clone(), d.text.as_str().to_owned()))
|
||||
.collect();
|
||||
let cache = self.configuration_cache.clone();
|
||||
let cancelled = cancel.clone();
|
||||
let keys = response.keys;
|
||||
let files =
|
||||
tokio::task::spawn_blocking(move || configuration_files(&roots, &keys, &overlays, &cache, &cancelled))
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("configuration search worker stopped"))?;
|
||||
result.locations.extend(files.locations);
|
||||
result.incomplete = result.incomplete.or(files.incomplete);
|
||||
}
|
||||
if cancel.is_cancelled() || !self.docs.lock().values().any(|d| d.uri == snap.uri && d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if usages && key.is_some() && !include_declaration {
|
||||
let source_path = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.find(|d| d.uri == snap.uri)
|
||||
.map(|d| d.canonical.clone())
|
||||
.unwrap_or_else(|| snap.path.clone());
|
||||
result.locations.retain(|location| {
|
||||
location.path.to_path_buf() != source_path || !(location.range.start <= pos && pos < location.range.end)
|
||||
});
|
||||
}
|
||||
crate::convert::dedup_locations(&mut result.locations);
|
||||
Ok(Some(result))
|
||||
}
|
||||
}
|
||||
|
||||
fn in_module(root: &Path, path: &Path) -> bool {
|
||||
if !path.starts_with(root) {
|
||||
return false;
|
||||
}
|
||||
for parent in path.parent().into_iter().flat_map(Path::ancestors).take_while(|p| *p != root) {
|
||||
if matches!(
|
||||
parent.file_name().and_then(|n| n.to_str()),
|
||||
Some("target" | "build" | "node_modules" | ".git" | ".gradle")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"].iter().any(|name| parent.join(name).is_file())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn configuration_files(
|
||||
roots: &[PathBuf],
|
||||
patterns: &[Pattern],
|
||||
overlays: &HashMap<PathBuf, String>,
|
||||
cache: &Mutex<ConfigurationCache>,
|
||||
cancel: &CancellationToken,
|
||||
) -> References {
|
||||
let mut result = References::default();
|
||||
let mut paths = std::collections::BTreeSet::new();
|
||||
// Do not scan a source root twice when its enclosing module is also present.
|
||||
let roots: Vec<_> =
|
||||
roots.iter().filter(|root| !roots.iter().any(|other| other != *root && root.starts_with(other))).collect();
|
||||
for root in &roots {
|
||||
let module = (*root).clone();
|
||||
let walker = ignore::WalkBuilder::new(root)
|
||||
.follow_links(false)
|
||||
.filter_entry(move |entry| {
|
||||
if !entry.file_type().is_some_and(|t| t.is_dir()) {
|
||||
return true;
|
||||
}
|
||||
if entry.path() == module {
|
||||
return true;
|
||||
}
|
||||
if matches!(entry.file_name().to_str(), Some("target" | "build" | "node_modules" | ".git" | ".gradle"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// A sibling application's identical key must not leak into this module.
|
||||
!["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"]
|
||||
.iter()
|
||||
.any(|name| entry.path().join(name).is_file())
|
||||
})
|
||||
.build();
|
||||
for (visited, entry) in walker.enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return result;
|
||||
}
|
||||
if visited >= 50_000 || paths.len() >= MAX_FILES {
|
||||
result.incomplete = Some(ReferencesIncomplete::TooManyFiles);
|
||||
break;
|
||||
}
|
||||
match entry {
|
||||
Ok(entry) if entry.file_type().is_some_and(|t| t.is_file()) && language(entry.path()).is_some() => {
|
||||
paths.insert(entry.into_path());
|
||||
}
|
||||
Err(_) => result.incomplete = Some(ReferencesIncomplete::FilesSkipped),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
paths.extend(overlays.keys().filter(|p| roots.iter().any(|r| in_module(r, p))).cloned());
|
||||
let mut cache = cache.lock();
|
||||
if cache.files.len() > MAX_FILES {
|
||||
cache.files.clear();
|
||||
}
|
||||
for path in paths {
|
||||
if cancel.is_cancelled() {
|
||||
return result;
|
||||
}
|
||||
let lang = language(&path).expect("configuration file");
|
||||
let keys = if let Some(text) = overlays.get(&path) {
|
||||
syntax().configuration_keys(&lang, text, &|| cancel.is_cancelled()).ok()
|
||||
} else {
|
||||
(|| {
|
||||
let metadata = std::fs::metadata(&path).ok()?;
|
||||
if metadata.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let stamp = (metadata.modified().ok()?, metadata.len());
|
||||
if let Some(file) = cache.files.get(&path).filter(|f| f.stamp == stamp) {
|
||||
return Some(file.keys.clone());
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).ok()?;
|
||||
let keys = syntax().configuration_keys(&lang, &text, &|| cancel.is_cancelled()).ok()?;
|
||||
cache.files.remove(&path);
|
||||
if cache.files.len() >= MAX_FILES
|
||||
|| cache.files.values().map(|file| file.keys.len()).sum::<usize>() + keys.len() > MAX_CACHED_KEYS
|
||||
{
|
||||
cache.files.clear();
|
||||
}
|
||||
cache.files.insert(path.clone(), CachedFile { stamp, keys: keys.clone() });
|
||||
Some(keys)
|
||||
})()
|
||||
};
|
||||
match keys {
|
||||
Some(keys) => result.locations.extend(
|
||||
keys.into_iter()
|
||||
.filter(|key| patterns.iter().any(|p| matches(p, &key.name)))
|
||||
.map(|key| Location::file(path.clone(), key.range)),
|
||||
),
|
||||
None => result.incomplete = Some(ReferencesIncomplete::FilesSkipped),
|
||||
}
|
||||
if result.locations.len() >= MAX_FILES {
|
||||
result.locations.truncate(MAX_FILES);
|
||||
result.incomplete = Some(ReferencesIncomplete::TooManyFiles);
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn file_cache_tracks_edits_overlays_removals_and_limits() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().to_path_buf();
|
||||
let file = root.join("application.properties");
|
||||
std::fs::write(&file, "app.port=1\n").unwrap();
|
||||
let patterns = [Pattern { name: "app.port".into(), relaxed: true }];
|
||||
let cache = Mutex::new(ConfigurationCache::default());
|
||||
let cancel = CancellationToken::new();
|
||||
let query = |overlays: &HashMap<PathBuf, String>| {
|
||||
configuration_files(std::slice::from_ref(&root), &patterns, overlays, &cache, &cancel)
|
||||
};
|
||||
assert_eq!(query(&HashMap::new()).locations.len(), 1);
|
||||
std::fs::write(&file, "app.other=12\n").unwrap();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
assert_eq!(query(&HashMap::from([(file.clone(), "app.port=unsaved\n".into())])).locations.len(), 1);
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
std::fs::write(&file, "x".repeat(MAX_BYTES as usize + 1)).unwrap();
|
||||
assert_eq!(query(&HashMap::new()).incomplete, Some(ReferencesIncomplete::FilesSkipped));
|
||||
cancel.cancel();
|
||||
assert!(query(&HashMap::new()).locations.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relaxed_binding_keeps_boundaries() {
|
||||
let pattern = Pattern { name: "app.clients[*].timeOut".into(), relaxed: true };
|
||||
assert!(matches(&pattern, "app.clients[2].time-out"));
|
||||
assert!(!matches(&pattern, "app.clientsTimeOut"));
|
||||
let map = Pattern { name: "app.routes.*.url".into(), relaxed: true };
|
||||
assert!(matches(&map, "app.routes[us.east].url"));
|
||||
assert!(!matches(&map, "app.routes.us.east.url"));
|
||||
assert!(!matches(&Pattern { name: "app.time-out".into(), relaxed: false }, "app.timeOut"));
|
||||
}
|
||||
}
|
||||
@@ -7,61 +7,6 @@ use std::path::Path;
|
||||
|
||||
const PROFILE: &str = "OpenIDEA IntelliJ IDEA";
|
||||
const XML: &str = include_str!("intellij.xml");
|
||||
const GENERATED_PROFILE: &str = "OpenIDEA Code Style";
|
||||
const TAB_CHAR: &str = "org.eclipse.jdt.core.formatter.tabulation.char";
|
||||
const TAB_SIZE: &str = "org.eclipse.jdt.core.formatter.tabulation.size";
|
||||
const INDENT_SIZE: &str = "org.eclipse.jdt.core.formatter.indentation.size";
|
||||
|
||||
/// The Tabs and Indents override as Eclipse formatter settings. The profile must
|
||||
/// carry them too: `indentation.size`, the per-level width, cannot come from the
|
||||
/// format request, and an unset Indent follows the tab size, as in IDEA.
|
||||
fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, String)>> {
|
||||
let tab_char = style.use_tab.map(|tab| if tab { "tab" } else { "space" });
|
||||
let indent = style.indent.or(style.tab_size);
|
||||
if tab_char.is_none() && style.tab_size.is_none() && indent.is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut settings: Vec<(&'static str, String)> = Vec::new();
|
||||
if let Some(char) = tab_char {
|
||||
settings.push((TAB_CHAR, char.to_owned()));
|
||||
}
|
||||
if let Some(size) = style.tab_size {
|
||||
settings.push((TAB_SIZE, size.to_string()));
|
||||
}
|
||||
if let Some(size) = indent {
|
||||
settings.push((INDENT_SIZE, size.to_string()));
|
||||
}
|
||||
Some(settings)
|
||||
}
|
||||
|
||||
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
|
||||
for (id, value) in settings {
|
||||
let marker = format!(r#"<setting id="{id}" value=""#);
|
||||
let Some(at) = xml.find(&marker) else { continue };
|
||||
let start = at + marker.len();
|
||||
let Some(end) = xml[start..].find('"') else { continue };
|
||||
xml.replace_range(start..start + end, value);
|
||||
}
|
||||
xml
|
||||
}
|
||||
|
||||
/// A minimal Eclipse profile with just the override: unset keys keep jdtls's
|
||||
/// built-in formatter defaults.
|
||||
fn indent_profile_xml(settings: &[(&'static str, String)]) -> String {
|
||||
let mut xml = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<profiles version="21">
|
||||
<profile kind="CodeFormatterProfile" name="{}" version="21">
|
||||
"#,
|
||||
GENERATED_PROFILE
|
||||
);
|
||||
for (id, value) in settings {
|
||||
xml.push_str(&format!(r#" <setting id="{id}" value="{value}"/>"#));
|
||||
xml.push('\n');
|
||||
}
|
||||
xml.push_str(" </profile>\n</profiles>\n");
|
||||
xml
|
||||
}
|
||||
|
||||
/// Protocol settings only: switching profiles reaches a running jdtls through
|
||||
/// didChangeConfiguration. Explicit language-server settings are applied later.
|
||||
@@ -86,17 +31,12 @@ pub fn configure_formatter(
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
|
||||
cfg.settings = Some(settings);
|
||||
let Some(style) = style else { return Ok(()) };
|
||||
let indent = indent_settings(style);
|
||||
let (path, profile) = match style.formatter.as_deref() {
|
||||
Some("intellij") => {
|
||||
let path = data_dir.join("lsp/jdtls/intellij.xml");
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
let xml = match indent {
|
||||
Some(indent) => patch_profile_xml(XML.to_owned(), &indent),
|
||||
None => XML.to_owned(),
|
||||
};
|
||||
if std::fs::read_to_string(&path).ok().as_deref() != Some(xml.as_str()) {
|
||||
ide_vfs::write_atomic(&path, xml.as_bytes())?;
|
||||
if std::fs::read_to_string(&path).ok().as_deref() != Some(XML) {
|
||||
ide_vfs::write_atomic(&path, XML.as_bytes())?;
|
||||
}
|
||||
(path, PROFILE)
|
||||
}
|
||||
@@ -114,22 +54,9 @@ pub fn configure_formatter(
|
||||
if !path.is_file() {
|
||||
return Err(ide_core::IdeError::invalid(format!("Not a formatter XML file: {}", path.display())));
|
||||
}
|
||||
// The user's profile defines the style; the override stays editor-only.
|
||||
(path, "")
|
||||
}
|
||||
_ => {
|
||||
// Default formatter: with a Tabs and Indents override, hand jdtls a
|
||||
// minimal generated profile carrying it — the format request cannot
|
||||
// set indentation.size. Without an override the built-in style stays.
|
||||
let Some(indent) = indent else { return Ok(()) };
|
||||
let path = data_dir.join("lsp/jdtls/indent.xml");
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
let xml = indent_profile_xml(&indent);
|
||||
if std::fs::read_to_string(&path).ok().as_deref() != Some(xml.as_str()) {
|
||||
ide_vfs::write_atomic(&path, xml.as_bytes())?;
|
||||
}
|
||||
(path, GENERATED_PROFILE)
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(
|
||||
@@ -217,73 +144,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_and_indents_override_reaches_the_formatter_profile() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
let data = dir.path().join("data");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
|
||||
// The IntelliJ profile is the bundled XML with the override patched in.
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
formatter: Some("intellij".into()),
|
||||
use_tab: Some(true),
|
||||
tab_size: Some(1),
|
||||
indent: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
|
||||
let settings = crate::handler::all_settings(&cfg)["java"]["format"]["settings"].clone();
|
||||
assert_eq!(settings["profile"], PROFILE);
|
||||
let patched = std::fs::read_to_string(data.join("lsp/jdtls/intellij.xml")).unwrap();
|
||||
assert!(patched.contains(&format!(r#"<setting id="{TAB_CHAR}" value="tab"/>"#)));
|
||||
assert!(patched.contains(&format!(r#"<setting id="{TAB_SIZE}" value="1"/>"#)));
|
||||
assert!(patched.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="1"/>"#)));
|
||||
|
||||
// The default formatter gets a minimal generated profile.
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { use_tab: Some(false), tab_size: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
|
||||
let settings = crate::handler::all_settings(&cfg)["java"]["format"]["settings"].clone();
|
||||
let path = data.join("lsp/jdtls/indent.xml");
|
||||
assert_eq!(settings["url"], crate::uri::path_to_uri_string(&path));
|
||||
assert_eq!(settings["profile"], GENERATED_PROFILE);
|
||||
let xml = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(xml.contains(&format!(r#"<setting id="{TAB_CHAR}" value="space"/>"#)));
|
||||
// An unset Indent follows the tab size, as in IDEA.
|
||||
assert!(xml.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="2"/>"#)));
|
||||
|
||||
// Only Indent: the bundled tab settings stay.
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { formatter: Some("intellij".into()), indent: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, &data, None).unwrap();
|
||||
let patched = std::fs::read_to_string(data.join("lsp/jdtls/intellij.xml")).unwrap();
|
||||
assert!(patched.contains(&format!(r#"<setting id="{INDENT_SIZE}" value="2"/>"#)));
|
||||
assert!(patched.contains(&format!(r#"<setting id="{TAB_CHAR}" value="space"/>"#)));
|
||||
assert!(patched.contains(&format!(r#"<setting id="{TAB_SIZE}" value="4"/>"#)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_and_indents_override_leaves_custom_profiles_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let custom = root.join("style.xml");
|
||||
std::fs::write(&custom, XML).unwrap();
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
formatter: Some("custom".into()),
|
||||
formatter_path: Some("style.xml".into()),
|
||||
use_tab: Some(true),
|
||||
tab_size: Some(1),
|
||||
indent: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&custom).unwrap(), XML);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_custom_paths_are_nonfatal_and_do_not_set_launch_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -179,7 +179,6 @@ pub struct LspManager {
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
java_usages_warned: AtomicBool,
|
||||
configuration_cache: Arc<Mutex<jdtls::configuration::ConfigurationCache>>,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
shown_messages: Mutex<HashSet<(String, String)>>,
|
||||
/// Virtual (non-`file:`) URIs a server returned, by the server that owns them.
|
||||
@@ -314,7 +313,6 @@ impl LspManager {
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
java_usages_warned: AtomicBool::new(false),
|
||||
configuration_cache: Arc::new(Mutex::new(Default::default())),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
virtual_origins: Mutex::new(HashMap::new()),
|
||||
virtual_docs: Mutex::new(HashMap::new()),
|
||||
@@ -1124,15 +1122,6 @@ impl LspManager {
|
||||
}
|
||||
|
||||
pub async fn goto(&self, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
|
||||
if matches!(kind, GotoKind::Definition) {
|
||||
let snap = self.snapshot(doc)?;
|
||||
if let Some(result) =
|
||||
self.configuration_navigation(&snap, pos, false, false, &CancellationToken::new()).await?
|
||||
&& !result.locations.is_empty()
|
||||
{
|
||||
return Ok(result.locations);
|
||||
}
|
||||
}
|
||||
let (method, cap, feature) = goto_method(kind);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
self.goto_in(&snap, &targets, method, pos, None).await
|
||||
@@ -1211,36 +1200,6 @@ impl LspManager {
|
||||
include_declaration: bool,
|
||||
project_wide: bool,
|
||||
cancel: CancellationToken,
|
||||
) -> 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) = configuration
|
||||
{
|
||||
return Ok(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);
|
||||
convert::dedup_locations(&mut result.locations);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn native_references(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
include_declaration: bool,
|
||||
project_wide: bool,
|
||||
cancel: CancellationToken,
|
||||
) -> 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.
|
||||
@@ -1253,7 +1212,7 @@ impl LspManager {
|
||||
let t = &targets[0];
|
||||
let extension_error = Mutex::new(None);
|
||||
let query = || async {
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let params = snap.pos_params(t, pos);
|
||||
@@ -1281,7 +1240,7 @@ impl LspManager {
|
||||
*extension_error.lock() = Some(e.clone());
|
||||
}
|
||||
let rows = result?;
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let conv = self.conv(t.enc());
|
||||
@@ -1307,7 +1266,7 @@ impl LspManager {
|
||||
scope::Widened::only(first, empty, &t.server)
|
||||
};
|
||||
// A changed source also invalidates an earlier answer retained by scope widening.
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
|
||||
if cancel.is_cancelled() || !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Scope widening can retain the first answer after a failed second query.
|
||||
@@ -1333,7 +1292,7 @@ impl LspManager {
|
||||
Err(e) => {
|
||||
if e.kind == ErrorKind::Cancelled
|
||||
|| cancel.is_cancelled()
|
||||
|| self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version)
|
||||
|| !self.docs.lock().get(&doc).is_some_and(|d| d.version == snap.version)
|
||||
{
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -650,7 +650,7 @@ async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
assert_eq!(s.requested("codeAction/resolve")[0]["data"], json!({ "id": 7 }));
|
||||
let edit = resolved.edit.unwrap();
|
||||
assert!(
|
||||
matches!(&edit.files[0], FileEdit::Edit { path: p, edits, .. } if p == &path && edits[0].range == rng(0, 0, 1, 0))
|
||||
matches!(&edit.files[0], FileEdit::Edit { path: p, edits } if p == &path && edits[0].range == rng(0, 0, 1, 0))
|
||||
);
|
||||
|
||||
h.mgr.execute_command(doc, actions[1].command.clone().unwrap()).await.unwrap();
|
||||
@@ -695,9 +695,7 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
let edits = applied.lock().clone();
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].files[0], FileEdit::Create { path: new_file.into(), overwrite: false });
|
||||
assert!(
|
||||
matches!(&edits[0].files[1], FileEdit::Edit { path: p, edits, .. } if p == &path && edits[0].new_text == "X")
|
||||
);
|
||||
assert!(matches!(&edits[0].files[1], FileEdit::Edit { path: p, edits } if p == &path && edits[0].new_text == "X"));
|
||||
|
||||
let peer = s.peer();
|
||||
let cfg: Value = peer
|
||||
@@ -1166,40 +1164,6 @@ async fn unmanaged_java_run_imports_sources_without_an_open_editor() {
|
||||
assert!(state.notified("textDocument/didOpen").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_launch_serializes_the_classpath_with_the_build_lock() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (_, _file) = h.open("Main.java", "public class Main {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let state = h.launcher.state("jdtls");
|
||||
state.respond("java/buildWorkspace", json!(1));
|
||||
|
||||
// A launch with a build re-takes the lock after java_build has released it.
|
||||
let info = tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
h.mgr.java_launch(&h.root, false, true, false, &Default::default()),
|
||||
)
|
||||
.await
|
||||
.expect("java_launch deadlocked on the build lock")
|
||||
.unwrap();
|
||||
assert!(info.class_paths.is_empty());
|
||||
|
||||
// The delegated external build holds the lock while java_launch resolves the
|
||||
// classpath; java_launch must not re-take it, or the launch would deadlock.
|
||||
let guard = h.mgr.java_external_build(&h.root, &Default::default()).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(30), h.mgr.java_launch(&h.root, false, false, true, &Default::default()))
|
||||
.await
|
||||
.expect("java_launch deadlocked on the delegated external build's lock")
|
||||
.unwrap();
|
||||
drop(guard);
|
||||
let commands: Vec<_> = state
|
||||
.requested("workspace/executeCommand")
|
||||
.iter()
|
||||
.filter_map(|p| p["command"].as_str().map(str::to_owned))
|
||||
.collect();
|
||||
assert!(commands.contains(&"java.project.getClasspaths".to_owned()));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
// Preferred installed: the alternative is never started.
|
||||
@@ -1427,7 +1391,7 @@ fn edits_in(edit: &WorkspaceEdit, path: &Path) -> Vec<(Range, String)> {
|
||||
edit.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits, .. } if p.to_path_buf() == path => {
|
||||
FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| (e.range, e.new_text.clone())))
|
||||
}
|
||||
_ => None,
|
||||
@@ -1824,7 +1788,7 @@ async fn will_and_did_rename_files_honour_filters() {
|
||||
assert_eq!(result.servers, vec!["mock".to_owned()]);
|
||||
assert!(result.errors.is_empty());
|
||||
match &result.edit.files[..] {
|
||||
[FileEdit::Edit { path, edits, .. }] => {
|
||||
[FileEdit::Edit { path, edits }] => {
|
||||
assert_eq!(path, &main);
|
||||
assert_eq!(edits[0].range, rng(0, 4, 0, 7));
|
||||
assert_eq!(edits[0].new_text, "lib");
|
||||
@@ -2950,125 +2914,3 @@ async fn clang_tidy_config_for_a_later_opened_file_warns_on_a_running_server() {
|
||||
assert_eq!(h.mgr.servers().len(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_definition_uses_java_without_yaml_definition_capability() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
|
||||
let s = h.launcher.state("jdtls");
|
||||
let target = uri_of(&h.root.join("Settings.java"));
|
||||
s.respond("workspace/executeCommand", json!({
|
||||
"locations": [{"uri": target, "range": {"start": {"line": 2, "character": 4}, "end": {"line": 2, "character": 11}}}],
|
||||
"keys": [{"name": "app.timeOut", "relaxed": true}], "roots": []
|
||||
}));
|
||||
let path = h.root.join("application.yml");
|
||||
let doc = DocId::next();
|
||||
h.mgr.did_open(doc, &path, &LanguageId::new("yaml"), 1, "app:\n time-out: 5\n");
|
||||
let locations = h.mgr.goto(doc, Pos::new(1, 4), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start, Pos::new(2, 4));
|
||||
assert_eq!(s.requested("workspace/executeCommand")[0]["arguments"][1], "app.time-out");
|
||||
assert!(s.requested("textDocument/definition").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_usages_merge_native_and_unsaved_profiles_without_sibling_modules() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let (doc, path) = h.open("Settings.java", "int timeOut;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let root = uri_of(&h.root);
|
||||
s.respond(
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"locations": [], "keys": [{"name": "app.timeOut", "relaxed": true}], "roots": [root]
|
||||
}),
|
||||
);
|
||||
s.respond(
|
||||
"textDocument/references",
|
||||
json!([{"uri": uri_of(&path), "range": {
|
||||
"start": {"line": 3, "character": 0}, "end": {"line": 3, "character": 7}
|
||||
}}]),
|
||||
);
|
||||
std::fs::write(h.root.join("application.yml"), "app:\n time-out: 1\n").unwrap();
|
||||
std::fs::write(h.root.join("application-prod.properties"), "app.time-out=2\n").unwrap();
|
||||
let overlay = h.root.join("application-dev.yml");
|
||||
std::fs::write(&overlay, "app:\n old: 3\n").unwrap();
|
||||
h.mgr.did_open(DocId::next(), &overlay, &LanguageId::new("yaml"), 1, "app:\n time-out: 3\n");
|
||||
let sibling = h.root.join("other");
|
||||
std::fs::create_dir(&sibling).unwrap();
|
||||
std::fs::write(sibling.join("pom.xml"), "<project/>").unwrap();
|
||||
std::fs::write(sibling.join("application.yml"), "app:\n time-out: wrong\n").unwrap();
|
||||
h.mgr.did_open(
|
||||
DocId::next(),
|
||||
&sibling.join("application.yml"),
|
||||
&LanguageId::new("yaml"),
|
||||
1,
|
||||
"app:\n time-out: still-wrong\n",
|
||||
);
|
||||
let scoped = h.mgr.references(doc, Pos::new(0, 6), false, false, Default::default()).await.unwrap();
|
||||
assert_eq!(scoped.locations.len(), 1);
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 6), false, true, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.locations.len(), 4, "{refs:?}");
|
||||
assert!(refs.locations.iter().all(|l| !l.path.to_path_buf().starts_with(&sibling)));
|
||||
assert!(refs.locations.iter().any(|l| l.path.to_path_buf() == overlay));
|
||||
assert_eq!(refs.incomplete, None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_extension_failure_preserves_native_java_navigation() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let (doc, path) = h.open("Settings.java", "@Value(\"${app.port}\") int port;");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
s.errors.lock().insert("workspace/executeCommand".into(), (-32603, "old server".into()));
|
||||
s.respond(
|
||||
"textDocument/definition",
|
||||
json!({"uri": uri_of(&path), "range": {
|
||||
"start": {"line": 0, "character": 1}, "end": {"line": 0, "character": 6}
|
||||
}}),
|
||||
);
|
||||
let result = h.mgr.goto(doc, Pos::new(0, 12), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 1);
|
||||
assert_eq!(s.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
|
||||
/// The configuration command indexes the whole project, so Go to Definition (and
|
||||
/// every Ctrl+hover probe) consults it only inside a key argument; ordinary Java
|
||||
/// symbols in a Spring file go straight to JDT.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_definition_consults_configuration_only_inside_key_arguments() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let s = h.launcher.state("jdtls");
|
||||
let text = "class A {\n @Value(\"${app.port}\") int port;\n String a() { return env.getProperty(Keys.HOST) + x.getValue(); }\n}\n";
|
||||
let (doc, path) = h.open("A.java", text);
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
s.respond("workspace/executeCommand", json!({"locations": [], "keys": [], "roots": []}));
|
||||
s.respond(
|
||||
"textDocument/definition",
|
||||
json!({"uri": uri_of(&path), "range": {
|
||||
"start": {"line": 0, "character": 6}, "end": {"line": 0, "character": 7}
|
||||
}}),
|
||||
);
|
||||
// Field type, field name, method name, the lookup's receiver and name, another call.
|
||||
for pos in [Pos::new(1, 24), Pos::new(1, 28), Pos::new(2, 9), Pos::new(2, 22), Pos::new(2, 28), Pos::new(2, 53)] {
|
||||
assert_eq!(h.mgr.goto(doc, pos, GotoKind::Definition).await.unwrap().len(), 1, "{pos:?}");
|
||||
}
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
assert_eq!(s.requested("textDocument/definition").len(), 6);
|
||||
// Inside a placeholder and a constant lookup key: configuration first, JDT as fallback.
|
||||
for pos in [Pos::new(1, 13), Pos::new(2, 41)] {
|
||||
h.mgr.goto(doc, pos, GotoKind::Definition).await.unwrap();
|
||||
}
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 2);
|
||||
}
|
||||
@@ -194,102 +194,6 @@ async fn ty_python_end_to_end() {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Ruff next to basedpyright in a project configured for Ruff: its lint
|
||||
/// diagnostics, the only formatter and the only Organize Imports and Fix All.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires ruff and basedpyright on PATH"]
|
||||
async fn ruff_next_to_basedpyright_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.ruff.lint]\nselect = [\"F\", \"I\"]\n").unwrap();
|
||||
let path = root.join("example.py");
|
||||
let source = "import sys\nimport os\n\nx = os.getcwd( )\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
|
||||
python.language_servers.retain(|server| matches!(server.name.as_str(), "basedpyright" | "ruff"));
|
||||
assert_eq!(python.language_servers.len(), 2);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
|
||||
for name in ["basedpyright", "ruff"] {
|
||||
retry(name, Duration::from_secs(60), || {
|
||||
let status = last_status(&events, name);
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("{name} failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
}
|
||||
// F401 (`sys` unused) and I001 (unsorted imports).
|
||||
let codes = retry("ruff diagnostics", Duration::from_secs(30), || {
|
||||
let codes: Option<Vec<String>> = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { source, items, .. } if source == "ruff" && !items.is_empty() => {
|
||||
Some(items.iter().filter_map(|d| d.code.clone()).collect())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
async move { codes }
|
||||
})
|
||||
.await;
|
||||
assert!(codes.iter().any(|c| c == "F401") && codes.iter().any(|c| c == "I001"), "{codes:?}");
|
||||
|
||||
let options = ide_lsp::types::FormatOptions { tab_size: 4, insert_spaces: true, on_save: false };
|
||||
let edits = mgr.format(doc, None, options).await.unwrap();
|
||||
assert!(!edits.is_empty() && edits.iter().all(|e| e.range.start.line == 3), "{edits:?}");
|
||||
|
||||
let whole = Range::new(Pos::new(0, 0), Pos::new(4, 0));
|
||||
for kind in ["source.organizeImports", "source.fixAll"] {
|
||||
let actions = mgr.code_actions(doc, whole, vec![kind.into()]).await.unwrap();
|
||||
let kinds: Vec<&str> = actions.iter().filter_map(|a| a.kind.as_deref()).collect();
|
||||
assert_eq!(kinds, [format!("{kind}.ruff")], "{actions:?}");
|
||||
let action = mgr.resolve_code_action(doc, actions[0].clone()).await.unwrap();
|
||||
let edit = action.edit.expect("an edit");
|
||||
assert!(!edited_lines(&edit, &path).is_empty(), "{edit:?}");
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires pyrefly on PATH"]
|
||||
async fn pyrefly_python_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let path = root.join("example.py");
|
||||
let source = "def greet(name: str) -> str:\n return name\n\nresult = greet('Ada')\nbad: int = 'wrong'\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
// Pyrefly only reports type errors in projects with a Pyrefly configuration.
|
||||
std::fs::write(root.join("pyrefly.toml"), "").unwrap();
|
||||
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
|
||||
python.language_servers.retain(|server| server.name == "pyrefly");
|
||||
assert_eq!(python.language_servers.len(), 1);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
|
||||
retry("pyrefly ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "pyrefly");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("pyrefly failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
let defs = retry("pyrefly definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, Pos::new(3, 10), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs[0].path, path);
|
||||
assert_eq!(defs[0].range.start.line, 0);
|
||||
retry("pyrefly diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().any(
|
||||
|event| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "pyrefly" && !items.is_empty()),
|
||||
);
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires rust-analyzer"]
|
||||
async fn rust_analyzer_end_to_end() {
|
||||
@@ -508,7 +412,7 @@ fn edited_lines(edit: &ide_core::WorkspaceEdit, path: &Path) -> Vec<u32> {
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path: p, edits, .. } if p.to_path_buf() == path => {
|
||||
ide_core::FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| e.range.start.line))
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -15,7 +15,8 @@ toml.workspace = true
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tempfile.workspace = true
|
||||
zip.workspace = true
|
||||
wasmtime = { version = "49.0.4", default-features = false, features = ["runtime", "cranelift", "component-model", "std", "parallel-compilation"] }
|
||||
wasmtime-wasi = { version = "49.0.4", default-features = false, features = ["p2"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -15,7 +15,6 @@
|
||||
//! (dev plugins, loaded by [`PluginHost::sync_project`]).
|
||||
|
||||
mod manifest;
|
||||
mod package;
|
||||
mod runtime;
|
||||
mod sandbox;
|
||||
mod theme;
|
||||
@@ -264,20 +263,6 @@ impl PluginHost {
|
||||
self.info_of(&new_id)
|
||||
}
|
||||
|
||||
/// Installs the package at `path`: a folder, its `plugin.toml`, or a `.zip` of the folder.
|
||||
pub fn install_from_path(&self, path: &Path) -> IdeResult<PluginInfo> {
|
||||
if package::is_zip(path) && path.is_file() {
|
||||
// Outside the plugins directory: a crash must not leave a package that loads.
|
||||
let unpacked = tempfile::Builder::new().prefix("openidea-plugin-").tempdir()?;
|
||||
let root = package::unpack_zip(path, unpacked.path())?;
|
||||
return self.install_from_dir(&root);
|
||||
}
|
||||
if path.file_name().is_some_and(|name| name == MANIFEST_FILE) && path.is_file() {
|
||||
return self.install_from_dir(path.parent().unwrap_or(path));
|
||||
}
|
||||
self.install_from_dir(path)
|
||||
}
|
||||
|
||||
/// Copies a plugin package (manifest + referenced files) into the plugins
|
||||
/// directory, replacing an installed version with the same id.
|
||||
pub fn install_from_dir(&self, src: &Path) -> IdeResult<PluginInfo> {
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
//! Plugin packages on disk: a folder, its `plugin.toml`, or a `.zip` of the folder.
|
||||
|
||||
use crate::MANIFEST_FILE;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, BufReader, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Far above any real package; stops a zip bomb before it fills the disk.
|
||||
const MAX_ENTRIES: usize = 10_000;
|
||||
const MAX_UNPACKED_BYTES: u64 = 1024 * 1024 * 1024;
|
||||
|
||||
pub(crate) fn is_zip(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"))
|
||||
}
|
||||
|
||||
fn invalid_zip(zip: &Path, reason: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::invalid(format!("{} is not a valid plugin archive: {reason}", zip.display()))
|
||||
}
|
||||
|
||||
/// Unpacks `zip` into `dest` and returns the package folder inside it. Refuses the
|
||||
/// whole archive when an entry would leave `dest` or is a symbolic link.
|
||||
pub(crate) fn unpack_zip(zip: &Path, dest: &Path) -> IdeResult<PathBuf> {
|
||||
let mut archive = zip::ZipArchive::new(BufReader::new(File::open(zip)?)).map_err(|e| invalid_zip(zip, e))?;
|
||||
if archive.len() > MAX_ENTRIES {
|
||||
return Err(invalid_zip(zip, format!("more than {MAX_ENTRIES} entries")));
|
||||
}
|
||||
let mut budget = MAX_UNPACKED_BYTES;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive.by_index(i).map_err(|e| invalid_zip(zip, e))?;
|
||||
let name = entry.name().to_owned();
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
return Err(invalid_zip(zip, format!("unsafe path {name:?}")));
|
||||
};
|
||||
if entry.is_symlink() {
|
||||
return Err(invalid_zip(zip, format!("symbolic link {name:?}")));
|
||||
}
|
||||
let out = dest.join(rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// One byte over the budget tells a full budget from a file that exactly fits.
|
||||
let written =
|
||||
io::copy(&mut (&mut entry).take(budget + 1), &mut File::create(&out)?).map_err(|e| invalid_zip(zip, e))?;
|
||||
if written > budget {
|
||||
return Err(invalid_zip(zip, "it unpacks to more than 1 GB"));
|
||||
}
|
||||
budget -= written;
|
||||
}
|
||||
package_root(dest).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is not an OpenIDEA plugin: no {MANIFEST_FILE} at its root or in its only folder",
|
||||
zip.display()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// `dir` itself, or its only folder as when a zip holds the package folder.
|
||||
/// Archiver metadata (`__MACOSX`, dot files) does not count as a second folder.
|
||||
fn package_root(dir: &Path) -> Option<PathBuf> {
|
||||
if dir.join(MANIFEST_FILE).is_file() {
|
||||
return Some(dir.to_path_buf());
|
||||
}
|
||||
let mut folders = fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy();
|
||||
p.is_dir() && !name.starts_with('.') && name != "__MACOSX"
|
||||
});
|
||||
let only = folders.next().filter(|_| folders.next().is_none())?;
|
||||
only.join(MANIFEST_FILE).is_file().then_some(only)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ pub struct CatalogPlugin {
|
||||
pub authors: Vec<String>,
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
/// Package directory; install with `install_from_path(path)`.
|
||||
/// Package directory; install with `install_from_dir(path)`.
|
||||
pub path: ide_core::IpcPath,
|
||||
pub has_code: bool,
|
||||
pub permissions: Vec<Permission>,
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
use ide_plugin::*;
|
||||
use parking_lot::Mutex;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -511,93 +510,3 @@ fn restricted_dev_plugin_has_no_activation_registration() {
|
||||
f.host.sync_project(&f.project);
|
||||
assert!(f.host.list(Some(&f.project)).plugins.is_empty());
|
||||
}
|
||||
|
||||
/// Zips the files of `dir` under `prefix` (recursively).
|
||||
fn add_dir(zip: &mut zip::ZipWriter<std::fs::File>, dir: &Path, prefix: &str) {
|
||||
for entry in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let name = format!("{prefix}{}", entry.file_name().to_string_lossy());
|
||||
if entry.path().is_dir() {
|
||||
add_dir(zip, &entry.path(), &format!("{name}/"));
|
||||
} else {
|
||||
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(&std::fs::read(entry.path()).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn zip_of(dir: &Path, prefix: &str, out: &Path) -> PathBuf {
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(out).unwrap());
|
||||
add_dir(&mut zip, dir, prefix);
|
||||
zip.finish().unwrap();
|
||||
out.to_path_buf()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_zips_with_the_package_at_the_root_or_in_one_folder() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for (name, prefix) in [("root.ZIP", ""), ("folder.zip", "hello-1.0/")] {
|
||||
let zip = zip_of(&sample("hello"), prefix, &tmp.path().join(name));
|
||||
let info = f.host.install_from_path(&zip).unwrap();
|
||||
assert_eq!((info.id.as_str(), info.status), ("hello", PluginStatus::Active), "{:?}", info.error);
|
||||
assert!(f.plugins_dir.join("hello/dist/plugin.wasm").is_file());
|
||||
}
|
||||
// Still runs from the installed copy, not the unpacked archive.
|
||||
assert!(f.run("hello", "insert-date", None).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_from_a_manifest_or_a_folder() {
|
||||
let f = fixture(Limits::default());
|
||||
assert_eq!(f.host.install_from_path(&sample("hello").join("plugin.toml")).unwrap().id, "hello");
|
||||
assert_eq!(f.host.install_from_path(&sample("hello")).unwrap().id, "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_archiver_metadata_next_to_the_package_folder() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let out = tmp.path().join("mac.zip");
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&out).unwrap());
|
||||
add_dir(&mut zip, &sample("hello"), "hello/");
|
||||
zip.start_file("__MACOSX/hello/._plugin.toml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(b"metadata").unwrap();
|
||||
zip.finish().unwrap();
|
||||
assert_eq!(f.host.install_from_path(&out).unwrap().id, "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_zips_that_are_not_safe_plugin_packages() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let options = zip::write::SimpleFileOptions::default;
|
||||
|
||||
let no_manifest = tmp.path().join("idea-plugin.zip");
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&no_manifest).unwrap());
|
||||
zip.start_file("idea-plugin/lib/plugin.jar", options()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
let error = f.host.install_from_path(&no_manifest).unwrap_err();
|
||||
assert!(error.message.contains("no plugin.toml"), "{}", error.message);
|
||||
|
||||
let escape = tmp.path().join("escape.zip");
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&escape).unwrap());
|
||||
zip.start_file("../../evil.txt", options()).unwrap();
|
||||
zip.write_all(b"evil").unwrap();
|
||||
zip.finish().unwrap();
|
||||
let error = f.host.install_from_path(&escape).unwrap_err();
|
||||
assert!(error.message.contains("unsafe path"), "{}", error.message);
|
||||
|
||||
let link = tmp.path().join("link.zip");
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&link).unwrap());
|
||||
zip.add_symlink("plugin.toml", "/etc/passwd", options()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
let error = f.host.install_from_path(&link).unwrap_err();
|
||||
assert!(error.message.contains("symbolic link"), "{}", error.message);
|
||||
|
||||
let garbage = tmp.path().join("garbage.zip");
|
||||
std::fs::write(&garbage, "not a zip").unwrap();
|
||||
let error = f.host.install_from_path(&garbage).unwrap_err();
|
||||
assert!(error.message.contains("not a valid plugin archive"), "{}", error.message);
|
||||
|
||||
assert!(!f.plugins_dir.join("hello").exists());
|
||||
}
|
||||
@@ -33,7 +33,6 @@ pub(crate) fn detect_with_profiles(
|
||||
detect_maven(root, excluded_poms, &mut out);
|
||||
detect_go(root, &mut out);
|
||||
detect_python(root, &mut out);
|
||||
detect_ruby(root, &mut out);
|
||||
cmake::detect(root, profiles, &mut out);
|
||||
dotnet::detect(root, &mut out);
|
||||
detect_make(root, &mut out);
|
||||
@@ -891,146 +890,6 @@ fn detect_python(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
if uses_pytest(root) || env.has_tool(root, "pytest") {
|
||||
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
|
||||
}
|
||||
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
|
||||
if root.join("manage.py").is_file() {
|
||||
out.push(
|
||||
py_config(
|
||||
"django:test".into(),
|
||||
"manage.py test".into(),
|
||||
"django-test",
|
||||
env.python(),
|
||||
&["manage.py", "test"],
|
||||
)
|
||||
.test(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------- ruby
|
||||
|
||||
/// Tasks a Rakefile defines statically: `task :name`, `task "name" => deps`,
|
||||
/// `task name: [...]`, qualified by enclosing `namespace` blocks. `desc` lines are
|
||||
/// skipped; a `Rake::TestTask` contributes `test`. `load`/`import`ed files are not followed.
|
||||
pub(crate) fn rake_tasks(src: &str) -> Vec<String> {
|
||||
let mut tasks = Vec::new();
|
||||
let mut namespaces: Vec<String> = Vec::new();
|
||||
let mut depth: Vec<bool> = Vec::new(); // per open block: whether it is a namespace
|
||||
let name_of = |rest: &str| -> Option<String> {
|
||||
let rest = rest.trim_start();
|
||||
let (name, _) = if let Some(r) = rest.strip_prefix(':') {
|
||||
r.split(|c: char| !(c.is_alphanumeric() || c == '_')).next().map(|n| (n.to_owned(), ()))?
|
||||
} else if let Some(r) = rest.strip_prefix(['"', '\'']) {
|
||||
r.split(['"', '\'']).next().map(|n| (n.to_owned(), ()))?
|
||||
} else {
|
||||
let n: String = rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
(!n.is_empty() && rest[n.len()..].starts_with(':')).then_some((n, ()))?
|
||||
};
|
||||
(!name.is_empty()).then_some(name)
|
||||
};
|
||||
for raw in src.lines() {
|
||||
let line = raw.trim();
|
||||
if line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let opens = line.ends_with(" do") || line.contains(" do |") || line.contains(" do ") && !line.contains(" end");
|
||||
if let Some(rest) = line.strip_prefix("namespace ")
|
||||
&& let Some(ns) = name_of(rest)
|
||||
{
|
||||
namespaces.push(ns);
|
||||
depth.push(true);
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("task ").or_else(|| line.strip_prefix("task("))
|
||||
&& let Some(name) = name_of(rest)
|
||||
{
|
||||
let full = namespaces.iter().chain([&name]).cloned().collect::<Vec<_>>().join(":");
|
||||
if !tasks.contains(&full) {
|
||||
tasks.push(full);
|
||||
}
|
||||
}
|
||||
if line.contains("Rake::TestTask.new") || line.contains("RSpec::Core::RakeTask.new") {
|
||||
let name = name_of(line.split_once(".new").map(|(_, r)| r.trim_start_matches(['(', ' '])).unwrap_or(""))
|
||||
.unwrap_or_else(|| if line.contains("RSpec") { "spec".into() } else { "test".into() });
|
||||
let full = namespaces.iter().chain([&name]).cloned().collect::<Vec<_>>().join(":");
|
||||
if !tasks.contains(&full) {
|
||||
tasks.push(full);
|
||||
}
|
||||
}
|
||||
if opens && !line.starts_with("namespace ") {
|
||||
depth.push(false);
|
||||
}
|
||||
if (line == "end" || line.starts_with("end ") || line.starts_with("end#")) && depth.pop() == Some(true) {
|
||||
namespaces.pop();
|
||||
}
|
||||
}
|
||||
tasks
|
||||
}
|
||||
|
||||
/// `bundle exec <tool>` when the project has a Gemfile, else the bare tool.
|
||||
fn ruby_tool(root: &Path, tool: &str) -> (String, Vec<String>) {
|
||||
if root.join("Gemfile").is_file() {
|
||||
("bundle".into(), vec!["exec".into(), tool.into()])
|
||||
} else {
|
||||
(tool.into(), Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn ruby_config(
|
||||
id: String,
|
||||
name: String,
|
||||
kind: &str,
|
||||
(command, mut args): (String, Vec<String>),
|
||||
extra: &[&str],
|
||||
) -> RunConfig {
|
||||
args.extend(extra.iter().map(|a| (*a).to_owned()));
|
||||
let mut c = config(id, name, kind, &command, &[]);
|
||||
c.args = args;
|
||||
c
|
||||
}
|
||||
|
||||
fn uses_rspec(root: &Path) -> bool {
|
||||
root.join("spec").is_dir()
|
||||
|| root.join(".rspec").is_file()
|
||||
|| read(&root.join("Gemfile")).is_some_and(|g| g.contains("rspec"))
|
||||
}
|
||||
|
||||
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"));
|
||||
if !gemspec && !markers.iter().any(|m| root.join(m).is_file()) {
|
||||
return;
|
||||
}
|
||||
if root.join("bin/rails").is_file() {
|
||||
let mut c = ruby_config(
|
||||
"rails:server".into(),
|
||||
"rails server".into(),
|
||||
"ruby",
|
||||
("ruby".into(), Vec::new()),
|
||||
&["bin/rails", "server"],
|
||||
);
|
||||
c.extras.folder = Some("Rails".into());
|
||||
out.push(c);
|
||||
}
|
||||
if let Some(rakefile) = first_existing(root, &["Rakefile", "rakefile", "Rakefile.rb"])
|
||||
&& let Some(src) = read(&rakefile)
|
||||
{
|
||||
for task in rake_tasks(&src) {
|
||||
let mut c =
|
||||
ruby_config(format!("rake:{task}"), format!("rake {task}"), "rake", ruby_tool(root, "rake"), &[&task]);
|
||||
if task == "test" || task == "spec" || task.ends_with(":test") || task.ends_with(":spec") {
|
||||
c = c.test();
|
||||
}
|
||||
c.extras.folder = Some("Rake".into());
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
if uses_rspec(root) {
|
||||
out.push(ruby_config("rspec".into(), "rspec".into(), "rspec", ruby_tool(root, "rspec"), &[]).test());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- make / just
|
||||
|
||||
@@ -317,7 +317,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
|
||||
if matches!(config.kind.as_str(), "python" | "pytest") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
@@ -745,7 +745,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
|
||||
@@ -372,19 +372,13 @@ fn python_projects() {
|
||||
("manage.py", ""),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
// pytest stays ahead of `manage.py test`: the first test configuration is the default for context runs.
|
||||
assert_eq!(ids(&c), ["django:runserver", "python:module:mypkg", "pytest", "django:test"]);
|
||||
assert_eq!(ids(&c), ["django:runserver", "python:module:mypkg", "pytest"]);
|
||||
let pytest = find(&c, "pytest");
|
||||
assert_eq!(cmdline(pytest), "uv run pytest");
|
||||
assert!(pytest.is_test);
|
||||
assert_eq!(pytest.debug_adapter.as_deref(), Some("debugpy"));
|
||||
assert_eq!(cmdline(find(&c, "python:module:mypkg")), "uv run python -m mypkg");
|
||||
assert_eq!(cmdline(find(&c, "django:runserver")), "uv run python manage.py runserver");
|
||||
let django = find(&c, "django:test");
|
||||
assert_eq!(cmdline(django), "uv run python manage.py test");
|
||||
assert_eq!(django.kind, "django-test");
|
||||
assert!(django.is_test);
|
||||
assert_eq!(django.debug_adapter.as_deref(), Some("debugpy"));
|
||||
|
||||
let dir = project(&[("pytest.ini", "[pytest]\n"), ("poetry.lock", "")]);
|
||||
assert_eq!(cmdline(find(&detect(dir.path()), "pytest")), "poetry run pytest");
|
||||
@@ -404,7 +398,6 @@ fn python_virtualenv() {
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(cmdline(find(&c, "pytest")), ".venv/bin/pytest");
|
||||
assert_eq!(cmdline(find(&c, "django:runserver")), ".venv/bin/python manage.py runserver");
|
||||
assert_eq!(cmdline(find(&c, "django:test")), ".venv/bin/python manage.py test");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -728,69 +721,3 @@ fn cmake_profile_build_configures_only_without_a_cache() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_projects_list_rake_tasks_rspec_and_rails() {
|
||||
let rakefile = "\
|
||||
require 'rake/testtask'
|
||||
|
||||
desc \"Build it\"
|
||||
task :build do
|
||||
sh 'make'
|
||||
end
|
||||
task \"lint\" => [:build]
|
||||
task deploy: :build do |t|
|
||||
puts t
|
||||
end
|
||||
namespace :db do
|
||||
desc 'Migrate'
|
||||
task :migrate, [:version] do |t, args|
|
||||
puts args
|
||||
end
|
||||
namespace :schema do
|
||||
task :load
|
||||
end
|
||||
end
|
||||
Rake::TestTask.new do |t|
|
||||
t.libs << 'test'
|
||||
end
|
||||
task default: :build
|
||||
";
|
||||
let dir = project(&[
|
||||
("Gemfile", "source 'https://rubygems.org'\ngem 'rspec'\n"),
|
||||
("Rakefile", rakefile),
|
||||
("bin/rails", "#!/usr/bin/env ruby\n"),
|
||||
("spec/a_spec.rb", ""),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(
|
||||
ids(&c),
|
||||
[
|
||||
"rails:server",
|
||||
"rake:build",
|
||||
"rake:lint",
|
||||
"rake:deploy",
|
||||
"rake:db:migrate",
|
||||
"rake:db:schema:load",
|
||||
"rake:test",
|
||||
"rake:default",
|
||||
"rspec"
|
||||
]
|
||||
);
|
||||
assert_eq!(cmdline(find(&c, "rails:server")), "ruby bin/rails server");
|
||||
assert_eq!(cmdline(find(&c, "rake:db:migrate")), "bundle exec rake db:migrate");
|
||||
assert_eq!(find(&c, "rake:db:migrate").kind, "rake");
|
||||
assert!(find(&c, "rake:test").is_test);
|
||||
assert_eq!(cmdline(find(&c, "rspec")), "bundle exec rspec");
|
||||
assert!(find(&c, "rspec").is_test);
|
||||
assert_eq!(find(&c, "rake:build").extras.folder.as_deref(), Some("Rake"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_without_bundler_runs_bare_tools() {
|
||||
let dir = project(&[("Rakefile", "task :test\n")]);
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(ids(&c), ["rake:test"]);
|
||||
assert_eq!(cmdline(&c[0]), "rake test");
|
||||
assert!(detect(project(&[("a.rb", "puts 1\n")]).path()).is_empty());
|
||||
}
|
||||
@@ -447,7 +447,7 @@ fn build_tools_get_the_console_encoding_for_every_jvm() {
|
||||
|
||||
#[test]
|
||||
fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
for (kind, source_dir) in [("python", ""), ("pytest", "src"), ("django-test", "")] {
|
||||
for (kind, source_dir) in [("python", ""), ("pytest", "src")] {
|
||||
let h = harness();
|
||||
let root = h.root.path();
|
||||
let source = root.join(source_dir);
|
||||
@@ -465,11 +465,6 @@ fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
let mut config = cfg("python-imports", "python3", &["app/main.py"]);
|
||||
config.kind = kind.into();
|
||||
config.extras.env_files = vec![".env".into()];
|
||||
// Unbuffered, so output printed by a test stays next to its result line.
|
||||
assert_eq!(
|
||||
ide_run::resolved_env(root, &config).unwrap().get("PYTHONUNBUFFERED").map(String::as_str),
|
||||
Some("1")
|
||||
);
|
||||
let options = StartOptions { python_paths: vec![root.to_owned(), source], ..Default::default() };
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
|
||||
@@ -36,12 +36,6 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
.or_else(|| pinned::pinned_python(root))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
setting_path(root, &s.languages.ruby.interpreter).or_else(|| crate::ruby::project_ruby(root))
|
||||
}
|
||||
|
||||
/// The configured `node` executable's directory, else the `bin` of the Node.js the
|
||||
/// project pins for mise / asdf.
|
||||
pub(crate) fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
@@ -210,7 +204,7 @@ pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
const PYTHON_SERVERS: [&str; 7] = ["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff"];
|
||||
const PYTHON_SERVERS: [&str; 6] = ["basedpyright", "pyright", "ty", "pylsp", "jedi-language-server", "ruff"];
|
||||
|
||||
fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
@@ -630,16 +624,15 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
let jdk = project_jdk(root, s);
|
||||
let mvn = maven_command(root, s);
|
||||
let mvn_options = maven_options(root, s);
|
||||
let ruby = ruby_interpreter(root, s);
|
||||
|
||||
for c in configs.iter_mut() {
|
||||
resolve_run_command(c, root, s);
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
match c.kind.as_str() {
|
||||
"python" | "pytest" | "django-test" => {
|
||||
"python" | "pytest" => {
|
||||
if let Some(py) = &explicit_python {
|
||||
let runner = PY_RUNNERS.contains(&c.command.as_str());
|
||||
if (c.kind == "python" || c.kind == "django-test") && (runner || is_python_command(&c.command)) {
|
||||
if c.kind == "python" && (runner || is_python_command(&c.command)) {
|
||||
if runner && c.args.first().map(String::as_str) == Some("run") {
|
||||
// `uv run python …` → `<interpreter> …`
|
||||
let skip = if c.args.get(1).is_some_and(|a| is_python_command(a)) { 2 } else { 1 };
|
||||
@@ -716,26 +709,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
c.env.entry(key).or_insert(value);
|
||||
}
|
||||
}
|
||||
"ruby" | "rake" | "rspec" => {
|
||||
if let Some(ruby) = &ruby
|
||||
&& let Some(bin) = crate::ruby::bin_dir_of(ruby)
|
||||
{
|
||||
// `ruby`, `bundle`, `rake`, `rspec` of the chosen interpreter when installed
|
||||
// alongside it; the rest (a project `bin/rspec` binstub) stays as is.
|
||||
let name = Path::new(&c.command).file_name().map(|n| n.to_string_lossy().into_owned());
|
||||
if let Some(name) = name
|
||||
&& matches!(name.as_str(), "ruby" | "bundle" | "rake" | "rspec" | "gem" | "irb")
|
||||
&& !c.command.contains('/')
|
||||
&& !c.command.contains('\\')
|
||||
{
|
||||
let exe = bin.join(exe(&name));
|
||||
if exe.is_file() {
|
||||
c.command = exe.to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
path_dirs.push(bin);
|
||||
}
|
||||
}
|
||||
"maven" | "tomcat" => {
|
||||
if let Some(jdk) = &jdk {
|
||||
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
|
||||
|
||||
@@ -21,7 +21,6 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::TypeScript => typescript(root),
|
||||
SdkKind::Jdk => jdk(),
|
||||
SdkKind::Maven => maven(),
|
||||
SdkKind::Ruby => crate::ruby::detect(root),
|
||||
};
|
||||
if let Some(root) = root {
|
||||
pinned_first(&mut out, kind, root);
|
||||
@@ -36,7 +35,6 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
|
||||
SdkKind::Go => Some(Tool::Go),
|
||||
SdkKind::Jdk => Some(Tool::Java),
|
||||
SdkKind::Maven => Some(Tool::Maven),
|
||||
SdkKind::Ruby => Some(Tool::Ruby),
|
||||
SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,
|
||||
}
|
||||
}
|
||||
@@ -52,7 +50,7 @@ fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
|
||||
}
|
||||
|
||||
/// Runs `f` over `items` on scoped threads (version queries spawn processes).
|
||||
pub(crate) fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Option<R> + Sync) -> Vec<R> {
|
||||
fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Option<R> + Sync) -> Vec<R> {
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = items.iter().map(|item| s.spawn(|| f(item))).collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok().flatten()).collect()
|
||||
@@ -229,7 +227,7 @@ fn pyvenv_version(python: &Path) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn subdirs(dir: &Path) -> Vec<PathBuf> {
|
||||
fn subdirs(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> =
|
||||
std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
|
||||
out.sort();
|
||||
|
||||
@@ -1173,7 +1173,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.2.1.jar");
|
||||
let extension = data_dir.join("java-usages-1.1.1.jar");
|
||||
let bytes = include_bytes!("../../../plugins/java-usages/openidea-java-usages.jar");
|
||||
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
|
||||
@@ -19,7 +19,6 @@ pub mod lombok;
|
||||
mod npm;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod vue;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -43,7 +42,6 @@ pub enum SdkKind {
|
||||
Jdk,
|
||||
/// Maven homes.
|
||||
Maven,
|
||||
Ruby,
|
||||
}
|
||||
|
||||
/// One installed interpreter / toolchain.
|
||||
|
||||
@@ -54,7 +54,6 @@ const JAVA_MANIFESTS: &[&str] =
|
||||
const NODE_MANIFESTS: &[&str] = &["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb"];
|
||||
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
|
||||
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
|
||||
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
|
||||
|
||||
/// A Maven / Gradle dependency of the project, from the build model.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -71,7 +70,7 @@ pub struct BuildDependency {
|
||||
/// `dependencies` (from the build model) are listed when their jars are in the local repositories.
|
||||
pub fn project_libraries(root: &Path, settings: &Settings, dependencies: &[BuildDependency]) -> Vec<LibraryGroup> {
|
||||
type Detect = fn(&Path, &Settings) -> Vec<LibraryGroup>;
|
||||
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, rust_groups, go_groups, ruby_groups];
|
||||
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, rust_groups, go_groups];
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = detectors.iter().map(|d| s.spawn(move || d(root, settings))).collect();
|
||||
let deps = s.spawn(|| dependency_groups(root, settings, dependencies));
|
||||
@@ -194,24 +193,6 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ ruby
|
||||
|
||||
fn ruby_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
|
||||
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(ruby) = crate::apply::ruby_interpreter(root, s) else { return Vec::new() };
|
||||
cached(root, "ruby", ruby.display().to_string(), &files, || {
|
||||
let name = crate::ruby::ruby_sdk(&ruby, "system").map(|s| s.name).unwrap_or_else(|| "Ruby".into());
|
||||
let (stdlib, gems) = crate::ruby::library_roots(&ruby, Some(root));
|
||||
let mut out = Vec::new();
|
||||
out.extend(group(name, "ruby", named_roots(stdlib)));
|
||||
out.extend(group("Gems", "gems", named_roots(gems)));
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ jdk
|
||||
|
||||
fn jdk_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
//! Ruby interpreters: the ones a version manager installed (rbenv, rvm, chruby,
|
||||
//! mise, asdf), Homebrew's, and the ones on `PATH`; the project's `.ruby-version`;
|
||||
//! and the interpreter's standard library and Bundler gems for External Libraries.
|
||||
|
||||
use crate::discover::{par_map, subdirs};
|
||||
use crate::exec::{executables_in, query, query_in, search_path};
|
||||
use crate::{Sdk, exe, home_dir, pinned};
|
||||
use ide_core::version_managers::{self, Tool};
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
const VERSION_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
fn var_path(key: &str) -> Option<PathBuf> {
|
||||
ide_core::process::host_var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// Where version managers keep one directory per Ruby, with the manager's name.
|
||||
fn manager_roots() -> Vec<(PathBuf, &'static str)> {
|
||||
let mut out = Vec::new();
|
||||
let Some(home) = home_dir() else { return out };
|
||||
out.push((var_path("RBENV_ROOT").unwrap_or_else(|| home.join(".rbenv")).join("versions"), "rbenv"));
|
||||
out.push((var_path("rvm_path").unwrap_or_else(|| home.join(".rvm")).join("rubies"), "rvm"));
|
||||
out.push((PathBuf::from("/usr/local/rvm/rubies"), "rvm"));
|
||||
out.push((home.join(".rubies"), "chruby"));
|
||||
out.push((PathBuf::from("/opt/rubies"), "chruby"));
|
||||
out
|
||||
}
|
||||
|
||||
/// `bin/ruby` of a Ruby install directory.
|
||||
pub(crate) fn ruby_in_install(dir: &Path) -> Option<PathBuf> {
|
||||
let p = dir.join("bin").join(exe("ruby"));
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
|
||||
/// Installed Rubies: version-manager installs, Homebrew, then `PATH` (shims excluded).
|
||||
pub(crate) fn detect(root: Option<&Path>) -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
for (dir, manager) in manager_roots() {
|
||||
found.extend(subdirs(&dir).into_iter().filter_map(|v| ruby_in_install(&v)).map(|p| (p, manager)));
|
||||
}
|
||||
for (dir, manager) in version_managers::installs(Tool::Ruby) {
|
||||
found.extend(ruby_in_install(&dir).map(|p| (p, manager)));
|
||||
}
|
||||
for brew in ["/opt/homebrew/opt/ruby", "/usr/local/opt/ruby", "/home/linuxbrew/.linuxbrew/opt/ruby"] {
|
||||
found.extend(ruby_in_install(Path::new(brew)).map(|p| (p, "homebrew")));
|
||||
}
|
||||
let dirs = std::env::split_paths(&search_path())
|
||||
.filter(|d| !is_shims_dir(d) && !version_managers::is_shims_dir(d))
|
||||
.collect::<Vec<_>>();
|
||||
found.extend(executables_in("ruby", dirs.into_iter()).into_iter().map(|p| (p, "system")));
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
let candidates: Vec<(PathBuf, &'static str)> = found
|
||||
.into_iter()
|
||||
.filter(|(p, _)| p.is_file() && seen.insert(p.canonicalize().unwrap_or_else(|_| p.clone())))
|
||||
.collect();
|
||||
let mut out = par_map(&candidates, |(path, source)| ruby_sdk(path, source));
|
||||
if let Some(root) = root
|
||||
&& let Some(pinned) = pinned_ruby_version(root)
|
||||
{
|
||||
// The `.ruby-version` install first, like the project virtualenv for Python.
|
||||
if let Some(i) = out.iter().position(|s| version_matches(s.version.as_deref().unwrap_or(""), &pinned)) {
|
||||
let sdk = out.remove(i);
|
||||
out.insert(0, sdk);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// rbenv's and rvm's shim directories, which only forward to an install.
|
||||
fn is_shims_dir(dir: &Path) -> bool {
|
||||
dir.ends_with(".rbenv/shims") || dir.ends_with(".rvm/bin")
|
||||
}
|
||||
|
||||
/// `ruby 3.3.1 (2024-04-23 revision …) [arm64-darwin23]` → `3.3.1`.
|
||||
pub(crate) fn parse_version(out: &str) -> Option<String> {
|
||||
out.strip_prefix("ruby ")?
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.map(|v| v.trim_end_matches(|c: char| c.is_ascii_alphabetic() || c == '-').to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn ruby_sdk(path: &Path, source: &str) -> Option<Sdk> {
|
||||
let version = query(path, &["--version"], VERSION_TIMEOUT).and_then(|v| parse_version(&v))?;
|
||||
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
|
||||
let name = match source {
|
||||
"system" => format!("Ruby {short}"),
|
||||
tool => format!("Ruby {short} ({tool})"),
|
||||
};
|
||||
Some(Sdk {
|
||||
path: path.into(),
|
||||
name,
|
||||
version: Some(version),
|
||||
source: source.to_owned(),
|
||||
home: path.parent().and_then(Path::parent).map(Path::to_path_buf).map(Into::into),
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The version `.ruby-version` pins (rbenv / rvm / chruby read it; `ruby-3.3.1` → `3.3.1`),
|
||||
/// from `root` up, else the mise / asdf pin.
|
||||
pub fn pinned_ruby_version(root: &Path) -> Option<String> {
|
||||
let from_file = root.ancestors().find_map(|dir| {
|
||||
let text = std::fs::read_to_string(dir.join(".ruby-version")).ok()?;
|
||||
let v = text.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#'))?;
|
||||
Some(v.strip_prefix("ruby-").unwrap_or(v).to_owned())
|
||||
});
|
||||
from_file.or_else(|| pinned::pinned_version(root, Tool::Ruby))
|
||||
}
|
||||
|
||||
/// Whether `version` (`3.3.1`) satisfies a pin (`3.3.1`, `3.3`, `3`).
|
||||
pub(crate) fn version_matches(version: &str, pin: &str) -> bool {
|
||||
version == pin || version.strip_prefix(pin).is_some_and(|rest| rest.starts_with('.'))
|
||||
}
|
||||
|
||||
/// The Ruby for `root` without an explicit setting: the install matching
|
||||
/// `.ruby-version` (version managers, then mise / asdf), else `ruby` on PATH.
|
||||
pub fn project_ruby(root: &Path) -> Option<PathBuf> {
|
||||
if let Some(pin) = pinned_ruby_version(root) {
|
||||
let install = manager_roots()
|
||||
.into_iter()
|
||||
.flat_map(|(dir, _)| subdirs(&dir))
|
||||
.chain(version_managers::installs(Tool::Ruby).into_iter().map(|(d, _)| d))
|
||||
.find(|dir| {
|
||||
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
version_matches(name.strip_prefix("ruby-").unwrap_or(&name), &pin)
|
||||
});
|
||||
if let Some(ruby) = install.and_then(|d| ruby_in_install(&d)) {
|
||||
return Some(ruby);
|
||||
}
|
||||
}
|
||||
crate::exec::which("ruby")
|
||||
}
|
||||
|
||||
/// `bin` directory of `ruby` and the gems it was installed with (`gem` and `bundle` next to it).
|
||||
pub fn bin_dir_of(ruby: &Path) -> Option<PathBuf> {
|
||||
ruby.parent().map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
type NamedRoots = Vec<(String, PathBuf)>;
|
||||
|
||||
/// Standard-library / site directories (`ruby/3.3.0`) and the gems Bundler resolves
|
||||
/// for `root` (`rails-7.1.3`), each as `(name, path)`.
|
||||
pub fn library_roots(ruby: &Path, root: Option<&Path>) -> (NamedRoots, NamedRoots) {
|
||||
const PATHS: &str = "require 'rbconfig'; puts RbConfig::CONFIG['rubylibdir'], RbConfig::CONFIG['sitelibdir'], RbConfig::CONFIG['vendorlibdir']";
|
||||
let mut stdlib = Vec::new();
|
||||
let mut gems = Vec::new();
|
||||
let file_name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
if let Some(text) = query(ruby, &["-e", PATHS], QUERY_TIMEOUT) {
|
||||
for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
let path = PathBuf::from(line);
|
||||
if path.is_dir() && !stdlib.iter().any(|(_, p)| *p == path) {
|
||||
let parent = path.parent().map(file_name).unwrap_or_default();
|
||||
stdlib.push((format!("{parent}/{}", file_name(&path)), path));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(root) = root.filter(|r| r.join("Gemfile").is_file()) {
|
||||
let bin = bin_dir_of(ruby);
|
||||
let bundle = bin.as_ref().map(|b| b.join(exe("bundle"))).filter(|b| b.is_file());
|
||||
let path = bin.as_ref().map(|b| crate::exec::path_with(&[b.as_path()])).unwrap_or_default();
|
||||
let env: &[(&str, &str)] = &[("PATH", &path)];
|
||||
let text = match &bundle {
|
||||
Some(b) => query_in(b, &["list", "--paths"], Some(root), env, QUERY_TIMEOUT),
|
||||
None => query_in(ruby, &["-S", "bundle", "list", "--paths"], Some(root), env, QUERY_TIMEOUT),
|
||||
};
|
||||
for line in text.unwrap_or_default().lines().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
let path = PathBuf::from(line);
|
||||
if path.is_dir() && path != root {
|
||||
gems.push((file_name(&path), path));
|
||||
}
|
||||
}
|
||||
}
|
||||
(stdlib, gems)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn includes_bundled_gems_installed_inside_the_project() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
let gem = root.join("vendor/bundle/ruby/4.0.0/gems/rake-13.4.0");
|
||||
let external = dir.path().join("gems/rspec-3.13.2");
|
||||
let bin = dir.path().join("bin");
|
||||
for path in [&gem, &external, &bin] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("Gemfile"), "gem 'rake'\ngem 'rspec'\n").unwrap();
|
||||
for (name, output) in [
|
||||
("ruby", String::new()),
|
||||
("bundle", format!("{}\n{}\n{}", gem.display(), external.display(), root.display())),
|
||||
] {
|
||||
let path = bin.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\nprintf '%s\\n' '{output}'\n")).unwrap();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
let (_, gems) = library_roots(&bin.join("ruby"), Some(&root));
|
||||
assert_eq!(gems, vec![("rake-13.4.0".into(), gem), ("rspec-3.13.2".into(), external)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_ruby_version_output() {
|
||||
assert_eq!(
|
||||
parse_version("ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]").as_deref(),
|
||||
Some("3.3.1")
|
||||
);
|
||||
assert_eq!(parse_version("ruby 3.4.0dev (2024-10-01) +PRISM [x86_64-linux]").as_deref(), Some("3.4.0"));
|
||||
assert_eq!(parse_version("jruby 9.4.5.0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_pins_match_prefixes() {
|
||||
assert!(version_matches("3.3.1", "3.3.1"));
|
||||
assert!(version_matches("3.3.1", "3.3"));
|
||||
assert!(!version_matches("3.31.1", "3.3"));
|
||||
assert!(!version_matches("3.3.1", "3.3.10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_version_file_wins_over_managers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let project = dir.path().join("app/sub");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::write(dir.path().join("app/.ruby-version"), "ruby-3.2.2\n").unwrap();
|
||||
assert_eq!(pinned_ruby_version(&project).as_deref(), Some("3.2.2"));
|
||||
}
|
||||
}
|
||||
@@ -152,8 +152,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
run("pytest", "uv", &["run", "pytest", "-x"]),
|
||||
run("npm", "npm", &["run", "dev"]),
|
||||
run("shell", "python3", &["x.py"]),
|
||||
run("django-test", "uv", &["run", "python", "manage.py", "test"]),
|
||||
run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]),
|
||||
];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].command, "/opt/py/bin/python3");
|
||||
@@ -163,11 +161,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
assert_eq!(configs[2].args, ["-m", "pytest", "-x"]);
|
||||
assert_eq!(configs[3].command, "pnpm");
|
||||
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
|
||||
// Django tests run on the selected interpreter, like `manage.py runserver`.
|
||||
assert_eq!(configs[5].command, "/opt/py/bin/python3");
|
||||
assert_eq!(configs[5].args, ["manage.py", "test"]);
|
||||
assert_eq!(configs[6].command, "/opt/py/bin/python3");
|
||||
assert_eq!(configs[6].args, ["manage.py", "test", "polls"]);
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path) {
|
||||
@@ -261,10 +254,10 @@ fn language_server_settings_disable_add_and_override() {
|
||||
let mut s = Settings::default();
|
||||
s.language_servers.insert("pylsp".into(), LanguageServerSettings { enabled: false, ..Default::default() });
|
||||
s.language_servers.insert(
|
||||
"pylyzer".into(),
|
||||
"ruff".into(),
|
||||
LanguageServerSettings {
|
||||
command: "pylyzer".into(),
|
||||
args: Some(vec!["--server".into()]),
|
||||
command: "ruff".into(),
|
||||
args: Some(vec!["server".into()]),
|
||||
languages: vec!["python".into()],
|
||||
root_markers: vec!["pyproject.toml".into()],
|
||||
..Default::default()
|
||||
@@ -272,42 +265,17 @@ fn language_server_settings_disable_add_and_override() {
|
||||
);
|
||||
let defined = [server("basedpyright"), server("pylsp")];
|
||||
let names = |v: Vec<LanguageServerConfig>| v.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "pylyzer"]);
|
||||
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "ruff"]);
|
||||
assert_eq!(names(language_servers("rust", &[server("rust-analyzer")], &s)), ["rust-analyzer"]);
|
||||
|
||||
// Listed with the tools even while disabled.
|
||||
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
with_custom_servers(&mut langs, &s);
|
||||
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
|
||||
let mut pylyzer = python.language_servers.iter().find(|c| c.name == "pylyzer").unwrap().clone();
|
||||
assert_eq!(pylyzer.root_markers, ["pyproject.toml"]);
|
||||
server_launch_overrides(&mut pylyzer, &s);
|
||||
assert_eq!((pylyzer.command.as_str(), pylyzer.args.as_slice()), ("pylyzer", &["--server".to_string()][..]));
|
||||
|
||||
// A hand-defined server named like a built-in one only overrides how it
|
||||
// launches: languages and root markers stay the built-in definition's.
|
||||
s.language_servers.insert(
|
||||
"ruff".into(),
|
||||
LanguageServerSettings {
|
||||
command: "/opt/ruff".into(),
|
||||
args: Some(vec!["server".into(), "--preview".into()]),
|
||||
languages: vec!["python".into()],
|
||||
root_markers: vec!["pyproject.toml".into()],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
with_custom_servers(&mut langs, &s);
|
||||
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
|
||||
assert_eq!(python.language_servers.iter().filter(|c| c.name == "ruff").count(), 1);
|
||||
let mut ruff = python.language_servers.iter().find(|c| c.name == "ruff").unwrap().clone();
|
||||
assert_eq!(ruff.root_markers, ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"]);
|
||||
assert!(ruff.require_root_marker);
|
||||
assert_eq!(ruff.root_markers, ["pyproject.toml"]);
|
||||
server_launch_overrides(&mut ruff, &s);
|
||||
assert_eq!(
|
||||
(ruff.command.as_str(), ruff.args.as_slice()),
|
||||
("/opt/ruff", &["server".to_string(), "--preview".to_string()][..])
|
||||
);
|
||||
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", &["server".to_string()][..]));
|
||||
|
||||
s.language_servers.insert(
|
||||
"rust-analyzer".into(),
|
||||
|
||||
@@ -159,7 +159,7 @@ impl StructureService {
|
||||
let runnable = body.is_some_and(|b| {
|
||||
members(*b).into_iter().any(|n| {
|
||||
if !matches!(n.kind(), "method_declaration" | "function_declaration")
|
||||
|| n.child_by_field_name("name").is_none_or(|id| text(id, snap.text) != "main")
|
||||
|| !n.child_by_field_name("name").is_some_and(|id| text(id, snap.text) == "main")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ zip.workspace = true
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
@@ -540,15 +540,6 @@ impl Tools {
|
||||
if managed || self.method_missing(spec.method).is_some() { fallback } else { spec.method }
|
||||
}
|
||||
|
||||
/// [`Method::label`], naming the installer that will actually run: a virtualenv is
|
||||
/// made with uv when it is on `PATH` (see `install_venv`).
|
||||
fn method_label(&self, method: Method) -> &'static str {
|
||||
match method {
|
||||
Method::PipVenv { .. } if self.which("uv").is_some() => "uv (virtualenv)",
|
||||
m => m.label(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Requirement check for installing `spec` right now.
|
||||
fn unavailable_reason(&self, spec: &ToolSpec) -> Option<String> {
|
||||
self.method_missing(self.install_method(spec))
|
||||
@@ -633,7 +624,7 @@ impl Tools {
|
||||
status,
|
||||
path: path.map(Into::into),
|
||||
version,
|
||||
install_method: Some(self.method_label(self.install_method(spec)).to_string()),
|
||||
install_method: Some(self.install_method(spec).label().to_string()),
|
||||
can_install: unavailable_reason.is_none() && !bundled,
|
||||
unavailable_reason,
|
||||
can_uninstall,
|
||||
@@ -805,9 +796,7 @@ impl Tools {
|
||||
let result = (|| {
|
||||
std::fs::create_dir_all(&self.root)?;
|
||||
let method = self.install_method(spec);
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("Installing {} via {}…", spec.display, self.method_label(method)),
|
||||
});
|
||||
emit(InstallEvent::Line { text: format!("Installing {} via {}…", spec.display, method.label()) });
|
||||
match method {
|
||||
Method::Bundled { .. } => {
|
||||
bundled::install(&self.root, spec)?;
|
||||
|
||||
@@ -4,16 +4,48 @@
|
||||
use crate::InstallEvent;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::process::{kill_tree, own_group};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub type Emit<'a> = &'a dyn Fn(InstallEvent);
|
||||
|
||||
/// Starts the child as the leader of its own process group, so [`kill`] reaches what it
|
||||
/// starts in turn (`npm` → `node`, `go install` → the compiler, `pip` → build backends).
|
||||
fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started.
|
||||
fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
if let Ok(pid) = i32::try_from(child.id()) {
|
||||
// SAFETY: plain syscall; the child leads its own process group (`own_group`) and is not reaped yet.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut taskkill = Command::new("taskkill");
|
||||
ide_core::process::prepare(&mut taskkill)
|
||||
.args(["/T", "/F", "/PID", &child.id().to_string()])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let _ = taskkill.status();
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn describe(cmd: &Command) -> String {
|
||||
let mut s = Path::new(cmd.get_program()).file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
for a in cmd.get_args() {
|
||||
@@ -68,7 +100,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
|
||||
let mut output = String::new();
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
@@ -112,7 +144,7 @@ pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)>
|
||||
Ok(Some(s)) => break s,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(15)),
|
||||
_ => {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -224,7 +256,7 @@ impl Http {
|
||||
});
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match child.try_wait()? {
|
||||
@@ -276,7 +308,7 @@ impl Http {
|
||||
let mut last_bytes = 0;
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
let _ = std::fs::remove_file(dest);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -381,7 +413,7 @@ pub(crate) fn run_input(
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
kill_tree(&mut child);
|
||||
kill(&mut child);
|
||||
}
|
||||
result?;
|
||||
let output = output.unwrap()?;
|
||||
|
||||
@@ -233,28 +233,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://docs.astral.sh/ty/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "pyrefly",
|
||||
display: "Pyrefly (Python)",
|
||||
kind: LanguageServer,
|
||||
commands: &["pyrefly"],
|
||||
method: Method::PipVenv { package: "pyrefly" },
|
||||
fallback: None,
|
||||
version: ver("pyrefly"),
|
||||
homepage: "https://pyrefly.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "ruff",
|
||||
display: "Ruff",
|
||||
kind: LanguageServer,
|
||||
commands: &["ruff"],
|
||||
method: Method::PipVenv { package: "ruff" },
|
||||
fallback: None,
|
||||
version: ver("ruff"),
|
||||
homepage: "https://docs.astral.sh/ruff/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-language-server",
|
||||
display: "Bash Language Server",
|
||||
|
||||
@@ -130,11 +130,6 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert_eq!(ty.command, "ty");
|
||||
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
|
||||
assert!(ty.languages.iter().any(|language| language == "Python"));
|
||||
let pyrefly = find(&list, "pyrefly");
|
||||
assert_eq!(pyrefly.status, ToolStatus::Missing);
|
||||
assert_eq!(pyrefly.command, "pyrefly");
|
||||
assert_eq!(pyrefly.install_method.as_deref(), Some("pip (virtualenv)"));
|
||||
assert!(pyrefly.languages.iter().any(|language| language == "Python"));
|
||||
let angular = find(&list, "angular-language-server");
|
||||
assert_eq!(angular.command, "ngserver");
|
||||
assert_eq!(angular.install_method.as_deref(), Some("npm"));
|
||||
@@ -155,32 +150,16 @@ fn everything_missing_on_an_empty_system() {
|
||||
fn interchangeable_servers_list_their_alternatives() {
|
||||
let env = Env::new();
|
||||
let list = env.tools().list(&langs());
|
||||
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
|
||||
let python = ["basedpyright", "pyright", "ty"];
|
||||
for name in python {
|
||||
assert_eq!(find(&list, name).alternatives, python);
|
||||
}
|
||||
assert_eq!(find(&list, "vtsls").alternatives, ["vtsls", "typescript-language-server"]);
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
assert!(find(&list, "rust-analyzer").alternatives.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn python_servers_name_uv_when_it_makes_the_virtualenv() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "uv", "exit 0");
|
||||
let list = env.tools().list(&langs());
|
||||
for name in ["basedpyright", "ty", "ruff"] {
|
||||
let tool = find(&list, name);
|
||||
assert_eq!(tool.install_method.as_deref(), Some("uv (virtualenv)"), "{name}");
|
||||
assert!(tool.can_install, "{name}: uv alone is enough");
|
||||
}
|
||||
// debugpy's private copy is always made by `python -m pip`.
|
||||
assert_eq!(find(&list, "debugpy").install_method.as_deref(), Some("pip (private copy)"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn detects_tools_on_path_with_versions() {
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
//! Thin wrapper around the `git` executable used for every mutating operation.
|
||||
|
||||
use ide_core::process::{own_group, terminate_tree};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled git's process group (remote helpers, `ssh`, credential helpers) gets
|
||||
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
/// Explicit git executable from Settings › Version Control › Git (`None` = auto-detect).
|
||||
static CONFIGURED: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
|
||||
|
||||
@@ -366,7 +361,11 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
|
||||
}
|
||||
let mut cmd = command(root)?;
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
own_group(&mut cmd);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
let capture = |mut pipe: Box<dyn Read + Send>| {
|
||||
@@ -379,7 +378,8 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
|
||||
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
let _ = stdout.join();
|
||||
let _ = stderr.join();
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -504,7 +504,11 @@ pub(crate) fn run_streaming_env(
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
own_group(&mut cmd);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
tracing::debug!(?args, "git (streaming)");
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
@@ -525,7 +529,8 @@ pub(crate) fn run_streaming_env(
|
||||
let mut open = readers.len();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
for r in readers {
|
||||
let _ = r.join();
|
||||
}
|
||||
@@ -554,7 +559,8 @@ pub(crate) fn run_streaming_env(
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
kill(&mut child);
|
||||
let _ = child.wait();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -638,6 +644,22 @@ fn spawn_reader(
|
||||
})
|
||||
}
|
||||
|
||||
fn kill(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as libc::pid_t;
|
||||
// SAFETY: plain syscall; the child was spawned as leader of its own process group.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGTERM);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod command_session_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -297,9 +297,6 @@ pub struct ShelvedChangeList {
|
||||
pub time_ms: f64,
|
||||
/// Branch checked out when the changes were shelved.
|
||||
pub branch: Option<String>,
|
||||
/// Repository owning the patch; absent in legacy shelves.
|
||||
#[serde(default)]
|
||||
pub repo: Option<ide_core::IpcPath>,
|
||||
/// Repository-relative paths.
|
||||
pub files: Vec<ChangedFile>,
|
||||
}
|
||||
|
||||
@@ -19,8 +19,6 @@ struct Info {
|
||||
#[serde(default)]
|
||||
branch: Option<String>,
|
||||
files: Vec<crate::ChangedFile>,
|
||||
#[serde(default)]
|
||||
repo: Option<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
fn now_ms() -> f64 {
|
||||
@@ -69,7 +67,6 @@ pub fn list(shelf: &Path) -> IdeResult<Vec<ShelvedChangeList>> {
|
||||
name: id.clone(),
|
||||
time_ms: 0.0,
|
||||
branch: None,
|
||||
repo: None,
|
||||
files: std::fs::read_to_string(dir.join(PATCH))
|
||||
.map(|p| {
|
||||
crate::patch::parse_patch(&p)
|
||||
@@ -84,7 +81,6 @@ pub fn list(shelf: &Path) -> IdeResult<Vec<ShelvedChangeList>> {
|
||||
name: info.name,
|
||||
time_ms: info.time_ms,
|
||||
branch: info.branch,
|
||||
repo: info.repo,
|
||||
files: crate::patch::parse_patch(&std::fs::read_to_string(dir.join(PATCH))?)
|
||||
.into_iter()
|
||||
.map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path })
|
||||
@@ -100,11 +96,6 @@ pub fn patch_of(shelf: &Path, id: &str) -> IdeResult<String> {
|
||||
Ok(std::fs::read_to_string(entry_dir(shelf, id)?.join(PATCH))?)
|
||||
}
|
||||
|
||||
/// The repository captured when the shelf was made; legacy shelves used the primary repository.
|
||||
pub fn repository(shelf: &Path, id: &str) -> IdeResult<Option<PathBuf>> {
|
||||
Ok(read_info(&entry_dir(shelf, id)?).and_then(|info| info.repo).map(|repo| repo.into_path_buf()))
|
||||
}
|
||||
|
||||
pub fn delete(shelf: &Path, id: &str) -> IdeResult<()> {
|
||||
std::fs::remove_dir_all(entry_dir(shelf, id)?)?;
|
||||
Ok(())
|
||||
@@ -116,13 +107,8 @@ pub fn rename(shelf: &Path, id: &str, name: &str) -> IdeResult<()> {
|
||||
return Err(IdeError::invalid("name must not be empty"));
|
||||
}
|
||||
let dir = entry_dir(shelf, id)?;
|
||||
let mut info = read_info(&dir).unwrap_or(Info {
|
||||
name: String::new(),
|
||||
time_ms: now_ms(),
|
||||
branch: None,
|
||||
repo: None,
|
||||
files: vec![],
|
||||
});
|
||||
let mut info =
|
||||
read_info(&dir).unwrap_or(Info { name: String::new(), time_ms: now_ms(), branch: None, files: vec![] });
|
||||
info.name = name.to_string();
|
||||
std::fs::write(dir.join(INFO), serde_json::to_vec_pretty(&info).map_err(|e| IdeError::internal(e.to_string()))?)?;
|
||||
Ok(())
|
||||
@@ -148,13 +134,7 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) -
|
||||
}
|
||||
let dir = shelf.join(&id);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let info = Info {
|
||||
name: name.to_string(),
|
||||
time_ms: now_ms(),
|
||||
branch: r.branch_info()?.head,
|
||||
files: files.clone(),
|
||||
repo: Some(r.root().to_path_buf().into()),
|
||||
};
|
||||
let info = Info { name: name.to_string(), time_ms: now_ms(), branch: r.branch_info()?.head, files: files.clone() };
|
||||
let write = || -> IdeResult<()> {
|
||||
std::fs::write(dir.join(PATCH), patch.as_bytes())?;
|
||||
std::fs::write(
|
||||
@@ -168,7 +148,7 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) -
|
||||
return Err(e);
|
||||
}
|
||||
revert_files(r, &files)?;
|
||||
Ok(ShelvedChangeList { id, name: info.name, time_ms: info.time_ms, branch: info.branch, repo: info.repo, files })
|
||||
Ok(ShelvedChangeList { id, name: info.name, time_ms: info.time_ms, branch: info.branch, files })
|
||||
}
|
||||
|
||||
/// Restores `files` to HEAD in both index and working tree; files absent from HEAD are removed.
|
||||
@@ -338,7 +318,7 @@ pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult<Vec<ShelfDiffFi
|
||||
}
|
||||
|
||||
/// Import into the shelf without applying to the working tree.
|
||||
pub fn import_patch(shelf: &Path, name: &str, patch: &str, repo: Option<&Path>) -> IdeResult<()> {
|
||||
pub fn import_patch(shelf: &Path, name: &str, patch: &str) -> IdeResult<()> {
|
||||
let files = crate::patch::parse_patch(patch);
|
||||
if files.is_empty() || sections(patch).len() != files.len() {
|
||||
return Err(IdeError::invalid("no file changes found in the patch"));
|
||||
@@ -354,7 +334,6 @@ pub fn import_patch(shelf: &Path, name: &str, patch: &str, repo: Option<&Path>)
|
||||
name: name.to_string(),
|
||||
time_ms: now_ms(),
|
||||
branch: None,
|
||||
repo: repo.map(|r| r.to_path_buf().into()),
|
||||
files: files
|
||||
.into_iter()
|
||||
.map(|f| crate::ChangedFile { path: f.path, kind: f.kind, old_path: f.old_path })
|
||||
|
||||
@@ -614,7 +614,7 @@ fn shelf_diff_and_scoped_operations_preserve_siblings() {
|
||||
assert!(!shelf::list(&shelf).unwrap()[0].files.iter().any(|f| f.path == "b.txt"));
|
||||
shelf::delete_path(&shelf, &entry.id, Some(QUOTED)).unwrap();
|
||||
assert!(shelf::selected_patch(&shelf, &entry.id, Some("a.txt")).is_ok());
|
||||
shelf::import_patch(&shelf, "imported", &patch, None).unwrap();
|
||||
shelf::import_patch(&shelf, "imported", &patch).unwrap();
|
||||
assert_eq!(shelf::list(&shelf).unwrap().len(), 2);
|
||||
assert_eq!(fx.read("a.txt"), "local edits\n");
|
||||
}
|
||||
@@ -629,7 +629,7 @@ fn shelf_imported_rename_diff_and_last_file_delete() {
|
||||
fx.git(&["reset", "--hard", "HEAD"]);
|
||||
let repo = fx.repo();
|
||||
let shelf = fx._tmp.path().join("shelf");
|
||||
shelf::import_patch(&shelf, "rename", &patch, None).unwrap();
|
||||
shelf::import_patch(&shelf, "rename", &patch).unwrap();
|
||||
let id = &shelf::list(&shelf).unwrap()[0].id;
|
||||
let diffs = shelf::diff_files(&repo, &shelf, id).unwrap();
|
||||
assert_eq!(diffs.len(), 1);
|
||||
@@ -655,7 +655,7 @@ fn shelf_new_renames_keep_self_contained_sides_and_plain_imports_keep_scope() {
|
||||
assert_eq!(diffs.iter().find(|f| f.path == "old.txt").unwrap().before.as_deref(), Some("renamed content\n"));
|
||||
assert_eq!(diffs.iter().find(|f| f.path == "new.txt").unwrap().after.as_deref(), Some("renamed content\n"));
|
||||
let plain = "--- a/one.txt\n+++ b/one.txt\n@@ -1 +1 @@\n--- removed\n+++ added\n--- a/two.txt\n+++ b/two.txt\n@@ -1 +1 @@\n-old\n+new\n";
|
||||
shelf::import_patch(&shelf, "plain", plain, None).unwrap();
|
||||
shelf::import_patch(&shelf, "plain", plain).unwrap();
|
||||
let selected = shelf::selected_patch(&shelf, "plain", Some("one.txt")).unwrap();
|
||||
assert!(selected.contains("--- removed\n+++ added"));
|
||||
assert!(!selected.contains("two.txt"));
|
||||
|
||||
@@ -277,15 +277,6 @@ impl DirState {
|
||||
self.watch_tree(path, true, &mut discovered);
|
||||
}
|
||||
}
|
||||
// VCS metadata directories (`.git`, `.git/worktrees/<name>`) need
|
||||
// watches too: a worktree registered in the main gitdir writes its
|
||||
// entry below `.git/worktrees`, and the events in a gitdir created
|
||||
// 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.watch_tree(path, false, &mut discovered);
|
||||
}
|
||||
}
|
||||
for path in &batch.removed {
|
||||
self.unwatch_tree(path);
|
||||
}
|
||||
@@ -424,29 +415,15 @@ impl EventFilter {
|
||||
let idx = comps.iter().position(|c| *c == ".git")?;
|
||||
let rest = &comps[idx + 1..];
|
||||
Some(match rest {
|
||||
// `refs` and `worktrees` are directories whose creation is itself a
|
||||
// registration event (`git init`, the first `git worktree add`);
|
||||
// they must surface even though the depth below them is handled
|
||||
// separately.
|
||||
[one] => matches!(one.to_str(), Some("HEAD" | "index" | "packed-refs" | "refs" | "worktrees" | "info")),
|
||||
[first, ..] => {
|
||||
let metadata = *first == "refs"
|
||||
// Linked-worktree gitdirs: a worktree added or removed below
|
||||
// the project writes its HEAD here.
|
||||
|| *first == "worktrees";
|
||||
metadata && !rest.last().is_some_and(|l| l.to_string_lossy().ends_with(".lock"))
|
||||
}
|
||||
// The `.git` path itself: a linked worktree's `.git` is a plain
|
||||
// file (gitfile), and it is the only marker a new worktree writes
|
||||
// inside its own directory.
|
||||
[] => true,
|
||||
[one] => *one == "HEAD" || *one == "index" || *one == "packed-refs",
|
||||
[first, ..] => *first == "refs" && !rest.last().is_some_and(|l| l.to_string_lossy().ends_with(".lock")),
|
||||
[] => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a directory deserves its own watch in per-directory mode: not
|
||||
/// excluded or git-ignored; inside `.git` the directory itself, `refs/`
|
||||
/// and `worktrees/` (HEAD, index, refs and worktree metadata are what VCS
|
||||
/// refresh needs).
|
||||
/// excluded or git-ignored; inside `.git` only the directory itself and
|
||||
/// `refs/` (HEAD, index and refs are what VCS refresh needs).
|
||||
pub fn should_watch_dir(&self, dir: &Path) -> bool {
|
||||
let Ok(rel) = dir.strip_prefix(&self.root) else { return false };
|
||||
if rel.as_os_str().is_empty() {
|
||||
@@ -458,7 +435,6 @@ impl EventFilter {
|
||||
return match rest.as_slice() {
|
||||
[] => true,
|
||||
[first, ..] if *first == "refs" => true,
|
||||
[first, ..] if *first == "worktrees" => true,
|
||||
[only] => *only == "info",
|
||||
_ => false,
|
||||
};
|
||||
@@ -714,18 +690,7 @@ mod tests {
|
||||
assert_eq!(g(".git/refs/heads/main"), Some(true));
|
||||
assert_eq!(g(".git/refs/heads/main.lock"), Some(false));
|
||||
assert_eq!(g(".git/objects/aa/bb"), Some(false));
|
||||
// The `.git` path itself: a repo dir, or a linked worktree's gitfile.
|
||||
assert_eq!(g(".git"), Some(true));
|
||||
assert_eq!(g("wt/.git"), Some(true));
|
||||
// Linked-worktree gitdir metadata below the main repository.
|
||||
assert_eq!(g(".git/worktrees/wt/HEAD"), Some(true));
|
||||
assert_eq!(g(".git/worktrees/wt/index.lock"), Some(false));
|
||||
// The depth-1 directories themselves: `git init` or the first
|
||||
// `git worktree add` creates them in an already-watched gitdir.
|
||||
assert_eq!(g(".git/refs"), Some(true));
|
||||
assert_eq!(g(".git/worktrees"), Some(true));
|
||||
assert_eq!(g(".git/info"), Some(true));
|
||||
assert_eq!(g(".git/objects"), Some(false));
|
||||
assert_eq!(g(".git"), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -779,9 +744,6 @@ mod tests {
|
||||
assert!(!w("build") && w("src/build"));
|
||||
assert!(w(".git") && w(".git/refs") && w(".git/refs/heads") && w(".git/info"));
|
||||
assert!(!w(".git/objects") && !w(".git/objects/ab") && !w(".git/logs"));
|
||||
// Linked-worktree gitdirs are watched so worktrees added below the
|
||||
// project while it is open are discovered.
|
||||
assert!(w(".git/worktrees") && w(".git/worktrees/wt") && w(".git/worktrees/wt/rebase-merge"));
|
||||
assert!(!filter.should_watch_dir(Path::new("/elsewhere")));
|
||||
// Excludes are replaced in place (Watcher::set_excludes).
|
||||
*filter.excludes.write() = ExcludeMatcher::new(&["gen".into()]);
|
||||
@@ -899,51 +861,6 @@ mod tests {
|
||||
assert_eq!(batches.lock().len(), n, "no events after drop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_directory_mode_follows_worktree_registrations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for d in ["wt", ".git/refs/heads"] {
|
||||
std::fs::create_dir_all(root.join(d)).unwrap();
|
||||
}
|
||||
// The worktree's gitfile is written before any watch on the worktree
|
||||
// directory could register it — the same window a real
|
||||
// `git worktree add` runs into.
|
||||
std::fs::write(root.join("wt/.git"), "gitdir: ../.git/worktrees/wt\n").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::new(),
|
||||
sink,
|
||||
Box::new(move |b| batches.lock().push(b.clone())),
|
||||
WatchMode::PerDirectory,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
// Registering the worktree in the main gitdir surfaces as VCS metadata
|
||||
// (the deepest directory itself may be created before its parent gains
|
||||
// a watch, so `.git/worktrees` is the event that reliably fires)...
|
||||
std::fs::create_dir_all(root.join(".git/worktrees/wt")).unwrap();
|
||||
assert!(
|
||||
wait_for(&batches, |b| b.iter().any(|b| b.vcs.contains(&root.join(".git/worktrees")))),
|
||||
"{:?}",
|
||||
batches.lock()
|
||||
);
|
||||
// ...and the registered gitdir gains a watch, so writes inside it are
|
||||
// seen even though nothing reported the directory itself.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
std::fs::write(root.join(".git/worktrees/wt/HEAD"), "ref: refs/heads/topic\n").unwrap();
|
||||
assert!(
|
||||
wait_for(&batches, |b| b.iter().any(|b| b.vcs.contains(&root.join(".git/worktrees/wt/HEAD")))),
|
||||
"{:?}",
|
||||
batches.lock()
|
||||
);
|
||||
drop(watcher);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_mode_reports_the_roots_own_entries_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -173,12 +173,7 @@ async fn read_head(sock: &mut TcpStream) -> std::io::Result<Option<Request>> {
|
||||
}
|
||||
|
||||
enum Response {
|
||||
/// `path` is the resolved file to open; `mime` comes from the requested name.
|
||||
File {
|
||||
path: PathBuf,
|
||||
len: u64,
|
||||
mime: &'static str,
|
||||
},
|
||||
File { path: PathBuf, len: u64 },
|
||||
Redirect(String),
|
||||
Error(u16, &'static str),
|
||||
}
|
||||
@@ -196,9 +191,9 @@ async fn serve(mut sock: TcpStream, shared: &Shared, port: u16) -> std::io::Resu
|
||||
};
|
||||
let mut out = String::new();
|
||||
match &response {
|
||||
Response::File { len, mime, .. } => {
|
||||
Response::File { path, len } => {
|
||||
out.push_str("HTTP/1.1 200 OK\r\n");
|
||||
out.push_str(&format!("Content-Type: {mime}\r\nContent-Length: {len}\r\n"));
|
||||
out.push_str(&format!("Content-Type: {}\r\nContent-Length: {len}\r\n", content_type(path)));
|
||||
}
|
||||
Response::Redirect(to) => {
|
||||
out.push_str(&format!("HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\n"));
|
||||
@@ -238,9 +233,7 @@ async fn resolve(shared: &Shared, target: &str) -> Response {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
let Some(key) = segments.next().and_then(dec) else { return NOT_FOUND };
|
||||
let Some(root) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
|
||||
let Ok(real_root) = tokio::fs::canonicalize(&root).await else { return NOT_FOUND };
|
||||
let mut file = root;
|
||||
let Some(mut file) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
|
||||
let mut trailing_slash = true;
|
||||
for seg in segments {
|
||||
trailing_slash = seg.is_empty();
|
||||
@@ -252,29 +245,19 @@ async fn resolve(shared: &Shared, target: &str) -> Response {
|
||||
_ => return NOT_FOUND,
|
||||
}
|
||||
}
|
||||
let Some(real) = confined(&real_root, &file).await else { return NOT_FOUND };
|
||||
let Ok(meta) = tokio::fs::metadata(&real).await else { return NOT_FOUND };
|
||||
let Ok(meta) = tokio::fs::metadata(&file).await else { return NOT_FOUND };
|
||||
if meta.is_dir() {
|
||||
// Relative URLs in an index page resolve against the directory.
|
||||
if !trailing_slash {
|
||||
return Response::Redirect(format!("{path}/"));
|
||||
}
|
||||
let index = file.join("index.html");
|
||||
let Some(real_index) = confined(&real_root, &index).await else { return NOT_FOUND };
|
||||
return match tokio::fs::metadata(&real_index).await {
|
||||
Ok(m) if m.is_file() => Response::File { path: real_index, len: m.len(), mime: content_type(&index) },
|
||||
file.push("index.html");
|
||||
return match tokio::fs::metadata(&file).await {
|
||||
Ok(m) if m.is_file() => Response::File { path: file, len: m.len() },
|
||||
_ => NOT_FOUND,
|
||||
};
|
||||
}
|
||||
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved, if it still lies inside `real_root` (already
|
||||
/// canonical). Rejecting `..` segments is not enough: a project can commit symlinks
|
||||
/// that point anywhere on disk.
|
||||
async fn confined(real_root: &Path, path: &Path) -> Option<PathBuf> {
|
||||
let real = tokio::fs::canonicalize(path).await.ok()?;
|
||||
real.starts_with(real_root).then_some(real)
|
||||
Response::File { path: file, len: meta.len() }
|
||||
}
|
||||
|
||||
fn dec(s: &str) -> Option<String> {
|
||||
@@ -357,45 +340,6 @@ mod tests {
|
||||
assert!(get(&url, Some("evil.example:80")).await.starts_with("HTTP/1.1 403"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn symlinks_cannot_escape_the_served_root() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("repo");
|
||||
std::fs::create_dir_all(root.join("site/escape")).unwrap();
|
||||
std::fs::create_dir_all(root.join("site/assets")).unwrap();
|
||||
std::fs::write(root.join("site/index.html"), "<h1>hi</h1>").unwrap();
|
||||
std::fs::write(root.join("site/assets/app.js"), "export {}").unwrap();
|
||||
std::fs::write(root.join("site/raw"), "<p>raw</p>").unwrap();
|
||||
std::fs::write(dir.path().join("secret.txt"), "outside").unwrap();
|
||||
symlink("index.html", root.join("site/inside.html")).unwrap();
|
||||
symlink("assets", root.join("site/lib")).unwrap();
|
||||
symlink("raw", root.join("site/raw.html")).unwrap();
|
||||
symlink("../../secret.txt", root.join("site/leak.txt")).unwrap();
|
||||
symlink("../..", root.join("site/up")).unwrap();
|
||||
symlink("/", root.join("site/fsroot")).unwrap();
|
||||
symlink("../../../secret.txt", root.join("site/escape/index.html")).unwrap();
|
||||
|
||||
let server = WebServer::new();
|
||||
let url = server.url_for(Some(&root), &root.join("site/index.html")).await.unwrap();
|
||||
let base = url.trim_end_matches("index.html");
|
||||
let page = get(&format!("{base}inside.html"), None).await;
|
||||
assert!(page.starts_with("HTTP/1.1 200") && page.ends_with("<h1>hi</h1>"), "{page}");
|
||||
let page = get(&format!("{base}lib/app.js"), None).await;
|
||||
assert!(page.starts_with("HTTP/1.1 200") && page.contains("text/javascript"), "{page}");
|
||||
// The type follows the requested name, not the link target.
|
||||
let page = get(&format!("{base}raw.html"), None).await;
|
||||
assert!(page.contains("text/html") && page.ends_with("<p>raw</p>"), "{page}");
|
||||
|
||||
let secret = dir.path().join("secret.txt");
|
||||
let via_fsroot = format!("fsroot{}", secret.display());
|
||||
for escape in ["leak.txt", "up/secret.txt", via_fsroot.as_str(), "escape/"] {
|
||||
let page = get(&format!("{base}{escape}"), None).await;
|
||||
assert!(page.starts_with("HTTP/1.1 404"), "{escape}: {page}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn files_outside_the_project_get_their_own_root() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -19,7 +19,6 @@ semver = "1.0.28"
|
||||
parking_lot.workspace = true
|
||||
blake3.workspace = true
|
||||
tracing.workspace = true
|
||||
tempfile.workspace = true
|
||||
globset.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -4,7 +4,7 @@ use ide_core::error::ErrorKind;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
use parking_lot::{Mutex, ReentrantMutex, RwLock};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
@@ -62,11 +62,6 @@ pub type DetectUiMode = dyn Fn(&Path, &LanguageId) -> Option<String> + Send + Sy
|
||||
/// Every document has its own lock; operations on one document are serialized
|
||||
/// and observers see them in version order.
|
||||
pub struct Documents {
|
||||
/// Workspace transactions hold this across preflight/commit/rollback; ordinary
|
||||
/// operations re-enter it while accessing the individual document locks.
|
||||
operations: ReentrantMutex<()>,
|
||||
workspace_edits: Arc<Mutex<workspace_edit::History>>,
|
||||
workspace_edit_active: std::sync::atomic::AtomicBool,
|
||||
registry: Mutex<Registry>,
|
||||
observers: RwLock<Vec<Arc<dyn DocumentObserver>>>,
|
||||
sink: SharedSink,
|
||||
@@ -101,8 +96,6 @@ pub trait DocumentObserver: Send + Sync {
|
||||
fn closed(&self, _doc: DocId, _path: &Path) {}
|
||||
}
|
||||
|
||||
mod workspace_edit;
|
||||
|
||||
type Slot = Arc<Mutex<DocState>>;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -118,7 +111,6 @@ struct RegEntry {
|
||||
keys: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DocState {
|
||||
path: PathBuf,
|
||||
doc: Document,
|
||||
@@ -171,9 +163,6 @@ fn read_only_error(path: &Path) -> IdeError {
|
||||
impl Documents {
|
||||
pub fn new(sink: SharedSink, detect_language: Box<DetectLanguage>) -> Self {
|
||||
Self {
|
||||
operations: ReentrantMutex::new(()),
|
||||
workspace_edits: Arc::default(),
|
||||
workspace_edit_active: std::sync::atomic::AtomicBool::new(false),
|
||||
registry: Mutex::default(),
|
||||
observers: RwLock::default(),
|
||||
sink,
|
||||
@@ -290,7 +279,6 @@ impl Documents {
|
||||
|
||||
/// Locks a document, failing if it was closed concurrently.
|
||||
fn with_doc<T>(&self, doc: DocId, f: impl FnOnce(&mut DocState) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let _operation = self.operations.lock();
|
||||
let slot = self.slot(doc)?;
|
||||
let mut st = slot.lock();
|
||||
if st.closed {
|
||||
@@ -338,7 +326,6 @@ impl Documents {
|
||||
|
||||
/// Opens (or re-references) the document at `path`.
|
||||
pub fn open(&self, path: &Path) -> IdeResult<DocumentInfo> {
|
||||
let _operation = self.operations.lock();
|
||||
if let Some(info) = self.reopen(path) {
|
||||
return Ok(info);
|
||||
}
|
||||
@@ -431,7 +418,6 @@ impl Documents {
|
||||
/// language server provides for a non-`file:` URI. It is keyed by the URI,
|
||||
/// never touches the disk and cannot be edited or saved.
|
||||
pub fn open_virtual(&self, uri: &str, language: LanguageId, text: &str) -> IdeResult<DocumentInfo> {
|
||||
let _operation = self.operations.lock();
|
||||
let key = PathBuf::from(uri);
|
||||
if let Some(info) = self.reopen(&key) {
|
||||
return Ok(info);
|
||||
@@ -490,7 +476,6 @@ impl Documents {
|
||||
}
|
||||
|
||||
pub fn close(&self, doc: DocId) {
|
||||
let _operation = self.operations.lock();
|
||||
let slot = {
|
||||
let mut reg = self.registry.lock();
|
||||
let Some(entry) = reg.docs.get_mut(&doc) else { return };
|
||||
@@ -573,13 +558,7 @@ impl Documents {
|
||||
edits: &[ByteEdit],
|
||||
) {
|
||||
self.notify_changed(doc, st, applied, edits);
|
||||
self.sink.emit(IdeEvent::DocPatched {
|
||||
doc,
|
||||
base_version,
|
||||
version: st.doc.version(),
|
||||
changes: set.changes,
|
||||
workspace_edit: self.workspace_edit_active.load(std::sync::atomic::Ordering::Relaxed),
|
||||
});
|
||||
self.sink.emit(IdeEvent::DocPatched { doc, base_version, version: st.doc.version(), changes: set.changes });
|
||||
}
|
||||
|
||||
/// Minimal-diff replacement; no event when the text is unchanged.
|
||||
@@ -714,11 +693,6 @@ impl Documents {
|
||||
self.with_doc(doc, |st| Ok(st.dirty))
|
||||
}
|
||||
|
||||
/// Current generation without copying the document text.
|
||||
pub fn version(&self, doc: DocId) -> IdeResult<u32> {
|
||||
self.with_doc(doc, |st| Ok(st.doc.version()))
|
||||
}
|
||||
|
||||
/// Ids of all open documents.
|
||||
pub fn open_documents(&self) -> Vec<DocId> {
|
||||
self.registry.lock().docs.keys().copied().collect()
|
||||
@@ -731,7 +705,6 @@ impl Documents {
|
||||
/// for the observers, so it moves to the matching language servers and
|
||||
/// syntax tree. Returns the changed documents.
|
||||
pub fn redetect_languages(&self) -> Vec<DocId> {
|
||||
let _operation = self.operations.lock();
|
||||
let slots: Vec<(DocId, Slot)> = self.registry.lock().docs.iter().map(|(id, e)| (*id, e.slot.clone())).collect();
|
||||
let mut changed = Vec::new();
|
||||
for (id, slot) in slots {
|
||||
@@ -821,17 +794,6 @@ impl Documents {
|
||||
/// Re-checks open file buffers, including files outside the watched roots.
|
||||
/// Call from a blocking worker; unchanged files only need their metadata.
|
||||
pub fn sync_from_disk(&self) {
|
||||
self.sync_open_documents(false);
|
||||
}
|
||||
|
||||
/// Refreshes clean buffers after an IDE operation rewrites files. Such an
|
||||
/// operation can preserve both file length and the timestamp's millisecond.
|
||||
/// The open document's selected codec is retained.
|
||||
pub fn sync_after_disk_change(&self) {
|
||||
self.sync_open_documents(true);
|
||||
}
|
||||
|
||||
fn sync_open_documents(&self, force_clean: bool) {
|
||||
let slots: Vec<Slot> = self.registry.lock().docs.values().map(|e| e.slot.clone()).collect();
|
||||
let paths: Vec<PathBuf> = slots
|
||||
.iter()
|
||||
@@ -841,17 +803,13 @@ impl Documents {
|
||||
.then(|| st.path.clone())
|
||||
})
|
||||
.collect();
|
||||
self.reload_from_disk(&paths, force_clean);
|
||||
self.on_disk_changed(&paths);
|
||||
}
|
||||
|
||||
/// Re-reads from disk after an external change. Clean documents reload
|
||||
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
|
||||
/// Changes matching our own last save are ignored.
|
||||
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
|
||||
self.reload_from_disk(paths, false);
|
||||
}
|
||||
|
||||
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool) {
|
||||
for path in paths {
|
||||
let Some(id) = self.by_path(path) else { continue };
|
||||
let result = self.with_doc(id, |st| {
|
||||
@@ -860,7 +818,7 @@ impl Documents {
|
||||
}
|
||||
let Ok(meta) = std::fs::metadata(&st.path) else { return Ok(()) };
|
||||
let mtime = ide_vfs::mtime_ms(&meta);
|
||||
if mtime == st.disk_mtime && meta.len() == st.disk_len && (!force_clean || st.dirty) {
|
||||
if mtime == st.disk_mtime && meta.len() == st.disk_len {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
@@ -878,14 +836,9 @@ impl Documents {
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?
|
||||
} else {
|
||||
let defaults = self.file_defaults();
|
||||
let loaded = Self::load_with_defaults(&st.path, &defaults)?;
|
||||
st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
|
||||
loaded
|
||||
};
|
||||
let defaults = self.file_defaults();
|
||||
let loaded = Self::load_with_defaults(&st.path, &defaults)?;
|
||||
st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
if loaded.binary || st.binary {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -89,7 +89,7 @@ fn write_text(documents: &Documents, path: &Path, text: &str) -> IdeResult<()> {
|
||||
fn edited_paths(edit: &WorkspaceEdit) -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for f in &edit.files {
|
||||
if let FileEdit::Edit { path, edits, .. } = f
|
||||
if let FileEdit::Edit { path, edits } = f
|
||||
&& !edits.is_empty()
|
||||
&& !out.iter().any(|p| p == path)
|
||||
{
|
||||
@@ -245,7 +245,17 @@ mod tests {
|
||||
}
|
||||
|
||||
fn apply(documents: &Documents) -> impl Fn(&WorkspaceEdit) -> IdeResult<()> + '_ {
|
||||
move |edit| documents.apply_file_move_edits(edit)
|
||||
move |edit| {
|
||||
for f in &edit.files {
|
||||
if let FileEdit::Edit { path, edits } = f {
|
||||
let doc = documents.open(path)?.id;
|
||||
documents.apply_edits(doc, edits)?;
|
||||
documents.save(doc)?;
|
||||
documents.close(doc);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,10 +272,8 @@ mod tests {
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit {
|
||||
path: root.join("main.ts").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 21), Pos::new(0, 22)), new_text: "b".into() }],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let id = moves.perform(&docs, Some(&history), &mv, &edit, "Move", &apply(&docs)).unwrap();
|
||||
assert!(root.join("b/util.ts").exists() && !root.join("a").exists());
|
||||
@@ -295,16 +303,13 @@ mod tests {
|
||||
files: vec![
|
||||
FileEdit::Edit {
|
||||
path: root.join("Foo.java").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 6), Pos::new(0, 9)), new_text: "Bar".into() }],
|
||||
},
|
||||
FileEdit::Edit {
|
||||
path: root.join("Use.java").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "Bar".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let mv = vec![FileMove { from: root.join("Foo.java").into(), to: root.join("Bar.java").into() }];
|
||||
let id = moves.perform(&docs, None, &mv, &edit, "Rename", &apply(&docs)).unwrap();
|
||||
|
||||
@@ -201,11 +201,7 @@ pub fn find_text_occurrences(
|
||||
let mut files = found.into_inner();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
WorkspaceEdit {
|
||||
files: files
|
||||
.into_iter()
|
||||
.map(|(path, edits)| FileEdit::Edit { path: path.into(), edits, version: None })
|
||||
.collect(),
|
||||
..Default::default()
|
||||
files: files.into_iter().map(|(path, edits)| FileEdit::Edit { path: path.into(), edits }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,37 +57,6 @@ fn fixture() -> Fixture {
|
||||
Fixture { _tmp: tmp, root, docs, events, rec }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_disk_changes_preserve_the_open_documents_encoding() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("query.sql");
|
||||
let original = "SELECT '中文';\r\n";
|
||||
fs::write(&path, ide_vfs::encode(original, "gbk", false).unwrap()).unwrap();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults.clone());
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "gbk");
|
||||
defaults.project_fallback = "windows-1252".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
f.docs.sync_after_disk_change();
|
||||
let unchanged = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!(unchanged.text, doc.text);
|
||||
assert_eq!(unchanged.encoding, "gbk");
|
||||
assert!(!unchanged.dirty);
|
||||
let changed = "SELECT '世界';\r\n";
|
||||
let bytes = ide_vfs::encode(changed, "gbk", false).unwrap();
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
f.docs.sync_after_disk_change();
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!(reloaded.text, changed.replace("\r\n", "\n"));
|
||||
assert_eq!(reloaded.encoding, "gbk");
|
||||
assert_eq!(reloaded.line_ending, LineEnding::CrLf);
|
||||
assert!(!reloaded.dirty);
|
||||
f.docs.save_all().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
|
||||
fn change(from: u32, to: u32, insert: &str) -> ChangeSet {
|
||||
ChangeSet { changes: vec![TextChange { from, to, insert: insert.into() }] }
|
||||
}
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{IdeEvent, error::ErrorKind};
|
||||
use ide_workspace::Documents;
|
||||
use parking_lot::Mutex;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn documents() -> Documents {
|
||||
Documents::new(Arc::new(NullSink), Box::new(|_, _| LanguageId::plain_text()))
|
||||
}
|
||||
|
||||
fn edit(path: &Path, text: &str) -> FileEdit {
|
||||
FileEdit::Edit {
|
||||
path: path.to_owned().into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: text.into() }],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_failure_preserves_disk_and_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let missing = tmp.path().join("missing.txt");
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
let result = docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![edit(&first, "new"), edit(&missing, "bad")],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
let after = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(after.text, "own\n");
|
||||
assert!(after.dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_conflict_does_not_modify_earlier_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("first.txt");
|
||||
let existing = tmp.path().join("exists.txt");
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
std::fs::write(&existing, "keep").unwrap();
|
||||
let docs = documents();
|
||||
let result = docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![edit(&first, "new"), FileEdit::Create { path: existing.clone().into(), overwrite: false }],
|
||||
..Default::default()
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(existing).unwrap(), "keep");
|
||||
}
|
||||
|
||||
fn recorded_documents() -> (Documents, Arc<Mutex<Vec<IdeEvent>>>) {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
(Documents::new(Arc::new(move |event| sink.lock().push(event)), Box::new(|_, _| LanguageId::plain_text())), events)
|
||||
}
|
||||
|
||||
fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.expect("successful transaction has one undo record")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_document_version_rejects_the_whole_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let b = tmp.path().join("b.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
std::fs::write(&b, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&b).unwrap();
|
||||
docs.edit(info.id, 0, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "own ".into() }] }).unwrap();
|
||||
let mut second = edit(&b, "new");
|
||||
if let FileEdit::Edit { version, .. } = &mut second {
|
||||
*version = Some(0);
|
||||
}
|
||||
let result =
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&a, "new"), second], ..Default::default() });
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "old\n");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own old\n");
|
||||
assert!(docs.is_dirty(info.id).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_document_version_is_applied() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&a).unwrap();
|
||||
let mut operation = edit(&a, "new");
|
||||
if let FileEdit::Edit { version, .. } = &mut operation {
|
||||
*version = Some(info.version as i32);
|
||||
}
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![operation], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unversioned_preview_rejects_changed_disk_and_dirty_buffers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for open in [false, true] {
|
||||
let path = tmp.path().join(if open { "open.txt" } else { "closed.txt" });
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = open.then(|| docs.open(&path).unwrap());
|
||||
let mut change = WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() };
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
if let Some(info) = &info {
|
||||
docs.edit(
|
||||
info.id,
|
||||
info.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
std::fs::write(&path, "own\n").unwrap();
|
||||
}
|
||||
let original = change.preconditions.clone();
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
assert_eq!(change.preconditions, original, "resolution must not refresh an old preview's guard");
|
||||
assert_eq!(docs.apply_workspace_edit(&change).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
if let Some(info) = info {
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
} else {
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "own\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_undo_restores_open_closed_and_unsaved_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let b = tmp.path().join("b.txt");
|
||||
let c = tmp.path().join("c.txt");
|
||||
for path in [&a, &b, &c] {
|
||||
std::fs::write(path, "old\r\n").unwrap();
|
||||
}
|
||||
let (docs, events) = recorded_documents();
|
||||
let dirty = docs.open(&a).unwrap();
|
||||
let clean = docs.open(&b).unwrap();
|
||||
docs.edit(dirty.id, 0, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] }).unwrap();
|
||||
let change =
|
||||
WorkspaceEdit { files: [&a, &b, &c].into_iter().map(|p| edit(p, "new")).collect(), ..Default::default() };
|
||||
docs.apply_workspace_edit(&change).unwrap();
|
||||
assert_eq!(docs.snapshot(dirty.id).unwrap().text, "new\n");
|
||||
assert!(docs.is_dirty(dirty.id).unwrap());
|
||||
assert_eq!(std::fs::read(&a).unwrap(), b"old\r\n", "unrelated unsaved work is not saved");
|
||||
assert_eq!(std::fs::read(&c).unwrap(), b"new\r\n");
|
||||
let opened_later = docs.open(&c).unwrap();
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(docs.snapshot(dirty.id).unwrap().text, "own\n");
|
||||
assert!(docs.is_dirty(dirty.id).unwrap());
|
||||
for info in [clean, opened_later] {
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old\n");
|
||||
assert!(!docs.is_dirty(info.id).unwrap());
|
||||
}
|
||||
for path in [&a, &b, &c] {
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"old\r\n");
|
||||
}
|
||||
assert!(docs.undo_workspace_edit(id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&a, "new")], ..Default::default() }).unwrap();
|
||||
let id = undo_id(&events);
|
||||
std::fs::write(&a, "own\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(id).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "own\n");
|
||||
std::fs::write(&a, "new\n").unwrap();
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let created = tmp.path().join("new/deep/file.txt");
|
||||
let renamed = tmp.path().join("renamed.txt");
|
||||
let deleted = tmp.path().join("binary.dat");
|
||||
let overwritten = tmp.path().join("overwrite.txt");
|
||||
std::fs::write(&deleted, [0, 255, 1, 128]).unwrap();
|
||||
std::fs::write(&overwritten, [255, 254, 65, 0]).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let change = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Create { path: created.clone().into(), overwrite: false },
|
||||
edit(&created, "hello"),
|
||||
FileEdit::Rename { from: created.clone().into(), to: renamed.clone().into() },
|
||||
FileEdit::Delete { path: deleted.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: overwritten.clone().into(), overwrite: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.apply_workspace_edit(&change).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&renamed).unwrap(), "hello");
|
||||
assert!(!deleted.exists());
|
||||
assert!(std::fs::read(&overwritten).unwrap().is_empty());
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert!(!tmp.path().join("new").exists());
|
||||
assert!(!renamed.exists());
|
||||
assert_eq!(std::fs::read(deleted).unwrap(), [0, 255, 1, 128]);
|
||||
assert_eq!(std::fs::read(overwritten).unwrap(), [255, 254, 65, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonrecursive_directory_delete_is_rejected_before_any_write() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a.txt");
|
||||
let dir = tmp.path().join("directory");
|
||||
std::fs::write(&a, "old\n").unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("keep.txt"), "keep").unwrap();
|
||||
let change = WorkspaceEdit {
|
||||
files: vec![edit(&a, "new"), FileEdit::Delete { path: dir.clone().into(), recursive: false }],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(documents().apply_workspace_edit(&change).is_err());
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
assert!(dir.join("keep.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_write_not_yet_seen_by_watcher_is_not_overwritten() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
std::fs::write(&path, "own\n").unwrap();
|
||||
let mut change = WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() };
|
||||
docs.prepare_workspace_edit(&mut change).unwrap();
|
||||
assert_eq!(docs.apply_workspace_edit(&change).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "own\n");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn undo_restores_deleted_directory_with_symlinks_and_permissions() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("tree");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("script"), "old\n").unwrap();
|
||||
std::fs::set_permissions(dir.join("script"), std::fs::Permissions::from_mode(0o751)).unwrap();
|
||||
symlink("missing-target", dir.join("link")).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit {
|
||||
files: vec![FileEdit::Delete { path: dir.clone().into(), recursive: true }],
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!dir.exists());
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join("script")).unwrap(), b"old\n");
|
||||
assert_eq!(std::fs::metadata(dir.join("script")).unwrap().permissions().mode() & 0o777, 0o751);
|
||||
assert_eq!(std::fs::read_link(dir.join("link")).unwrap(), Path::new("missing-target"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn preflight_never_writes_through_copied_or_moved_symlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("target.txt");
|
||||
let link = tmp.path().join("link.txt");
|
||||
let moved = tmp.path().join("moved.txt");
|
||||
std::fs::write(&target, "old\n").unwrap();
|
||||
symlink(&target, &link).unwrap();
|
||||
let docs = documents();
|
||||
for files in [
|
||||
vec![FileEdit::Create { path: link.clone().into(), overwrite: true }],
|
||||
vec![FileEdit::Rename { from: link.clone().into(), to: moved.clone().into() }, edit(&moved, "new")],
|
||||
] {
|
||||
assert!(docs.apply_workspace_edit(&WorkspaceEdit { files, ..Default::default() }).is_err());
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old\n");
|
||||
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
||||
assert!(!moved.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_after_restoring_inplace_typing_saves_but_real_unsaved_work_stays_dirty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.ts");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
for (version, text) in [(0, "own"), (1, "old")] {
|
||||
docs.edit(info.id, version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
assert!(docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty, "restoring saved bytes must clear a stale dirty flag");
|
||||
docs.redo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.edit(
|
||||
info.id,
|
||||
docs.version(info.id).unwrap(),
|
||||
ChangeSet { changes: vec![TextChange { from: 3, to: 3, insert: " own".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(id).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_edits_keep_versions_and_apply_one_replacement() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.cpp");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let docs = documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
let mut versioned = edit(&path, "new_long");
|
||||
if let FileEdit::Edit { version, .. } = &mut versioned {
|
||||
*version = Some(info.version as i32);
|
||||
}
|
||||
let mut workspace = WorkspaceEdit { files: vec![edit(&path, "new_long"), versioned], ..Default::default() };
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 1);
|
||||
assert!(matches!(workspace.files[0], FileEdit::Edit { version: Some(0), .. }));
|
||||
docs.apply_workspace_edit(&workspace).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "new_long");
|
||||
|
||||
let mut conflicting = workspace.files[0].clone();
|
||||
if let FileEdit::Edit { version, .. } = &mut conflicting {
|
||||
*version = Some(99);
|
||||
}
|
||||
workspace.files.push(conflicting);
|
||||
workspace.deduplicate();
|
||||
assert_eq!(workspace.files.len(), 2, "deduplication must not discard incompatible versions");
|
||||
assert_eq!(docs.apply_workspace_edit(&workspace).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "new_long");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_accepts_typing_that_was_reverted_to_the_saved_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("main.ts");
|
||||
std::fs::write(&path, "old").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
let id = undo_id(&events);
|
||||
for text in ["own", "new"] {
|
||||
docs.edit(
|
||||
info.id,
|
||||
docs.version(info.id).unwrap(),
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: text.into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(docs.snapshot(info.id).unwrap().dirty);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "old");
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "old");
|
||||
assert!(!docs.snapshot(info.id).unwrap().dirty);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn replacing_a_symlink_then_editing_the_new_file_never_writes_its_old_target() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("precious.txt");
|
||||
let link = tmp.path().join("new.txt");
|
||||
std::fs::write(&target, "old target\n").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let target_doc = docs.open(&target).unwrap();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Delete { path: link.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: link.clone().into(), overwrite: false },
|
||||
FileEdit::Edit {
|
||||
path: link.clone().into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::point(Pos::new(0, 0)), new_text: "new file\n".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
docs.apply_workspace_edit(&edit).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old target\n");
|
||||
assert_eq!(docs.snapshot(target_doc.id).unwrap().text, "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(&link).unwrap(), "new file\n");
|
||||
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
|
||||
let id = undo_id(&events);
|
||||
docs.undo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_link(&link).unwrap(), target);
|
||||
docs.redo_workspace_edit(id).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(&link).unwrap(), "new file\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn replacing_a_directory_symlink_does_not_resolve_later_child_paths_through_its_old_target() {
|
||||
for alias in 0..3 {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("precious");
|
||||
let link = tmp.path().join("new");
|
||||
std::fs::create_dir(&target).unwrap();
|
||||
std::fs::write(target.join("file.txt"), "old target\n").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let alternate = tmp.path().join("alternate");
|
||||
std::os::unix::fs::symlink(tmp.path(), &alternate).unwrap();
|
||||
let shortcut = tmp.path().join("shortcut");
|
||||
std::os::unix::fs::symlink(&link, &shortcut).unwrap();
|
||||
let edited = match alias {
|
||||
0 => link.join("file.txt"),
|
||||
1 => alternate.join("new/file.txt"),
|
||||
_ => shortcut.join("file.txt"),
|
||||
};
|
||||
let docs = documents();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![
|
||||
FileEdit::Delete { path: link.clone().into(), recursive: false },
|
||||
FileEdit::Create { path: link.join("file.txt").into(), overwrite: false },
|
||||
FileEdit::Edit {
|
||||
path: edited.into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::point(Pos::new(0, 0)), new_text: "new file\n".into() }],
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
docs.apply_workspace_edit(&edit).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target.join("file.txt")).unwrap(), "old target\n");
|
||||
assert_eq!(std::fs::read_to_string(link.join("file.txt")).unwrap(), "new file\n");
|
||||
}
|
||||
}
|
||||
@@ -109,8 +109,8 @@ There is no build step. The package *is* the folder.
|
||||
1. Copy `templates/theme-plugin` and rename `id`, `name` and the theme files.
|
||||
2. Edit the colours. Keep `kind` truthful (`light` for light backgrounds).
|
||||
3. **Install:** *Settings › Plugins › ⚙ › Install Plugin from Disk…* (or the
|
||||
*Install Plugin from Disk…* action) and pick the package's `plugin.toml`, or
|
||||
a `.zip` of the folder. The manifest and the files it references are copied to
|
||||
*Install Plugin from Disk…* action) and pick the package folder. The
|
||||
manifest and the files it references are copied to
|
||||
`<app-data>/plugins/<id>/`.
|
||||
4. **Apply:** in *Settings › Plugins*, select the plugin and press *Apply* next
|
||||
to the theme. *Use Default Theme* switches back.
|
||||
|
||||
@@ -82,24 +82,3 @@ test("preserves all lines in a drag selection across virtual windows", async ({
|
||||
expect(text).toContain("output 250\noutput 251");
|
||||
expect(text).toContain("output 284");
|
||||
});
|
||||
|
||||
test("Select All takes the whole buffer, not just the mounted rows", async ({ page }) => {
|
||||
const log = await consoleOutput(page);
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { copied: string[] }).copied = [];
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: { writeText: async (text: string) => (window as unknown as { copied: string[] }).copied.push(text) },
|
||||
});
|
||||
});
|
||||
await log.focus();
|
||||
await page.keyboard.press("Meta+A");
|
||||
// Selection stays inside the console: nothing from the workbench behind it is selected.
|
||||
const selected = await page.evaluate(() => window.getSelection()?.toString() ?? "");
|
||||
expect(selected).not.toContain("Project");
|
||||
await page.keyboard.press("Meta+C");
|
||||
const [copied] = await page.evaluate(() => (window as unknown as { copied: string[] }).copied);
|
||||
expect(copied?.split("\n")).toHaveLength(500);
|
||||
expect(copied).toContain("output 0\n");
|
||||
expect(copied).toMatch(/output 499$/);
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("local terminal stores clipboard media and pastes one shell-quoted argument", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const observed = await page.evaluate(async () => {
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const sessionPath = "/src/features/terminal/session.ts";
|
||||
const { commands } = await import(ipcPath);
|
||||
const { TerminalSession } = await import(sessionPath);
|
||||
Object.defineProperty(window, "__TAURI_INTERNALS__", {
|
||||
configurable: true,
|
||||
value: { transformCallback: () => 1 },
|
||||
});
|
||||
const stored: { id: number; data: number[]; mime: string }[] = [];
|
||||
const writes: string[] = [];
|
||||
commands.termSpawn = async () => ({ status: "ok", data: { id: 838, title: "pwsh", pid: 1 } });
|
||||
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
|
||||
commands.termStoreImage = async (id: number, data: number[], mime: string) => {
|
||||
stored.push({ id, data, mime });
|
||||
return { status: "ok", data: "C:\\Temp\\a'b c\\image.png" };
|
||||
};
|
||||
commands.termWrite = async (_id: number, data: string) => writes.push(data);
|
||||
commands.termResize = async () => undefined;
|
||||
commands.termKill = async () => undefined;
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText = "position:fixed;inset:0;z-index:99999";
|
||||
document.body.append(container);
|
||||
const session = new TerminalSession({ key: "clipboard", cwd: "C:/Temp", onChange() {}, onFocus() {} });
|
||||
try {
|
||||
session.attach(container);
|
||||
await session.start();
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(new File([new Uint8Array([137, 80, 78, 71])], "image.png", { type: "image/png" }));
|
||||
const event = new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer });
|
||||
container.querySelector("textarea")!.dispatchEvent(event);
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!writes.length && Date.now() < deadline) await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
return { stored, writes, claimed: event.defaultPrevented };
|
||||
} finally {
|
||||
session.dispose();
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
expect(observed.claimed).toBe(true);
|
||||
expect(observed.stored).toEqual([{ id: 838, data: [137, 80, 78, 71], mime: "image/png" }]);
|
||||
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
id = "erb"
|
||||
name = "ERB"
|
||||
extensions = ["erb", "html.erb", "rhtml", "js.erb", "text.erb", "xml.erb", "json.erb"]
|
||||
block-comment = ["<%#", "%>"]
|
||||
indent = { tab-size = 2, insert-spaces = true }
|
||||
ui-mode = "ERB"
|
||||
@@ -40,24 +40,6 @@ args = ["server"]
|
||||
root-markers = ["ty.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
|
||||
install-hint = "uv tool install ty (or: pip install ty)"
|
||||
|
||||
[[language-servers]]
|
||||
name = "pyrefly"
|
||||
fallback = true
|
||||
command = "pyrefly"
|
||||
args = ["lsp"]
|
||||
root-markers = ["pyrefly.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
|
||||
install-hint = "uv tool install pyrefly (or: pip install pyrefly)"
|
||||
|
||||
# Lint, format, organize imports and fix all next to the type checker, in
|
||||
# projects configured for Ruff (formatting is Ruff's alone: basedpyright has none).
|
||||
[[language-servers]]
|
||||
name = "ruff"
|
||||
command = "ruff"
|
||||
args = ["server"]
|
||||
root-markers = ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"]
|
||||
require-root-marker = true
|
||||
install-hint = "pip install ruff (or: uv tool install ruff)"
|
||||
|
||||
[debugger]
|
||||
adapter = "debugpy"
|
||||
command = "python3"
|
||||
|
||||
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача