дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
81fe384f4f | ||
|
|
01defdefe4 | ||
|
|
5bab140968 | ||
|
|
33d8d87ca2 | ||
|
|
669595e045 | ||
|
|
9c31a27e30 | ||
|
|
f265e636e9 | ||
|
|
47bd21e315 | ||
|
|
a5b7c154e1 | ||
|
|
b2c183dbd4 | ||
|
|
bc70ec7028 | ||
|
|
195356c4b1 | ||
|
|
67e3c60db8 | ||
|
|
f87d153caf | ||
|
|
552a43a0a1 | ||
|
|
2b1add64db | ||
|
|
d277fc1522 | ||
|
|
b983e3d0b2 | ||
|
|
ce981e4fd6 | ||
|
|
19b96b60a4 | ||
|
|
9295a8f78a | ||
|
|
f507f55d16 | ||
|
|
86cf348310 | ||
|
|
a1294598a5 | ||
|
|
6669df8313 | ||
|
|
83eb1ce2ba | ||
|
|
6356e85671 | ||
|
|
ed6092a4e9 | ||
|
|
12f676e0c0 | ||
|
|
1ee22dbf35 | ||
|
|
7ba75c814c | ||
|
|
ae110f73be | ||
|
|
c3252d43c3 | ||
|
|
924446279b | ||
|
|
f88b5d6f8c | ||
|
|
ea53e4f6fa | ||
|
|
379a52d6e7 | ||
|
|
92b3ae508c | ||
|
|
d837cb1acb | ||
|
|
932ac379bc | ||
|
|
fd5908e224 | ||
|
|
e017154c75 | ||
|
|
3655961642 | ||
|
|
545fb93744 | ||
|
|
d9d1caa476 | ||
|
|
9d1fe17894 | ||
|
|
9575500dd6 | ||
|
|
0329678124 | ||
|
|
2924c0f8e5 | ||
|
|
082420b5bb | ||
|
|
9a5b44bebb | ||
|
|
2203938491 | ||
|
|
503bbb2f02 | ||
|
|
ab6fca01c4 | ||
|
|
0a27d02f4d | ||
|
|
97b8928e4f | ||
|
|
53fd3683e2 | ||
|
|
27bef6956e | ||
|
|
3563f70810 | ||
|
|
7a46774fda | ||
|
|
2ad979af66 | ||
|
|
f5a95dcc21 | ||
|
|
1ed6f7241b | ||
|
|
0d880b9d35 | ||
|
|
95068f5885 | ||
|
|
15d926a5d8 | ||
|
|
7da58637c2 | ||
|
|
b1be3c6a09 | ||
|
|
5792e7d9b6 | ||
|
|
ab7cc02561 | ||
|
|
a7b5758f5a | ||
|
|
e85ffa2ae8 | ||
|
|
2c10b63f76 | ||
|
|
44d0f40b13 | ||
|
|
f28d8da3a1 |
No files matched your search
@@ -3,6 +3,8 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -69,6 +71,15 @@ jobs:
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
|
||||
deny:
|
||||
name: Cargo deny
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: taiki-e/install-action@cargo-deny
|
||||
- run: cargo deny check
|
||||
|
||||
frontend:
|
||||
name: Frontend
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
Створено
+229
-272
File diff suppressed because it is too large.
Load diff
+3
-3
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.26"
|
||||
version = "0.1.28"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -76,6 +76,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
|
||||
# search, index, language
|
||||
grep-searcher = "0.1"
|
||||
@@ -96,9 +97,8 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.12", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
bb8 = "0.9"
|
||||
bb8-tiberius = { version = "0.16", default-features = false, features = ["tds73", "tls", "with-tokio", "sql-browser"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
# testing
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
<a href="#benchmark">Benchmark</a>
|
||||
·
|
||||
<a href="#build">Build</a>
|
||||
·
|
||||
<a href="https://discord.gg/2Zy4yn7gP">Discord</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
@@ -147,6 +147,7 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Use the TodoWrite tool"),
|
||||
provider: "claude-acp".into(),
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
|
||||
|
||||
@@ -37,6 +37,16 @@ pub(crate) fn bypass_approvals(provider: &str, config: &[AgentConfigOption]) ->
|
||||
provider == "cursor" && config.iter().any(|o| o.id == CURSOR_APPROVAL && o.current.as_deref() == Some("bypass"))
|
||||
}
|
||||
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| {
|
||||
let m: String = v.value.to_lowercase().chars().filter(char::is_ascii_lowercase).collect();
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
|
||||
})?;
|
||||
Some((option, value))
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
/// plus the older `modes` / `models` fields for what those don't cover.
|
||||
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
|
||||
@@ -23,6 +23,7 @@ pub use model::*;
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -116,9 +117,13 @@ impl Shared {
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
|
||||
config::add_client_options(provider, &mut config);
|
||||
// Approval bypass belongs to the conversation, never to another new task.
|
||||
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
|
||||
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
|
||||
{
|
||||
o.current = Some(v);
|
||||
}
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
|
||||
o.current = Some("ask".into());
|
||||
o.current = Some("bypass".into());
|
||||
}
|
||||
config
|
||||
}
|
||||
@@ -314,8 +319,8 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
|
||||
/// in the project: what the agent offered last time there, plus, for Claude Code, the
|
||||
/// skills and custom commands on disk it has not listed.
|
||||
/// in the project: what the agent offered last time there, unadvertised builtins,
|
||||
/// and, for Claude Code, skills and custom commands on disk it has not listed.
|
||||
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
|
||||
let (provider, offered, cwd) = match task {
|
||||
Some(id) => {
|
||||
@@ -325,6 +330,14 @@ impl AgentManager {
|
||||
}
|
||||
None => (provider.to_owned(), self.shared.known_commands(provider), self.shared.paths.project_root.clone()),
|
||||
};
|
||||
// Commands the agent implements itself and never lists (its CLI builtins):
|
||||
// merged without duplicating what `availableCommands` or the disk offer.
|
||||
let mut offered = offered;
|
||||
for &(name, description) in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == name) {
|
||||
offered.push(AgentCommand { name: name.to_owned(), description: description.to_owned(), hint: None });
|
||||
}
|
||||
}
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
return Ok(offered);
|
||||
}
|
||||
@@ -353,9 +366,16 @@ impl AgentManager {
|
||||
.ok_or_else(|| IdeError::invalid(format!("unknown agent {}", req.provider)))?;
|
||||
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the task first"))?;
|
||||
let title = title_of(&prompt);
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let root = req.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone());
|
||||
let project_root = Some(IpcPath(root.clone()));
|
||||
let (cwd, branch, base, base_commit, before) = match req.isolation {
|
||||
Isolation::Worktree => {
|
||||
// The UI offers worktrees for git projects only; state it when it isn't one.
|
||||
if Repo::discover(&root)?.is_none() {
|
||||
return Err(IdeError::invalid(
|
||||
"worktrees need a git repository: run the task in the local checkout",
|
||||
));
|
||||
}
|
||||
let dir = self.shared.paths.worktrees_dir.clone();
|
||||
let (t, b) = (title.clone(), req.base.clone());
|
||||
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
|
||||
@@ -379,6 +399,7 @@ impl AgentManager {
|
||||
}
|
||||
let now = now_ms();
|
||||
let task = AgentTask {
|
||||
project_root,
|
||||
id: uuid::Uuid::new_v4().simple().to_string(),
|
||||
title,
|
||||
provider: spec.id.clone(),
|
||||
@@ -539,6 +560,10 @@ impl AgentManager {
|
||||
o.current = Some(value);
|
||||
}
|
||||
s.task.model = model_of(&s.task.config).or(s.task.model.take());
|
||||
let provider = s.task.provider.clone();
|
||||
let config = s.task.config.clone();
|
||||
drop(s);
|
||||
task.shared.remember(&provider, Some(&config), None);
|
||||
}
|
||||
task.approve_pending();
|
||||
task.persist();
|
||||
@@ -748,18 +773,41 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns an archived task to the active list without starting the agent.
|
||||
pub fn unarchive(&self, id: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
{
|
||||
let mut s = task.state.lock();
|
||||
if s.task.status != AgentStatus::Archived {
|
||||
return Ok(());
|
||||
}
|
||||
if s.busy {
|
||||
return Err(IdeError::invalid("the task is still stopping"));
|
||||
}
|
||||
s.task.status = AgentStatus::Ready;
|
||||
s.task.error = None;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays).
|
||||
pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
task.kill();
|
||||
let (isolation, cwd) = {
|
||||
let (isolation, cwd, root) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.isolation, s.task.cwd.0.clone())
|
||||
(
|
||||
s.task.isolation,
|
||||
s.task.cwd.0.clone(),
|
||||
s.task.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone()),
|
||||
)
|
||||
};
|
||||
// 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 root = self.shared.paths.project_root.clone();
|
||||
blocking(move || worktree::remove(&root, &cwd)).await?;
|
||||
}
|
||||
self.tasks.write().remove(id);
|
||||
@@ -1017,6 +1065,7 @@ impl Task {
|
||||
self.push_entry(AgentEntry::User {
|
||||
text: prompt.text,
|
||||
attachments,
|
||||
images: prompt.images,
|
||||
sent_ms: Some(now_ms()),
|
||||
done_ms: None,
|
||||
steered: true,
|
||||
@@ -1037,6 +1086,7 @@ impl Task {
|
||||
self.push_entry(AgentEntry::User {
|
||||
text: prompt.text.clone(),
|
||||
attachments,
|
||||
images: prompt.images.clone(),
|
||||
sent_ms: Some(now_ms()),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
@@ -1183,7 +1233,6 @@ impl Task {
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
};
|
||||
config::add_client_options(&provider_id, &mut options);
|
||||
self.shared.remember(&provider_id, Some(&options), None);
|
||||
for choice in &wanted {
|
||||
// An option the session doesn't offer yet is set once it does (`apply_late_choices`).
|
||||
let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue };
|
||||
@@ -1212,6 +1261,7 @@ impl Task {
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
|
||||
}
|
||||
}
|
||||
self.shared.remember(&provider_id, Some(&options), None);
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.model = model_of(&options).or(s.task.model.take());
|
||||
@@ -1629,6 +1679,16 @@ fn model_of(config: &[AgentConfigOption]) -> Option<String> {
|
||||
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
|
||||
}
|
||||
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands` —
|
||||
/// its CLI builtins, passed through as prompt text (e.g. `/compact`). `(name, description)`.
|
||||
fn builtin_commands(provider: &str) -> &'static [(&'static str, &'static str)] {
|
||||
match provider {
|
||||
// OpenCode ACP handles `/compact` via session.summarize but omits it from its command list.
|
||||
"opencode" => &[("compact", "compact the conversation")],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ pub enum Isolation {
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentTask {
|
||||
/// Original project folder; absent in tasks saved before per-task roots.
|
||||
#[serde(default)]
|
||||
pub project_root: Option<IpcPath>,
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
/// [`AgentProvider::id`].
|
||||
@@ -240,6 +243,9 @@ pub enum AgentEntry {
|
||||
text: String,
|
||||
/// Names of the files and images sent with it.
|
||||
attachments: Vec<String>,
|
||||
/// The images sent with it, shown in the conversation.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// When it was sent (ms since the epoch); `None` in tasks saved before this was kept.
|
||||
#[serde(default)]
|
||||
sent_ms: Option<f64>,
|
||||
@@ -361,6 +367,9 @@ pub struct AgentProbe {
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NewAgentTask {
|
||||
/// Validated by the host; defaults to the window project root.
|
||||
#[serde(default)]
|
||||
pub project_root: Option<IpcPath>,
|
||||
pub prompt: AgentPrompt,
|
||||
pub provider: String,
|
||||
/// Settings for the new session (model, mode…).
|
||||
|
||||
@@ -124,4 +124,24 @@ mod tests {
|
||||
assert_eq!(newest_install_in("nope", &search), "nope");
|
||||
assert_eq!(newest_install_in("bin/claude", &search), "bin/claude");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_compares_versions_across_path_entries() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
for (path, version) in [(&old, "2.9.0"), (&new, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(&executable, format!("#!/bin/sh\necho {version}\n")).unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
for paths in [[&old, &new], [&new, &old]] {
|
||||
let search = std::env::join_paths(paths).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,7 +335,7 @@ pub fn mark_updates(paths: &RegistryPaths, providers: &mut [AgentProvider]) {
|
||||
|
||||
/// HTTPS only, redirects included. Tests serve downloads over `file://`.
|
||||
fn http() -> IdeResult<Http> {
|
||||
let http = Http::new(&ide_tools::default_search_path())?;
|
||||
let http = Http::new(&ide_core::tool_path::search_path())?;
|
||||
Ok(if cfg!(test) { http } else { http.https_only() })
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ fn config(provider: &str) -> Vec<AgentConfigChoice> {
|
||||
|
||||
async fn create(mgr: &AgentManager, provider: &str, prompt: &str) -> String {
|
||||
let req = NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text(prompt),
|
||||
provider: provider.into(),
|
||||
config: config(provider),
|
||||
|
||||
@@ -210,10 +210,11 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
let names = |c: Vec<AgentCommand>| c.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
|
||||
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
|
||||
// Before any session: the skills on disk.
|
||||
// Before any session: only the skills on disk.
|
||||
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["triage"]);
|
||||
let task = mgr_a
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Fix the lexer"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
@@ -227,6 +228,8 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
|
||||
// Other agents get only what they offered.
|
||||
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::Ready).await;
|
||||
mgr_a.shutdown();
|
||||
|
||||
// Another project shares the settings but not the commands.
|
||||
@@ -239,6 +242,46 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
for provider in ["claude", "claude-acp", "opencode2", "codex", "custom"] {
|
||||
assert!(mgr.commands(provider, None).await.unwrap().is_empty(), "{provider}");
|
||||
}
|
||||
let commands = mgr.commands("opencode", None).await.unwrap();
|
||||
assert_eq!(commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["compact"]);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Hello"),
|
||||
provider: "opencode".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let advertised = AgentCommand {
|
||||
name: "compact".into(),
|
||||
description: "Agent supplied description".into(),
|
||||
hint: Some("instructions".into()),
|
||||
};
|
||||
mgr.task(&task.id).unwrap().state.lock().task.commands = vec![advertised.clone()];
|
||||
// The task's provider wins over the caller's provider; metadata is not replaced.
|
||||
let commands = mgr.commands("claude", Some(&task.id)).await.unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert_eq!(commands[0].name, advertised.name);
|
||||
assert_eq!(commands[0].description, advertised.description);
|
||||
assert_eq!(commands[0].hint, advertised.hint);
|
||||
// Finish the in-process agent before Tokio stops driving its permission response.
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
|
||||
for _ in 0..500 {
|
||||
let task = mgr.task(id).unwrap();
|
||||
@@ -268,6 +311,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Fix the lexer\nmore detail"),
|
||||
provider: "claude".into(),
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "small".into() }],
|
||||
@@ -374,6 +418,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
@@ -428,6 +473,7 @@ async fn subagents_get_their_own_conversation() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("delegate"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
@@ -521,6 +567,7 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("do it"),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
@@ -542,6 +589,7 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
|
||||
assert!(
|
||||
mgr.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text(" "),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
@@ -587,6 +635,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Create a file named hello.txt containing the single word hi. Do nothing else."),
|
||||
provider: "claude".into(),
|
||||
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
|
||||
@@ -635,6 +684,7 @@ async fn forks_rollbacks_and_steering() {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = |prompt: &str| NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text(prompt),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
@@ -685,6 +735,7 @@ async fn usage_limits_and_late_settings() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("limit"),
|
||||
provider: "claude".into(),
|
||||
// `effort` isn't offered until the session runs.
|
||||
@@ -727,6 +778,7 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = || NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Fix"),
|
||||
provider: "cursor".into(),
|
||||
config: Vec::new(),
|
||||
@@ -752,15 +804,17 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
mgr.prompt(&task.id, text("Fix again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c.contains("bypass")));
|
||||
assert!(!config::bypass_approvals("cursor", &mgr.shared.known_config("cursor")));
|
||||
assert!(config::bypass_approvals("cursor", &mgr.shared.known_config("cursor")));
|
||||
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "ask".into()).await.unwrap();
|
||||
mgr.prompt(&task.id, text("Fix once more"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
// An unrelated new conversation still asks, even after the cache was updated.
|
||||
// A task created without choosing approvals still asks; the New Task page sends the default.
|
||||
let other = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &other.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&other.id, None).unwrap();
|
||||
wait_for(&mgr, &other.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
@@ -770,6 +824,7 @@ async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Fix"),
|
||||
provider: "cursor".into(),
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
@@ -781,3 +836,109 @@ async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn archived_tasks_can_be_restored_and_continue_their_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(mgr.prompt(&task.id, text("again"), false).await.is_err());
|
||||
mgr.unarchive(&task.id).unwrap();
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(mgr.task(&task.id).unwrap().live.lock().is_none());
|
||||
assert_eq!(mgr.entries(&task.id, None).unwrap().len(), entries.len());
|
||||
drop(mgr);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
|
||||
assert_eq!(mgr.entries(&task.id, None).unwrap().len(), entries.len() + 2);
|
||||
mgr.unarchive(&task.id).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn task_project_root_controls_local_and_worktree_repositories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let member = root.join("project-b");
|
||||
std::fs::create_dir(&member).unwrap();
|
||||
let git = |args: &[&str]| {
|
||||
let out = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&member)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_owned()
|
||||
};
|
||||
git(&["init", "-q", "-b", "member-main"]);
|
||||
std::fs::write(member.join("file.txt"), "original\n").unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["commit", "-qm", "initial"]);
|
||||
let mgr = manager(&root, Arc::new(FakeAgent::default()));
|
||||
for isolation in [Isolation::Local, Isolation::Worktree] {
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(member.clone())),
|
||||
prompt: text("member task"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(task.project_root, Some(IpcPath(member.clone())));
|
||||
assert_eq!(task.base.as_deref(), Some("member-main"));
|
||||
if isolation == Isolation::Local {
|
||||
assert_eq!(task.cwd.0, member);
|
||||
} else {
|
||||
assert_ne!(task.cwd.0, member);
|
||||
assert_eq!(std::fs::read_to_string(task.cwd.0.join("file.txt")).unwrap(), "original\n");
|
||||
}
|
||||
std::fs::write(task.cwd.0.join("file.txt"), "changed\n").unwrap();
|
||||
let changes = mgr.changes(&task.id).await.unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0].path.0, task.cwd.0.join("file.txt"));
|
||||
assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).await.unwrap().as_deref(), Some("original\n"));
|
||||
let saved = std::fs::read(root.join("store").join(format!("{}.json", task.id))).unwrap();
|
||||
assert!(String::from_utf8(saved).unwrap().contains("projectRoot"));
|
||||
let mut old = serde_json::to_value(&task).unwrap();
|
||||
old.as_object_mut().unwrap().remove("projectRoot");
|
||||
assert!(serde_json::from_value::<AgentTask>(old).unwrap().project_root.is_none());
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
if isolation == Isolation::Worktree {
|
||||
assert!(!task.cwd.0.exists());
|
||||
}
|
||||
std::fs::write(member.join("file.txt"), "original\n").unwrap();
|
||||
}
|
||||
assert_eq!(git(&["worktree", "list", "--porcelain"]).matches("worktree ").count(), 1);
|
||||
}
|
||||
@@ -446,6 +446,7 @@ mod tests {
|
||||
let user = |sent: f64| AgentEntry::User {
|
||||
text: "q".into(),
|
||||
attachments: vec![],
|
||||
images: vec![],
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
|
||||
@@ -53,8 +53,9 @@ pub(crate) fn remove(project_root: &Path, path: &Path) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
/// Files under `cwd` that differ from `base` (untracked files included), with line counts.
|
||||
/// Outside a repository there is nothing to compare against: no changes.
|
||||
pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let repo = repo_at(cwd)?;
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
let stats = repo.numstat_with_worktree(base)?;
|
||||
let stat = |rel: &str| stats.iter().find(|(p, ..)| p == rel).map_or((0, 0), |&(_, a, r)| (a, r));
|
||||
@@ -96,7 +97,7 @@ pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<Str
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let repo = repo_at(cwd)?;
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -141,6 +142,20 @@ mod tests {
|
||||
assert_eq!(unique_slug("x", |s| s == "x" || s == "x-2"), "x-3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_a_repository_there_is_nothing_to_compare() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plain");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.txt"), "one\n").unwrap();
|
||||
|
||||
assert!(changes(&dir, "HEAD").unwrap().is_empty());
|
||||
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, &dir).is_err());
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
|
||||
@@ -399,6 +399,12 @@ pub fn parse_tasks(output: &str) -> Vec<(String, GradleTask)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Static fallback until Gradle has reported its tasks.
|
||||
pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
let script = strip_comments(script);
|
||||
script.split(|c: char| !c.is_alphanumeric() && c != '_').any(|word| word == "war")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod maven;
|
||||
pub mod pom_edit;
|
||||
mod process;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
|
||||
pub use gradle::{GradleModel, GradleProject, GradleTask};
|
||||
|
||||
@@ -401,6 +401,9 @@ struct Inherited {
|
||||
managed: Vec<RawDep>,
|
||||
plugins: Vec<RawPlugin>,
|
||||
managed_plugins: Vec<RawPlugin>,
|
||||
/// `<id>`, `activeByDefault`: profiles of the POM and its ancestors —
|
||||
/// Maven lets a child enable a parent's profiles with `-P`.
|
||||
profiles: Vec<(String, bool)>,
|
||||
}
|
||||
|
||||
fn merge_by<T: Clone>(base: &mut Vec<T>, own: &[T], key: impl Fn(&T) -> String) {
|
||||
@@ -523,6 +526,11 @@ impl Resolver {
|
||||
merge_by(&mut ctx.deps, &p.deps, RawDep::key);
|
||||
merge_plugins(&mut ctx.plugins, &p.plugins);
|
||||
}
|
||||
merge_by(
|
||||
&mut ctx.profiles,
|
||||
&pom.profiles.iter().map(|p| (p.id.clone(), p.active_by_default)).collect::<Vec<_>>(),
|
||||
|(id, _)| id.clone(),
|
||||
);
|
||||
// Managed dependencies: own entries win; imported BOMs fill the gaps.
|
||||
let props = self.properties_for(&pom, &ctx, &dir);
|
||||
let mut imported: Vec<RawDep> = Vec::new();
|
||||
@@ -935,9 +943,10 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
|
||||
.or_else(|| pom.compiler_release.as_deref().map(i))
|
||||
.and_then(|v| java_version(&v));
|
||||
|
||||
for p in &pom.profiles {
|
||||
if !model.profiles.iter().any(|x| x.id == p.id) {
|
||||
model.profiles.push(MavenProfile { id: p.id.clone(), active_by_default: p.active_by_default });
|
||||
// The project can activate the profiles of its own POM and its ancestors'.
|
||||
for (id, active) in &ctx.profiles {
|
||||
if !model.profiles.iter().any(|x| x.id == *id) {
|
||||
model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active });
|
||||
}
|
||||
}
|
||||
let artifact_id = i(&pom.artifact_id);
|
||||
@@ -954,7 +963,7 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(root, &dir),
|
||||
options: Vec::new(),
|
||||
@@ -1280,9 +1289,41 @@ mod tests {
|
||||
let profiles: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert_eq!(profiles, [("dev", true), ("extra", false)]);
|
||||
assert_eq!(parent.profiles, ["dev", "extra"]);
|
||||
assert_eq!(core.profiles, ["dev", "extra"], "a module inherits its parent's profiles");
|
||||
assert!(model.projects.iter().all(|p| p.command == if cfg!(windows) { "mvn.cmd" } else { "mvn" }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_of_a_parent_pom_are_inherited() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version>
|
||||
<packaging>pom</packaging><modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>jdk8</id></profile>
|
||||
<profile><id>jdk21</id><activation><activeByDefault>true</activeByDefault></activation></profile>
|
||||
</profiles>
|
||||
</project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"child/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>own</id></profile></profiles>
|
||||
</project>"#,
|
||||
);
|
||||
let model = load_with_repo(root, None);
|
||||
let child = &model.projects[1];
|
||||
// `-Pjdk8` on the module activates the parent's profile, so it is listed.
|
||||
assert_eq!(child.profiles, ["jdk8", "jdk21", "own"]);
|
||||
let profiles: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert_eq!(profiles, [("jdk8", false), ("jdk21", true), ("own", false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_and_bom_from_the_local_repository_and_wrapper() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -34,6 +34,22 @@ fn kill_tree(child: &mut Child) {
|
||||
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.
|
||||
fn program_path(program: &str, env: &BTreeMap<String, String>) -> std::path::PathBuf {
|
||||
let path = std::path::Path::new(program);
|
||||
if !path.is_relative() || path.components().count() > 1 {
|
||||
return path.to_path_buf();
|
||||
}
|
||||
let search = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.unwrap_or_else(ide_core::tool_path::search_path);
|
||||
ide_core::process::find_executable(program, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// Runs `program args` in `cwd`, feeding each output line to `on_line`; kills
|
||||
/// the process group and returns `cancelled` when `cancel` fires.
|
||||
pub(crate) fn run(
|
||||
@@ -48,7 +64,8 @@ pub(crate) fn run(
|
||||
// Output is read as UTF-8: JVMs on Windows are told to write it (see `ide_core::output_encoding`).
|
||||
let encoding =
|
||||
ide_core::output_encoding::fix(program, args, env, |k| std::env::var(k).ok(), "UTF-8", cfg!(windows));
|
||||
let mut command = Command::new(program);
|
||||
let program = program_path(program, env);
|
||||
let mut command = Command::new(&program);
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
@@ -57,7 +74,8 @@ pub(crate) fn run(
|
||||
command.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -121,6 +121,16 @@ fn now_ms() -> f64 {
|
||||
/// Merges the cached effective build into `model`.
|
||||
pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel) {
|
||||
let Some(cache) = read_cache::<MavenCache>(cache_dir, MAVEN_CACHE) else { return };
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model));
|
||||
model.stale = !cache.verbose || changed;
|
||||
// A cache older than the current build files: its effective-POM plugins and
|
||||
// resolved dependencies would hide what the POMs declare now (a just added
|
||||
// dependency never appears). The static parse stays until Reload.
|
||||
if changed {
|
||||
return;
|
||||
}
|
||||
for p in &mut model.projects {
|
||||
if let Some(c) = cache.projects.iter().find(|c| c.key == p.key()) {
|
||||
if !c.plugins.is_empty() {
|
||||
@@ -129,9 +139,6 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
|
||||
p.dependencies = c.dependencies.clone();
|
||||
}
|
||||
}
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
model.stale = !cache.verbose || cache.hash != hash_files(&maven::build_files(root, model));
|
||||
}
|
||||
|
||||
/// Merges the cached task list into `model`.
|
||||
@@ -349,12 +356,16 @@ mod tests {
|
||||
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><groupId>g</groupId><artifactId>a</artifactId><version>2</version></project>",
|
||||
"<project><groupId>g</groupId><artifactId>a</artifactId><version>2</version>\
|
||||
<dependencies><dependency><groupId>g</groupId><artifactId>fresh</artifactId><version>1</version></dependency></dependencies>\
|
||||
</project>",
|
||||
)
|
||||
.unwrap();
|
||||
let mut model = maven::load_with_repo(&root, None);
|
||||
apply_maven_cache(&root, &cache_dir, &mut model);
|
||||
assert!(model.stale);
|
||||
// The POM changed: the stale effective dependencies must not hide the new one (#249).
|
||||
assert_eq!(model.projects[0].dependencies[0].artifact_id, "fresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! WAR modules and build-tool-owned archive resolution (including custom output names).
|
||||
use crate::BuildModel;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebArtifact {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub module: String,
|
||||
pub tool: String,
|
||||
}
|
||||
|
||||
pub fn artifacts(root: &Path, model: &BuildModel) -> Vec<WebArtifact> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(maven) = &model.maven {
|
||||
for p in maven.projects.iter().filter(|p| p.packaging == "war") {
|
||||
out.push(WebArtifact {
|
||||
id: format!("maven:{}", p.pom),
|
||||
name: p.artifact_id.clone(),
|
||||
module: p.dir.clone(),
|
||||
tool: "maven".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(gradle) = &model.gradle {
|
||||
for p in &gradle.projects {
|
||||
let script = p.build_file.as_ref().and_then(|f| fs::read_to_string(root.join(f)).ok()).unwrap_or_default();
|
||||
if p.tasks.iter().any(|t| t.name == "war") || crate::gradle::has_war_plugin(&script) {
|
||||
out.push(WebArtifact {
|
||||
id: format!("gradle:{}", p.path),
|
||||
name: p.name.clone(),
|
||||
module: p.dir.clone(),
|
||||
tool: "gradle".into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub struct WebBuild {
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
pub cwd: String,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResult<WebBuild> {
|
||||
fs::create_dir_all(cache)?;
|
||||
let manifest = cache.join("artifact-path.txt");
|
||||
// A failed build must never silently reuse an older archive manifest.
|
||||
if manifest.exists() {
|
||||
fs::remove_file(&manifest)?;
|
||||
}
|
||||
fs::write(cache.join("artifact-id.txt"), id)?;
|
||||
if let Some(pom) = id.strip_prefix("maven:") {
|
||||
let p = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let projects = &model.maven.as_ref().unwrap().projects;
|
||||
let top = projects
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
|
||||
})
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.unwrap_or(p);
|
||||
let mut args = top.options.clone();
|
||||
if top.pom != p.pom {
|
||||
let module = root
|
||||
.join(&p.dir)
|
||||
.strip_prefix(root.join(&top.dir))
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
args.extend(["-pl".into(), module, "-am".into()]);
|
||||
}
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.artifact.file".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
return Ok(WebBuild { command: top.command.clone(), args, cwd: top.dir.clone(), env: p.env.clone() });
|
||||
}
|
||||
if let Some(path) = id.strip_prefix("gradle:") {
|
||||
let g = model.gradle.as_ref().ok_or_else(|| IdeError::invalid("Choose a Gradle WAR module"))?;
|
||||
if !artifacts(root, model).iter().any(|a| a.id == id) {
|
||||
return Err(IdeError::invalid("Choose a Gradle WAR module"));
|
||||
}
|
||||
let literal = |s: &str| format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'"));
|
||||
let script = cache.join("war.init.gradle");
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def warTask = p.tasks.named('war')
|
||||
p.tasks.register('openideaTomcatArtifact') {{
|
||||
dependsOn warTask
|
||||
doLast {{ new File({}).text = warTask.get().archiveFile.get().asFile.absolutePath }}
|
||||
}}
|
||||
}}
|
||||
"#,
|
||||
literal(path),
|
||||
literal(&manifest.to_string_lossy())
|
||||
),
|
||||
)?;
|
||||
let task = format!("{}:openideaTomcatArtifact", path.trim_end_matches(':'));
|
||||
return Ok(WebBuild {
|
||||
command: g.command.clone(),
|
||||
args: vec!["--init-script".into(), script.to_string_lossy().into_owned(), task],
|
||||
cwd: g.dir.clone(),
|
||||
env: g.env.clone(),
|
||||
});
|
||||
}
|
||||
Err(IdeError::invalid("Choose a WAR artifact"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn maven_war_modules_use_resolved_artifact_file() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fs::write(tmp.path().join("pom.xml"), "<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>web</artifactId><version>1</version><packaging>war</packaging><build><directory>custom</directory><finalName>renamed</finalName></build></project>").unwrap();
|
||||
let model = crate::load(tmp.path(), &tmp.path().join("cache"), None);
|
||||
let a = artifacts(tmp.path(), &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_eq!(a[0].name, "web");
|
||||
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base with spaces")).unwrap();
|
||||
assert!(plan.args.contains(&"-Dexpression=project.artifact.file".into()));
|
||||
assert!(
|
||||
plan.args.iter().any(|a| a.ends_with("base with spaces/artifact-path.txt")
|
||||
|| a.ends_with("base with spaces\\artifact-path.txt"))
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn maven_module_build_includes_reactor_dependencies() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(tmp.path().join("web")).unwrap();
|
||||
fs::write(tmp.path().join("pom.xml"), "<project><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>web</module></modules></project>").unwrap();
|
||||
fs::write(tmp.path().join("web/pom.xml"), "<project><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version></parent><artifactId>web</artifactId><packaging>war</packaging></project>").unwrap();
|
||||
let model = crate::load(tmp.path(), &tmp.path().join("cache"), None);
|
||||
let plan = build(tmp.path(), &model, "maven:web/pom.xml", &tmp.path().join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "web", "-am"]);
|
||||
}
|
||||
#[test]
|
||||
fn gradle_war_uses_archive_provider_and_ignores_comments() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fs::write(
|
||||
tmp.path().join("build.gradle.kts"),
|
||||
"plugins { war }\ntasks.war { archiveFileName.set(\"custom.war\") }",
|
||||
)
|
||||
.unwrap();
|
||||
let model = crate::load(tmp.path(), &tmp.path().join("cache"), None);
|
||||
let a = artifacts(tmp.path(), &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
|
||||
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
|
||||
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ use std::sync::Arc;
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum IdeEvent {
|
||||
/// Project window membership or selection changed.
|
||||
WindowGroupsChanged,
|
||||
/// Files or directories changed on disk (after debouncing, ignore rules applied).
|
||||
FsChanged {
|
||||
created: Vec<crate::IpcPath>,
|
||||
@@ -115,6 +117,8 @@ pub enum IdeEvent {
|
||||
id: u64,
|
||||
prompt: String,
|
||||
kind: AskpassKind,
|
||||
/// The dialog offers "Remember" for the answer (git HTTPS passwords).
|
||||
remember: bool,
|
||||
},
|
||||
/// Prompt `id` was answered (in any window) or gave up.
|
||||
AskpassDone {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod remote_settings;
|
||||
pub mod settings;
|
||||
pub mod task;
|
||||
pub mod text;
|
||||
pub mod tool_path;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ pub struct CustomKeymap {
|
||||
pub struct GeneralSettings {
|
||||
pub reopen_last_project: bool,
|
||||
pub confirm_exit: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same`.
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Where the IDE looks up the executables it runs: language servers, the tools
|
||||
//! their settings come from, installers. An app started from the desktop gets a
|
||||
//! minimal `PATH`, and version managers set theirs up in shell rc files.
|
||||
|
||||
use crate::process::{host_var_os, login_env};
|
||||
use crate::version_managers;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
/// launchers, their settings hooks and tool detection all look here, so a settings
|
||||
/// hook finds the executable its server is launched from.
|
||||
pub fn search_path() -> OsString {
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let shell_path = login_env().and_then(|env| env.iter().find(|(k, _)| k == "PATH").map(|(_, v)| v.clone()));
|
||||
let shims: Vec<PathBuf> = version_managers::managers().iter().map(|m| m.shims()).collect();
|
||||
let dirs = search_dirs(host_var_os("PATH").as_deref(), shell_path.as_deref(), home.as_deref(), &shims);
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolves a command on the shared path, or an explicit path relative to `root`.
|
||||
pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBuf> {
|
||||
let path = Path::new(command);
|
||||
let explicit = path.parent().is_some_and(|p| !p.as_os_str().is_empty());
|
||||
let pathext = host_var_os("PATHEXT");
|
||||
let names = crate::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(OsStr::to_str));
|
||||
let dirs = if explicit {
|
||||
vec![root.to_path_buf()]
|
||||
} else {
|
||||
std::env::split_paths(search).filter(|p| !p.as_os_str().is_empty()).map(|p| root.join(p)).collect()
|
||||
};
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
if !metadata.is_file() {
|
||||
return false;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
metadata.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
true
|
||||
}
|
||||
|
||||
/// [`search_path`]'s directories, in order and once each. Only absolute ones: a
|
||||
/// relative entry (`.`, `node_modules/.bin`) resolves against the project, which
|
||||
/// could then supply the tools the IDE runs. One that can't be joined (a `:` in a
|
||||
/// directory name) is left out rather than failing the whole path.
|
||||
fn search_dirs(
|
||||
process_path: Option<&OsStr>,
|
||||
shell_path: Option<&OsStr>,
|
||||
home: Option<&Path>,
|
||||
shims: &[PathBuf],
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = process_path.into_iter().chain(shell_path).flat_map(std::env::split_paths).collect();
|
||||
if let Some(home) = home {
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
dirs.extend(home.map(|h| h.join(".pyenv/shims")));
|
||||
dirs.extend(shims.iter().cloned());
|
||||
dirs.extend(SYSTEM_DIRS.iter().map(PathBuf::from));
|
||||
let mut seen = HashSet::new();
|
||||
dirs.retain(|d| d.is_absolute() && std::env::join_paths([d]).is_ok() && seen.insert(d.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Tool directories below the home directory.
|
||||
const USER_DIRS: &[&str] = &[
|
||||
".cargo/bin",
|
||||
".local/bin",
|
||||
"go/bin",
|
||||
".bun/bin",
|
||||
".deno/bin",
|
||||
".npm-global/bin",
|
||||
".volta/bin",
|
||||
// Set up in shell rc files: fnm's default Node and pnpm's global bin (Linux, then macOS).
|
||||
".local/share/fnm/aliases/default/bin",
|
||||
"Library/Application Support/fnm/aliases/default/bin",
|
||||
".fnm/aliases/default/bin",
|
||||
".local/share/pnpm/bin",
|
||||
".local/share/pnpm",
|
||||
"Library/pnpm/bin",
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// The `bin` directories of nvm's Node versions in `dir`, newest first.
|
||||
fn nvm_bins(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut versions: Vec<(Vec<u64>, PathBuf)> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| (version_key(&e.file_name().to_string_lossy()), e.path().join("bin")))
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.into_iter().rev().map(|(_, bin)| bin).collect()
|
||||
}
|
||||
|
||||
/// `v22.10.1` as `[22, 10, 1]`: v22 is newer than v9, v20.10 newer than v20.9.
|
||||
fn version_key(name: &str) -> Vec<u64> {
|
||||
name.trim_start_matches('v').split('.').map(|n| n.parse().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn commands_resolve_on_path_and_explicit_paths_under_root() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("bin");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
let name = if cfg!(windows) { "ngserver.cmd" } else { "ngserver" };
|
||||
std::fs::write(bin.join(name), "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(bin.join(name), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&bin]).unwrap();
|
||||
assert_eq!(find_command("ngserver", &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command("bin/ngserver", &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command(bin.join(name).to_str().unwrap(), &search, dir.path()), Some(bin.join(name)));
|
||||
assert_eq!(find_command("absent", &search, dir.path()), None);
|
||||
for command in ["bin/ngserver", bin.join(name).to_str().unwrap()] {
|
||||
assert_eq!(find_command(command, OsStr::new(""), dir.path()), Some(bin.join(name)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_executable_files_do_not_shadow_commands() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dirs = [tmp.path().join("first"), tmp.path().join("second")];
|
||||
for (dir, mode) in dirs.iter().zip([0o644, 0o755]) {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
let file = dir.join("ngserver");
|
||||
std::fs::write(&file, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(file, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
}
|
||||
let path = std::env::join_paths(&dirs).unwrap();
|
||||
assert_eq!(find_command("ngserver", &path, tmp.path()), Some(dirs[1].join("ngserver")));
|
||||
assert_eq!(find_command("first/ngserver", &path, tmp.path()), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn search_dirs_put_the_process_path_first_and_shims_after_real_tools() {
|
||||
let shims = [PathBuf::from("/home/me/.local/share/mise/shims"), "/home/me/.asdf/shims".into()];
|
||||
let dirs = search_dirs(
|
||||
Some(OsStr::new("/usr/bin:.:node_modules/.bin:/opt/tools")),
|
||||
// nushell prints `$PATH` as is.
|
||||
Some(OsStr::new("$PATH:/opt/tools:/home/me/.asdf/shims")),
|
||||
Some(Path::new("/home/me")),
|
||||
&shims,
|
||||
);
|
||||
let at = |d: &str| dirs.iter().position(|p| p == Path::new(d)).unwrap();
|
||||
assert_eq!(dirs[..3], [PathBuf::from("/usr/bin"), "/opt/tools".into(), "/home/me/.asdf/shims".into()]);
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nvm_versions_newest_first() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-nvm-{}", std::process::id()));
|
||||
for v in ["v9.11.2", "v20.9.0", "v22.1.0", "v20.10.0"] {
|
||||
std::fs::create_dir_all(dir.join(v).join("bin")).unwrap();
|
||||
}
|
||||
let bins = nvm_bins(&dir);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let names: Vec<_> = bins.iter().map(|b| b.parent().unwrap().file_name().unwrap().to_owned()).collect();
|
||||
assert_eq!(names, ["v22.1.0", "v20.10.0", "v20.9.0", "v9.11.2"]);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tempfile.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
|
||||
@@ -63,6 +63,12 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
|
||||
"tcp",
|
||||
"Install the CodeLLDB adapter (https://github.com/vadimcn/codelldb/releases) and put `codelldb` on PATH",
|
||||
),
|
||||
"kotlin-debug-adapter" => cfg(
|
||||
"kotlin-debug-adapter",
|
||||
&[],
|
||||
"stdio",
|
||||
"Install the Kotlin Debug Adapter from Settings > Language Servers",
|
||||
),
|
||||
"debugpy" => cfg("python3", &["-m", "debugpy.adapter"], "stdio", "pip install debugpy"),
|
||||
"js-debug" => cfg(
|
||||
"js-debug-adapter",
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Package-aligned sources for fwcd's path-based class resolver. Never write into a project.
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub const ADAPTER: &str = "kotlin-debug-adapter";
|
||||
|
||||
pub struct SourceMirror {
|
||||
dir: tempfile::TempDir,
|
||||
paths: HashMap<PathBuf, PathBuf>,
|
||||
copies: Vec<(PathBuf, PathBuf)>,
|
||||
source_dir: PathBuf,
|
||||
roots: HashMap<PathBuf, usize>,
|
||||
}
|
||||
|
||||
impl SourceMirror {
|
||||
pub fn create(project: &Path) -> IdeResult<Self> {
|
||||
let base = fs::canonicalize(std::env::temp_dir())?;
|
||||
// Check before creating anything, including when TMPDIR points into a project.
|
||||
if base.starts_with(fs::canonicalize(project)?) {
|
||||
return Err(IdeError::invalid("Kotlin source mirror must be outside the project"));
|
||||
}
|
||||
let dir = tempfile::Builder::new().prefix("openidea-kotlin-").tempdir_in(base)?;
|
||||
let source_dir = if project.join("src").is_dir() { project.join("src") } else { project.to_owned() };
|
||||
let mut mirror = Self {
|
||||
dir,
|
||||
paths: HashMap::new(),
|
||||
copies: Vec::new(),
|
||||
source_dir: source_dir.clone(),
|
||||
roots: HashMap::new(),
|
||||
};
|
||||
mirror.scan(&source_dir)?;
|
||||
Ok(mirror)
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
self.dir.path()
|
||||
}
|
||||
|
||||
fn scan(&mut self, dir: &Path) -> IdeResult<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_dir() {
|
||||
if !matches!(
|
||||
entry.file_name().to_str(),
|
||||
Some(".git" | ".gradle" | "build" | "target" | "node_modules" | ".idea" | ".openidea")
|
||||
) {
|
||||
self.scan(&path)?;
|
||||
}
|
||||
} else if matches!(path.extension().and_then(|s| s.to_str()), Some("kt" | "java")) {
|
||||
self.add(&path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add(&mut self, real: &Path) -> IdeResult<()> {
|
||||
if self.paths.contains_key(real) {
|
||||
return Ok(());
|
||||
}
|
||||
let Ok(text) = fs::read_to_string(real) else {
|
||||
tracing::debug!("Kotlin debug mirror: skipping unreadable {}", real.display());
|
||||
return Ok(());
|
||||
};
|
||||
let language = if real.extension().is_some_and(|e| e == "java") { "java" } else { "kotlin" };
|
||||
let relative = real.strip_prefix(&self.source_dir).unwrap_or(real);
|
||||
let mut components = relative.components();
|
||||
let source_set = components.next().map(|c| PathBuf::from(c.as_os_str())).unwrap_or_default();
|
||||
let next_root = self.roots.len();
|
||||
let index = *self.roots.entry(source_set).or_insert(next_root);
|
||||
let mut mirror = self.root().join(format!("root{index}")).join("src/main").join(language);
|
||||
for part in package(&text).split('.').filter(|s| !s.is_empty()) {
|
||||
if part == ".." || part.contains(['/', '\\']) {
|
||||
tracing::debug!("Kotlin debug mirror: skipping {} (invalid package)", real.display());
|
||||
return Ok(());
|
||||
}
|
||||
mirror.push(part);
|
||||
}
|
||||
mirror.push(real.file_name().ok_or_else(|| IdeError::invalid("Source has no filename"))?);
|
||||
// Same package and file name in one source set (e.g. main and test of a module):
|
||||
// the first wins; breakpoints in the other stay unverified instead of failing the session.
|
||||
if self.paths.values().any(|p| p == &mirror) {
|
||||
tracing::debug!("Kotlin debug mirror: skipping ambiguous {}", real.display());
|
||||
return Ok(());
|
||||
}
|
||||
fs::create_dir_all(mirror.parent().unwrap())?;
|
||||
if link(real, &mirror).is_err() {
|
||||
fs::copy(real, &mirror)?;
|
||||
self.copies.push((real.to_owned(), mirror.clone()));
|
||||
}
|
||||
self.paths.insert(real.to_owned(), mirror);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn adapter_path(&self, real: &Path) -> Option<PathBuf> {
|
||||
self.paths.get(real).cloned()
|
||||
}
|
||||
pub fn client_path(&self, mirror: &Path) -> Option<PathBuf> {
|
||||
self.paths.iter().find_map(|(real, p)| (p == mirror).then(|| real.clone()))
|
||||
}
|
||||
pub fn refresh(&mut self) -> IdeResult<()> {
|
||||
for (real, mirror) in &self.copies {
|
||||
if real.is_file() {
|
||||
fs::copy(real, mirror)?;
|
||||
}
|
||||
}
|
||||
self.scan(&self.source_dir.clone())
|
||||
}
|
||||
pub fn translate(&self, value: &mut Value) {
|
||||
match value {
|
||||
Value::Object(obj) => {
|
||||
if let Some(path) = obj.get("path").and_then(Value::as_str).and_then(|p| self.client_path(Path::new(p)))
|
||||
{
|
||||
obj.insert("path".into(), Value::String(path.to_string_lossy().into_owned()));
|
||||
}
|
||||
for child in obj.values_mut() {
|
||||
self.translate(child);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for child in items {
|
||||
self.translate(child);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn link(real: &Path, mirror: &Path) -> std::io::Result<()> {
|
||||
std::os::unix::fs::symlink(real, mirror)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn link(real: &Path, mirror: &Path) -> std::io::Result<()> {
|
||||
std::os::windows::fs::symlink_file(real, mirror)
|
||||
}
|
||||
|
||||
// Remove comments before reading the package directive (including nested Kotlin block comments).
|
||||
fn package(text: &str) -> String {
|
||||
let mut clean = String::new();
|
||||
let mut chars = text.chars().peekable();
|
||||
let mut depth = 0;
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '/' && chars.peek() == Some(&'*') {
|
||||
chars.next();
|
||||
depth += 1;
|
||||
clean.push(' ');
|
||||
} else if depth > 0 && c == '*' && chars.peek() == Some(&'/') {
|
||||
chars.next();
|
||||
depth -= 1;
|
||||
} else if depth == 0 && c == '/' && chars.peek() == Some(&'/') {
|
||||
for c in chars.by_ref() {
|
||||
if c == '\n' {
|
||||
clean.push('\n');
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if depth == 0 {
|
||||
clean.push(c);
|
||||
}
|
||||
}
|
||||
clean
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let rest = line.trim().strip_prefix("package")?;
|
||||
if !rest.starts_with(char::is_whitespace) {
|
||||
return None;
|
||||
}
|
||||
Some(rest.split(';').next().unwrap_or_default().trim().replace('`', ""))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn external_mirror_round_trip_and_cleanup() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let real = project.path().join("Main.kt");
|
||||
fs::write(&real, "/* package wrong */\npackage org.example\nfun main() {}\n").unwrap();
|
||||
let mirror = SourceMirror::create(project.path()).unwrap();
|
||||
let path = mirror.adapter_path(&real).unwrap();
|
||||
assert!(!path.starts_with(project.path()));
|
||||
assert!(path.ends_with("src/main/kotlin/org/example/Main.kt"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), fs::read_to_string(&real).unwrap());
|
||||
let mut payload =
|
||||
serde_json::json!({"stackFrames": [{"source": {"path": path}, "line": 6}], "source": {"path": path}});
|
||||
mirror.translate(&mut payload);
|
||||
assert_eq!(payload["stackFrames"][0]["source"]["path"], real.to_string_lossy().as_ref());
|
||||
assert_eq!(payload["source"]["path"], real.to_string_lossy().as_ref());
|
||||
let root = mirror.root().to_owned();
|
||||
drop(mirror);
|
||||
assert!(!root.exists());
|
||||
assert!(real.exists());
|
||||
}
|
||||
#[test]
|
||||
fn copies_refresh_after_save() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let real = project.path().join("Main.java");
|
||||
fs::write(&real, "package example;\nclass Main {}\n").unwrap();
|
||||
let mut mirror = SourceMirror::create(project.path()).unwrap();
|
||||
let path = mirror.adapter_path(&real).unwrap();
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::copy(&real, &path).unwrap();
|
||||
mirror.copies.push((real.clone(), path.clone()));
|
||||
fs::write(&real, "package example;\nclass Main { int i; }\n").unwrap();
|
||||
mirror.refresh().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), fs::read(&real).unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Keep a suspended JVM stopped until Kotlin's adapter has installed its listeners.
|
||||
//! The official 0.4.4 adapter resumes VMStart while constructing its debuggee, before
|
||||
//! installing breakpoint hooks. DAP attach completes only after those hooks exist.
|
||||
use ide_core::IdeResult;
|
||||
use std::{io, time::Duration};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::oneshot,
|
||||
task::JoinHandle,
|
||||
};
|
||||
|
||||
pub(crate) struct StartupRelay {
|
||||
release: Option<oneshot::Sender<()>>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl StartupRelay {
|
||||
pub async fn start(host: String, port: u16) -> IdeResult<(Self, u16)> {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).await?;
|
||||
let local = listener.local_addr()?.port();
|
||||
let (release, ready) = oneshot::channel();
|
||||
let task = tokio::spawn(async move {
|
||||
let connect = async {
|
||||
let (adapter, _) = listener.accept().await?;
|
||||
let jvm = TcpStream::connect((host.as_str(), port)).await?;
|
||||
adapter.set_nodelay(true)?;
|
||||
jvm.set_nodelay(true)?;
|
||||
Ok::<_, io::Error>((adapter, jvm))
|
||||
};
|
||||
if let Ok(Ok((adapter, jvm))) = tokio::time::timeout(Duration::from_secs(60), connect).await {
|
||||
let (mut ar, mut aw) = adapter.into_split();
|
||||
let (mut jr, mut jw) = jvm.into_split();
|
||||
let upstream = forward(&mut ar, &mut jw, ready);
|
||||
let downstream = tokio::io::copy(&mut jr, &mut aw);
|
||||
// Close both sockets as soon as either side disconnects.
|
||||
tokio::select! {
|
||||
r = upstream => if let Err(e) = r { tracing::debug!("Kotlin JDWP relay: {e}"); },
|
||||
_ = downstream => {},
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok((Self { release: Some(release), task }, local))
|
||||
}
|
||||
|
||||
pub fn release(&mut self) {
|
||||
if let Some(ready) = self.release.take() {
|
||||
let _ = ready.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StartupRelay {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn packet(reader: &mut (impl AsyncRead + Unpin)) -> io::Result<Vec<u8>> {
|
||||
let mut header = [0; 11];
|
||||
reader.read_exact(&mut header).await?;
|
||||
let len = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize;
|
||||
if !(11..=16 * 1024 * 1024).contains(&len) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid JDWP packet length"));
|
||||
}
|
||||
let mut packet = vec![0; len];
|
||||
packet[..11].copy_from_slice(&header);
|
||||
reader.read_exact(&mut packet[11..]).await?;
|
||||
Ok(packet)
|
||||
}
|
||||
|
||||
async fn forward(
|
||||
reader: &mut (impl AsyncRead + Unpin),
|
||||
writer: &mut (impl AsyncWrite + Unpin),
|
||||
mut ready: oneshot::Receiver<()>,
|
||||
) -> io::Result<()> {
|
||||
let mut handshake = [0; 14];
|
||||
reader.read_exact(&mut handshake).await?;
|
||||
if &handshake != b"JDWP-Handshake" {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid JDWP handshake"));
|
||||
}
|
||||
writer.write_all(&handshake).await?;
|
||||
let mut released = false;
|
||||
let mut held: Vec<Vec<u8>> = Vec::new();
|
||||
loop {
|
||||
// Retain the in-flight read when attach completes, including partial packets.
|
||||
let read = packet(reader);
|
||||
tokio::pin!(read);
|
||||
let packet = tokio::select! {
|
||||
result = &mut read => result?,
|
||||
result = &mut ready, if !released => {
|
||||
result.map_err(|_| io::Error::new(io::ErrorKind::ConnectionAborted, "Kotlin attach cancelled"))?;
|
||||
released = true;
|
||||
for packet in held.drain(..) {
|
||||
writer.write_all(&packet).await?;
|
||||
}
|
||||
read.await?
|
||||
}
|
||||
};
|
||||
// JDWP VirtualMachine.Resume (1/9), ThreadReference.Resume (11/3).
|
||||
// Other commands must proceed: attach itself queries threads and installs requests.
|
||||
if !released && packet[8] == 0 && matches!((packet[9], packet[10]), (1, 9) | (11, 3)) {
|
||||
if held.len() >= 1024 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Too many pending JDWP resumes"));
|
||||
}
|
||||
held.push(packet);
|
||||
} else {
|
||||
writer.write_all(&packet).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn command(id: u8, set: u8, cmd: u8) -> Vec<u8> {
|
||||
vec![0, 0, 0, 11, 0, 0, 0, id, 0, set, cmd]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn holds_resumes_but_allows_setup_and_preserves_partial_reads() {
|
||||
let (mut adapter, mut reader) = tokio::io::duplex(4096);
|
||||
let (mut writer, mut jvm) = tokio::io::duplex(4096);
|
||||
let (release, ready) = oneshot::channel();
|
||||
let task = tokio::spawn(async move { forward(&mut reader, &mut writer, ready).await });
|
||||
adapter.write_all(b"JDWP-Handshake").await.unwrap();
|
||||
let mut handshake = [0; 14];
|
||||
jvm.read_exact(&mut handshake).await.unwrap();
|
||||
assert_eq!(&handshake, b"JDWP-Handshake");
|
||||
let resume = command(1, 1, 9);
|
||||
let thread_resume = command(2, 11, 3);
|
||||
let setup = command(3, 1, 4);
|
||||
adapter.write_all(&resume).await.unwrap();
|
||||
adapter.write_all(&thread_resume).await.unwrap();
|
||||
adapter.write_all(&setup).await.unwrap();
|
||||
assert_eq!(packet(&mut jvm).await.unwrap(), setup);
|
||||
let next = command(4, 1, 9);
|
||||
adapter.write_all(&next[..6]).await.unwrap();
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(packet(&mut jvm).await.unwrap(), resume);
|
||||
assert_eq!(packet(&mut jvm).await.unwrap(), thread_resume);
|
||||
adapter.write_all(&next[6..]).await.unwrap();
|
||||
assert_eq!(packet(&mut jvm).await.unwrap(), next);
|
||||
drop(adapter);
|
||||
assert!(task.await.unwrap().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_session_closes_relay() {
|
||||
let (relay, port) = StartupRelay::start("127.0.0.1".into(), 1).await.unwrap();
|
||||
let mut adapter = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
drop(relay);
|
||||
let result = tokio::time::timeout(Duration::from_secs(1), adapter.read_u8()).await.unwrap();
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_packet_lengths() {
|
||||
for len in [0_u32, 10, 16 * 1024 * 1024 + 1] {
|
||||
let mut bytes = command(1, 1, 9);
|
||||
bytes[..4].copy_from_slice(&len.to_be_bytes());
|
||||
assert_eq!(packet(&mut bytes.as_slice()).await.unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
pub mod jdwp;
|
||||
pub mod kotlin;
|
||||
mod kotlin_jdwp;
|
||||
mod session;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -563,6 +565,14 @@ impl DebugManager {
|
||||
let dbg = adapter::find_config(&self.languages, &config.adapter)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("unknown debug adapter `{}`", config.adapter)))?;
|
||||
let mut spec = adapter::resolve(&dbg, cwd.clone());
|
||||
if config.adapter == kotlin::ADAPTER
|
||||
&& let Some(home) = arguments
|
||||
.as_object_mut()
|
||||
.and_then(|o| o.remove("__adapterJavaHome"))
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
{
|
||||
spec.env.push(("JAVA_HOME".into(), home));
|
||||
}
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
@@ -722,7 +732,19 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fn configure(&self, s: &Arc<Session>, arguments: Value) -> IdeResult<()> {
|
||||
async fn configure(&self, s: &Arc<Session>, mut arguments: Value) -> IdeResult<()> {
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
let project = arguments
|
||||
.get("projectRoot")
|
||||
.and_then(Value::as_str)
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| s.spec.cwd.clone());
|
||||
let mirror = tokio::task::spawn_blocking(move || kotlin::SourceMirror::create(&project))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
arguments["projectRoot"] = json!(mirror.root());
|
||||
*s.kotlin_mirror.lock() = Some(mirror);
|
||||
}
|
||||
let caps = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
@@ -749,8 +771,32 @@ impl DebugManager {
|
||||
.await?;
|
||||
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
|
||||
|
||||
// The Kotlin adapter ignores the resolved classpath and project runtime on launch.
|
||||
let request = if s.adapter == kotlin::ADAPTER && s.request == "launch" {
|
||||
session::start_kotlin_debuggee(s, &mut arguments).await?;
|
||||
"attach"
|
||||
} else {
|
||||
&s.request
|
||||
};
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
let host = arguments
|
||||
.get("hostName")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::invalid("Missing Kotlin JDWP host"))?
|
||||
.to_owned();
|
||||
let port = arguments
|
||||
.get("port")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|p| u16::try_from(p).ok())
|
||||
.filter(|p| *p != 0)
|
||||
.ok_or_else(|| IdeError::invalid("Invalid Kotlin JDWP port"))?;
|
||||
let (relay, port) = kotlin_jdwp::StartupRelay::start(host, port).await?;
|
||||
*s.kotlin_relay.lock() = Some(relay);
|
||||
arguments["hostName"] = json!("127.0.0.1");
|
||||
arguments["port"] = json!(port);
|
||||
}
|
||||
// Many adapters answer `launch` only after `configurationDone`, so don't wait for it yet.
|
||||
let launch = s.conn.send_request(&s.request, arguments)?;
|
||||
let launch = s.conn.send_request(request, arguments)?;
|
||||
let mut launch = Box::pin(async move { launch.await.unwrap_or(Err(DapError::Closed)) });
|
||||
let mut initialized = s.initialized.subscribe();
|
||||
let mut launch_result = None;
|
||||
@@ -780,6 +826,7 @@ impl DebugManager {
|
||||
s.emit(ide_core::event::DebugEvent::BreakpointsChanged { path: path.into() });
|
||||
}
|
||||
}
|
||||
Err(e) if s.adapter == kotlin::ADAPTER => return Err(e.into()),
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
@@ -802,7 +849,11 @@ impl DebugManager {
|
||||
let _ = self.send_exception_breakpoints(s).await;
|
||||
}
|
||||
if s.supports("supportsConfigurationDoneRequest") {
|
||||
s.conn.request_timeout("configurationDone", Value::Null, REQUEST_TIMEOUT).await?;
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
drop(s.conn.send_request("configurationDone", json!({}))?);
|
||||
} else {
|
||||
s.conn.request_timeout("configurationDone", Value::Null, REQUEST_TIMEOUT).await?;
|
||||
}
|
||||
}
|
||||
s.configured.store(true, Ordering::Release);
|
||||
if launch_result.is_none() {
|
||||
@@ -813,6 +864,9 @@ impl DebugManager {
|
||||
Err(_) => return Err(DapError::Timeout(s.request.clone()).into()),
|
||||
}
|
||||
}
|
||||
if let Some(relay) = s.kotlin_relay.lock().as_mut() {
|
||||
relay.release();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -869,6 +923,7 @@ impl DebugManager {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
}
|
||||
Err(e) if s.adapter == kotlin::ADAPTER => return Err(e.into()),
|
||||
Err(e) => tracing::debug!("setBreakpoints on session {} failed: {e}", s.id.0),
|
||||
}
|
||||
}
|
||||
@@ -886,6 +941,23 @@ impl DebugManager {
|
||||
Ok(states)
|
||||
}
|
||||
|
||||
/// Refresh fallback copies after an editor save.
|
||||
pub async fn refresh_source_mirrors(&self, owner: &str) -> IdeResult<()> {
|
||||
let sessions: Vec<_> = self.sessions.lock().values().filter(|s| s.owner.key == owner).cloned().collect();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
for s in sessions {
|
||||
if let Some(mirror) = s.kotlin_mirror.lock().as_mut()
|
||||
&& let Err(e) = mirror.refresh()
|
||||
{
|
||||
tracing::warn!("Could not refresh Kotlin debug sources: {e}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Last known verification states of a file's breakpoints (after `BreakpointsChanged`).
|
||||
pub fn breakpoint_states(&self, path: &Path) -> Vec<BreakpointState> {
|
||||
self.states.lock().get(path).cloned().unwrap_or_default()
|
||||
|
||||
@@ -54,6 +54,8 @@ pub(crate) struct Session {
|
||||
/// Resolved path → the path as the IDE knows it, for adapters given resolved paths.
|
||||
resolved_paths: Mutex<HashMap<PathBuf, PathBuf>>,
|
||||
progress: Mutex<HashMap<String, TaskId>>,
|
||||
pub kotlin_relay: Mutex<Option<crate::kotlin_jdwp::StartupRelay>>,
|
||||
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
|
||||
}
|
||||
|
||||
/// Adapters that only match files by their resolved path: Godot maps a script to
|
||||
@@ -95,6 +97,8 @@ impl Session {
|
||||
breakpoint_ids: Mutex::new(HashMap::new()),
|
||||
resolved_paths: Mutex::new(HashMap::new()),
|
||||
progress: Mutex::new(HashMap::new()),
|
||||
kotlin_relay: Mutex::new(None),
|
||||
kotlin_mirror: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +108,14 @@ impl Session {
|
||||
|
||||
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
|
||||
pub fn adapter_path(&self, path: &Path) -> PathBuf {
|
||||
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
|
||||
return path;
|
||||
}
|
||||
if self.adapter == "java-debug" {
|
||||
let native = java_source_path(&path.to_string_lossy());
|
||||
self.resolved_paths.lock().insert(native.clone(), path.to_path_buf());
|
||||
return native;
|
||||
}
|
||||
if !RESOLVES_PATHS.contains(&self.adapter.as_str()) {
|
||||
return path.to_path_buf();
|
||||
}
|
||||
@@ -118,7 +130,14 @@ impl Session {
|
||||
|
||||
/// A path from the adapter as the IDE knows it (undoes [`Session::adapter_path`]).
|
||||
pub fn client_path(&self, path: &str) -> Option<PathBuf> {
|
||||
self.resolved_paths.lock().get(Path::new(path)).cloned()
|
||||
if let Some(real) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.client_path(Path::new(path))) {
|
||||
return Some(real);
|
||||
}
|
||||
let key = if self.adapter == "java-debug" { java_source_path(path) } else { PathBuf::from(path) };
|
||||
self.resolved_paths.lock().get(&key).cloned().or_else(|| {
|
||||
(self.adapter == "java-debug" && is_windows_source_path(path))
|
||||
.then(|| PathBuf::from(path.replace('\\', "/")))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn supports(&self, cap: &str) -> bool {
|
||||
@@ -236,6 +255,7 @@ impl Session {
|
||||
|
||||
/// Kills the adapter and every debuggee we started.
|
||||
pub fn kill_processes(&self) {
|
||||
self.kotlin_relay.lock().take();
|
||||
if let Some(mut c) = self.adapter_process.lock().take() {
|
||||
let _ = c.start_kill();
|
||||
}
|
||||
@@ -245,6 +265,19 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
// java-debug treats a forward-slash drive path as a URI (scheme "C").
|
||||
// Keep DAP path mode, but use native Windows separators for Java source lookup.
|
||||
fn is_windows_source_path(path: &str) -> bool {
|
||||
let bytes = path.as_bytes();
|
||||
(bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && matches!(bytes[2], b'/' | b'\\'))
|
||||
|| path.starts_with("//")
|
||||
|| path.starts_with(r"\\")
|
||||
}
|
||||
|
||||
fn java_source_path(path: &str) -> PathBuf {
|
||||
if is_windows_source_path(path) { PathBuf::from(path.replace('/', r"\")) } else { PathBuf::from(path) }
|
||||
}
|
||||
|
||||
fn with_conditions(v: &mut Value, condition: Option<&str>, hit_condition: Option<&str>) {
|
||||
if let Some(c) = condition.filter(|c| !c.trim().is_empty()) {
|
||||
v["condition"] = c.into();
|
||||
@@ -297,7 +330,10 @@ pub(crate) async fn event_loop(
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, body: Value) {
|
||||
async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut body: Value) {
|
||||
if let Some(mirror) = s.kotlin_mirror.lock().as_ref() {
|
||||
mirror.translate(&mut body);
|
||||
}
|
||||
let int = |k: &str| body.get(k).and_then(Value::as_i64);
|
||||
let str_ = |k: &str| body.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
match event {
|
||||
@@ -486,3 +522,74 @@ fn forward_output<R: AsyncRead + Unpin + Send + 'static>(s: &Session, mut stream
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
|
||||
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
let port = crate::adapter::free_port()?;
|
||||
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
|
||||
let strings = |key: &str| -> Vec<String> {
|
||||
args.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let classpath =
|
||||
std::env::join_paths(strings("classPaths")).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
|
||||
let mut cmd = tokio::process::Command::new(java);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(strings("vmArguments"))
|
||||
.arg(format!("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{port}"))
|
||||
.arg("-cp")
|
||||
.arg(classpath);
|
||||
let modules = strings("modulePaths");
|
||||
if !modules.is_empty() {
|
||||
cmd.arg("--module-path")
|
||||
.arg(std::env::join_paths(modules).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?);
|
||||
}
|
||||
cmd.arg(
|
||||
args.get("mainClass")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?,
|
||||
)
|
||||
.args(strings("programArgs"))
|
||||
.current_dir(&s.spec.cwd)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
if let Some(v) = v.as_str() {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut child = cmd.spawn()?;
|
||||
if let Some(err) = child.stderr.take() {
|
||||
forward_output(s, err, "stderr");
|
||||
}
|
||||
let mut stdout =
|
||||
BufReader::new(child.stdout.take().ok_or_else(|| ide_core::IdeError::internal("Missing JVM stdout"))?);
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if stdout.read_line(&mut line).await? == 0 {
|
||||
return Err(ide_core::IdeError::unavailable("JVM exited before starting its debug listener"));
|
||||
}
|
||||
if line.contains("Listening for transport dt_socket") {
|
||||
return Ok(());
|
||||
}
|
||||
s.emit(DebugEvent::Output { category: "stdout".into(), output: line });
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ide_core::IdeError::unavailable("JVM did not start its debug listener"))??;
|
||||
forward_output(s, stdout, "stdout");
|
||||
s.debuggees.lock().push(child);
|
||||
args["hostName"] = json!("127.0.0.1");
|
||||
args["port"] = json!(port);
|
||||
args["timeout"] = json!(10000);
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,6 +15,8 @@ struct Script {
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
/// Send a `startDebugging` reverse request (child session) when a non-child `launch` arrives.
|
||||
start_debugging: bool,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
}
|
||||
|
||||
struct FakeLauncher {
|
||||
@@ -130,7 +132,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"value": format!("{}!", msg["arguments"]["value"].as_str().unwrap()), "type": "int"}))
|
||||
}
|
||||
"configurationDone" => {
|
||||
ok!(msg, Value::Null);
|
||||
if !script.ignore_configuration_done {
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
if let Some(l) = pending_launch.take() {
|
||||
send!(json!({"type": "response", "request_seq": l, "command": "launch", "success": true}));
|
||||
}
|
||||
@@ -139,14 +143,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
send!(
|
||||
json!({"type": "event", "event": "breakpoint", "body": {"reason": "changed", "breakpoint": {"id": 1, "verified": false, "message": "moved", "line": 9}}})
|
||||
json!({"type": "event", "event": "breakpoint", "body": {"reason": "changed", "breakpoint": {"id": 1, "verified": false, "message": "moved", "line": 9, "source": {"path": script.source_path}}}})
|
||||
);
|
||||
}
|
||||
"threads" => ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]})),
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
{"id": 10, "name": "main", "line": 5, "column": 3, "source": {"path": "/p/a.py"}},
|
||||
{"id": 10, "name": "main", "line": 5, "column": 3, "source": {"path": script.source_path.as_deref().unwrap_or("/p/a.py")}},
|
||||
{"id": 11, "name": "lib", "line": 1, "column": 1, "source": {"path": "/usr/lib/x.py", "presentationHint": "deemphasize"}},
|
||||
]})
|
||||
),
|
||||
@@ -1016,3 +1020,122 @@ fn root_and_address_placeholders() {
|
||||
assert_eq!(adapter::parse_address("[::1]:6006"), Some(("::1".into(), 6006)));
|
||||
assert_eq!(adapter::parse_address("6006"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kotlin_configures_without_configuration_done_response() {
|
||||
let h = harness(Script { ignore_configuration_done: true, ..Default::default() });
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
config.cwd = Some(project.path().to_owned().into());
|
||||
config.extra_json = Some(json!({"projectRoot": project.path(), "hostName": "127.0.0.1", "port": 5005}).to_string());
|
||||
let id = tokio::time::timeout(Duration::from_secs(2), h.start(config)).await.unwrap().unwrap();
|
||||
let root = PathBuf::from(h.request("attach")["arguments"]["projectRoot"].as_str().unwrap());
|
||||
assert!(!root.starts_with(project.path()));
|
||||
let request = h.request("setBreakpoints");
|
||||
assert_eq!(request["arguments"]["source"]["name"], "Main.kt");
|
||||
let mapped = PathBuf::from(request["arguments"]["source"]["path"].as_str().unwrap());
|
||||
assert!(mapped.starts_with(&root));
|
||||
assert!(mapped.is_file());
|
||||
assert_eq!(h.manager.session(id).unwrap().client_path(mapped.to_str().unwrap()), Some(path));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
/// Requires a compiled no-delay reporter fixture (Main.kt, package org.example,
|
||||
/// loop at line 5, println(i) at line 6), and the unmodified official adapter.
|
||||
/// KOTLIN_PROBE_CONFIG is a LaunchConfig JSON file; KOTLIN_PROBE_ADAPTER is its executable.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires official Kotlin adapter and compiled reporter fixture"]
|
||||
async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let config: LaunchConfig = serde_json::from_slice(
|
||||
&std::fs::read(std::env::var("KOTLIN_PROBE_CONFIG").expect("KOTLIN_PROBE_CONFIG")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let adapter = std::env::var("KOTLIN_PROBE_ADAPTER").expect("KOTLIN_PROBE_ADAPTER");
|
||||
let source = PathBuf::from(config.cwd.clone().unwrap()).join("src/main/kotlin/Main.kt");
|
||||
for run in 1..=10 {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
let frames = h.manager.stack_trace(id, thread_id).await.unwrap();
|
||||
assert_eq!(frames[0].line, 5);
|
||||
assert_eq!(frames[0].path.as_deref(), Some(source.as_path()));
|
||||
let scopes = h.manager.scopes(id, frames[0].id).await.unwrap();
|
||||
let mut variables = Vec::new();
|
||||
for scope in scopes {
|
||||
variables.extend(h.manager.variables(id, scope.variables_reference).await.unwrap());
|
||||
}
|
||||
assert!(variables.iter().any(|v| v.name == "i" && v.value == "0"));
|
||||
h.manager.step(id, thread_id, StepKind::Over).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "step")).await;
|
||||
let frames = h.manager.stack_trace(id, thread_id).await.unwrap();
|
||||
assert_eq!(frames[0].line, 4);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
println!("Run {run}/10: breakpoint Main.kt:6, i=0, step Main.kt:5; stopped");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
for request in ["launch", "attach"] {
|
||||
for (client, native, returned) in [
|
||||
("C:/work/Main.java", r"C:\work\Main.java", r"C:\work\Main.java"),
|
||||
("C:/work/Main.java", r"C:\work\Main.java", "C:/work/Main.java"),
|
||||
(r"c:\work\Main.java", r"c:\work\Main.java", "c:/work/Main.java"),
|
||||
(r"D:/my project\Main.java", r"D:\my project\Main.java", r"D:\my project\Main.java"),
|
||||
("//server/share/Main.java", r"\\server\share\Main.java", "//server/share/Main.java"),
|
||||
(r"\\server\share/Main.java", r"\\server\share\Main.java", "//server/share/Main.java"),
|
||||
("/work/Main.java", "/work/Main.java", "/work/Main.java"),
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
assert_eq!(h.request("initialize")["arguments"]["pathFormat"], "path");
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], native);
|
||||
let commands = h.commands();
|
||||
assert!(
|
||||
commands.iter().position(|c| c == "setBreakpoints").unwrap()
|
||||
< commands.iter().position(|c| c == "configurationDone").unwrap()
|
||||
);
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames[0].path.as_deref(), Some(path.as_path()));
|
||||
h.wait_event(|e| {
|
||||
matches!(e, DebugEvent::BreakpointsChanged { path: p } if p.as_ref() == path.as_path())
|
||||
&& h.manager.breakpoint_states(&path)[0].message.as_deref() == Some("moved")
|
||||
})
|
||||
.await;
|
||||
assert_eq!(h.manager.breakpoint_states(&path)[0].message.as_deref(), Some("moved"));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn java_stack_frames_without_breakpoints_normalize_windows_paths() {
|
||||
for (returned, expected) in [
|
||||
(r"C:\work\Other.java", "C:/work/Other.java"),
|
||||
(r"\\server\share\Other.java", "//server/share/Other.java"),
|
||||
("C:/work/Other.java", "C:/work/Other.java"),
|
||||
("/work/Other.java", "/work/Other.java"),
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames[0].path.as_deref(), Some(PathBuf::from(expected).as_path()));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ futures.workspace = true
|
||||
sqlx.workspace = true
|
||||
tiberius.workspace = true
|
||||
bb8.workspace = true
|
||||
bb8-tiberius.workspace = true
|
||||
tokio-util = { workspace = true, features = ["compat"] }
|
||||
dirs.workspace = true
|
||||
ide-ssh.workspace = true
|
||||
|
||||
|
||||
@@ -47,13 +47,15 @@ pub struct QueryResult {
|
||||
pub execution_ms: f64,
|
||||
}
|
||||
|
||||
// bb8-tiberius never marks connections broken; keep an empty slot when discarded.
|
||||
pub struct MssqlConnectionManager(bb8_tiberius::ConnectionManager);
|
||||
// Keep an empty slot when a connection is discarded after cancellation or rollback failure.
|
||||
pub struct MssqlConnectionManager(tiberius::Config);
|
||||
|
||||
pub struct MssqlConnection(Option<bb8_tiberius::rt::Client>);
|
||||
type MssqlClient = tiberius::Client<tokio_util::compat::Compat<tokio::net::TcpStream>>;
|
||||
|
||||
pub struct MssqlConnection(Option<MssqlClient>);
|
||||
|
||||
impl std::ops::Deref for MssqlConnection {
|
||||
type Target = bb8_tiberius::rt::Client;
|
||||
type Target = MssqlClient;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.as_ref().expect("live SQL Server connection")
|
||||
}
|
||||
@@ -67,10 +69,26 @@ impl std::ops::DerefMut for MssqlConnection {
|
||||
|
||||
impl ManageConnection for MssqlConnectionManager {
|
||||
type Connection = MssqlConnection;
|
||||
type Error = bb8_tiberius::Error;
|
||||
type Error = tiberius::error::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
self.0.connect().await.map(|c| MssqlConnection(Some(c)))
|
||||
use tokio_util::compat::TokioAsyncWriteCompatExt;
|
||||
|
||||
let tcp = tokio::net::TcpStream::connect(self.0.get_addr()).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let client = match MssqlClient::connect(self.0.clone(), tcp.compat_write()).await {
|
||||
// Preserve the single redirect supported by the previous pool adapter.
|
||||
Err(tiberius::error::Error::Routing { host, port }) => {
|
||||
let mut config = self.0.clone();
|
||||
config.host(host);
|
||||
config.port(port);
|
||||
let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
MssqlClient::connect(config, tcp.compat_write()).await?
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
Ok(MssqlConnection(Some(client)))
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -120,28 +138,25 @@ pub(crate) fn db_err(e: sqlx::Error) -> IdeError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mssql_err(e: impl Into<bb8_tiberius::Error>) -> IdeError {
|
||||
match e.into() {
|
||||
bb8_tiberius::Error::Tiberius(e) => match &e {
|
||||
tiberius::error::Error::Server(d) => {
|
||||
let code = d.code();
|
||||
// Wrong login: SQL Server 18456.
|
||||
let auth = matches!(code, 18452 | 18456 | 18470);
|
||||
IdeError::new(
|
||||
if auth { ErrorKind::PermissionDenied } else { ErrorKind::InvalidInput },
|
||||
format!("[{code}] {}", d.message()),
|
||||
)
|
||||
}
|
||||
tiberius::error::Error::Io { .. } | tiberius::error::Error::Tls(_) => {
|
||||
IdeError::new(ErrorKind::Io, e.to_string())
|
||||
}
|
||||
_ => IdeError::new(ErrorKind::Protocol, e.to_string()),
|
||||
},
|
||||
bb8_tiberius::Error::Io(e) => IdeError::new(ErrorKind::Io, e.to_string()),
|
||||
pub(crate) fn mssql_err(e: tiberius::error::Error) -> IdeError {
|
||||
match &e {
|
||||
tiberius::error::Error::Server(d) => {
|
||||
let code = d.code();
|
||||
// Wrong login: SQL Server 18456.
|
||||
let auth = matches!(code, 18452 | 18456 | 18470);
|
||||
IdeError::new(
|
||||
if auth { ErrorKind::PermissionDenied } else { ErrorKind::InvalidInput },
|
||||
format!("[{code}] {}", d.message()),
|
||||
)
|
||||
}
|
||||
tiberius::error::Error::Io { .. } | tiberius::error::Error::Tls(_) => {
|
||||
IdeError::new(ErrorKind::Io, e.to_string())
|
||||
}
|
||||
_ => IdeError::new(ErrorKind::Protocol, e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn mssql_pool_err(e: bb8::RunError<bb8_tiberius::Error>) -> IdeError {
|
||||
fn mssql_pool_err(e: bb8::RunError<tiberius::error::Error>) -> IdeError {
|
||||
match e {
|
||||
bb8::RunError::User(e) => mssql_err(e),
|
||||
bb8::RunError::TimedOut => IdeError::new(ErrorKind::Io, "timed out connecting to the database"),
|
||||
@@ -364,13 +379,13 @@ macro_rules! fetch {
|
||||
/// Columns, rows, rows affected, more rows beyond the limit, time of the first answer.
|
||||
type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool, Option<Instant>);
|
||||
|
||||
async fn mssql_command(conn: &mut bb8_tiberius::rt::Client, sql: &str) -> IdeResult<()> {
|
||||
async fn mssql_command(conn: &mut MssqlClient, sql: &str) -> IdeResult<()> {
|
||||
// Transaction control must be a batch: sp_executesql rejects a changed transaction count.
|
||||
conn.simple_query(sql).await.map_err(mssql_err)?.into_results().await.map_err(mssql_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mssql_fetch(conn: &mut bb8_tiberius::rt::Client, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
async fn mssql_fetch(conn: &mut MssqlClient, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
let mut stream = conn.simple_query(sql).await.map_err(mssql_err)?;
|
||||
let first = Some(Instant::now());
|
||||
let columns = stream
|
||||
@@ -669,7 +684,7 @@ impl Pool {
|
||||
if matches!(source.ssl, DbSslMode::Disable | DbSslMode::Prefer) {
|
||||
config.trust_cert();
|
||||
}
|
||||
let manager = MssqlConnectionManager(bb8_tiberius::ConnectionManager::new(config));
|
||||
let manager = MssqlConnectionManager(config);
|
||||
let pool = bb8::Pool::builder()
|
||||
.max_size(MAX)
|
||||
.connection_timeout(timeout)
|
||||
@@ -908,6 +923,23 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::source::{DbOptions, DbProperty};
|
||||
|
||||
#[test]
|
||||
fn discarded_sqlserver_connections_are_broken() {
|
||||
let manager = MssqlConnectionManager(tiberius::Config::new());
|
||||
assert!(manager.has_broken(&mut MssqlConnection(None)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_connect_reports_io_errors() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let mut config = tiberius::Config::new();
|
||||
config.host("127.0.0.1");
|
||||
config.port(listener.local_addr().unwrap().port());
|
||||
drop(listener);
|
||||
let result = MssqlConnectionManager(config).connect().await;
|
||||
assert!(matches!(result, Err(tiberius::error::Error::Io { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_cells_preserve_values_and_nulls() {
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Automatic runtime provisioning belongs to the host, not SDK discovery.
|
||||
use ide_core::{CancellationToken, IdeEvent, SharedSink, TaskId};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use ide_sdk::java::{jdtls_jdks, jdtls_min_java, jdtls_runtime, language_server_runtimes_dir};
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
busy: bool,
|
||||
sinks: Vec<Weak<dyn ide_core::EventSink>>,
|
||||
attempted: HashSet<(PathBuf, u32)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Provisioner {
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
static PROVISIONER: LazyLock<Provisioner> = LazyLock::new(Provisioner::default);
|
||||
|
||||
fn needs_download(explicit: bool, suitable: bool, attempted: bool) -> bool {
|
||||
!explicit && !suitable && !attempted
|
||||
}
|
||||
|
||||
impl Provisioner {
|
||||
fn subscribe(&self, sink: &SharedSink) {
|
||||
let mut state = self.state.lock();
|
||||
state.sinks.retain(|s| s.strong_count() > 0);
|
||||
let weak = Arc::downgrade(sink);
|
||||
if !state.sinks.iter().any(|s| s.ptr_eq(&weak)) {
|
||||
state.sinks.push(weak);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&self, event: IdeEvent) {
|
||||
let sinks: Vec<_> = self.state.lock().sinks.iter().filter_map(Weak::upgrade).collect();
|
||||
for sink in sinks {
|
||||
sink.emit(event.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, key: (PathBuf, u32), cancel: &CancellationToken, work: impl FnOnce()) {
|
||||
let mut state = self.state.lock();
|
||||
while state.busy && !cancel.is_cancelled() {
|
||||
self.changed.wait_for(&mut state, Duration::from_millis(100));
|
||||
}
|
||||
if cancel.is_cancelled() || !state.attempted.insert(key) {
|
||||
return;
|
||||
}
|
||||
state.busy = true;
|
||||
drop(state);
|
||||
// Even a panicking installer must release waiters and retain the attempt.
|
||||
struct Flight<'a>(&'a Provisioner);
|
||||
impl Drop for Flight<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.state.lock().busy = false;
|
||||
self.0.changed.notify_all();
|
||||
}
|
||||
}
|
||||
let _flight = Flight(self);
|
||||
work();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(
|
||||
cfg: &LanguageServerConfig,
|
||||
data_dir: &Path,
|
||||
explicit: bool,
|
||||
sink: &SharedSink,
|
||||
launch_cancel: &CancellationToken,
|
||||
) {
|
||||
let min_java = jdtls_min_java(cfg);
|
||||
let jdks = jdtls_jdks(min_java, data_dir);
|
||||
// A launch environment override is explicit too, even if it is invalid.
|
||||
if !needs_download(explicit || cfg.env.contains_key("JAVA_HOME"), jdtls_runtime(&jdks, min_java).is_some(), false) {
|
||||
return;
|
||||
}
|
||||
PROVISIONER.subscribe(sink);
|
||||
PROVISIONER.run((data_dir.to_path_buf(), min_java), launch_cancel, || {
|
||||
if jdtls_runtime(&jdtls_jdks(min_java, data_dir), min_java).is_some() {
|
||||
return;
|
||||
}
|
||||
let id = TaskId::next();
|
||||
let title = format!("Downloading Java {min_java} language server runtime");
|
||||
// Closing one project must not cancel a download other projects await.
|
||||
let cancel = CancellationToken::new();
|
||||
let _handle = ide_core::task::on_cancel(id, {
|
||||
let cancel = cancel.clone();
|
||||
move || cancel.cancel()
|
||||
});
|
||||
let emit = |message, fraction, done| {
|
||||
PROVISIONER.emit(IdeEvent::Task { id, title: title.clone(), message, fraction, done, cancellable: !done });
|
||||
};
|
||||
emit(Some("Eclipse Temurin".into()), None, false);
|
||||
let result = ide_tools::Tools::new(data_dir).download_java_runtime(
|
||||
min_java,
|
||||
&language_server_runtimes_dir(data_dir),
|
||||
&cancel,
|
||||
&|event| match event {
|
||||
ide_tools::InstallEvent::Line { text } => emit(Some(text), None, false),
|
||||
ide_tools::InstallEvent::Progress { fraction, message } => {
|
||||
emit(Some(message), fraction.map(|f| f as f32), false)
|
||||
}
|
||||
},
|
||||
);
|
||||
emit(result.as_ref().err().map(ToString::to_string), Some(1.0), true);
|
||||
if let Err(error) = result {
|
||||
// The configuration hook retains the existing manual download action.
|
||||
tracing::warn!("automatic jdtls runtime download: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn download_decision() {
|
||||
assert!(needs_download(false, false, false));
|
||||
for (explicit, suitable, attempted) in [(true, false, false), (false, true, false), (false, false, true)] {
|
||||
assert!(!needs_download(explicit, suitable, attempted));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_projects_share_one_attempt_and_failures_do_not_retry() {
|
||||
let provisioner = Provisioner::default();
|
||||
let calls = AtomicUsize::new(0);
|
||||
let barrier = std::sync::Barrier::new(8);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
scope.spawn(|| {
|
||||
barrier.wait();
|
||||
provisioner.run((PathBuf::from("/data"), 25), &CancellationToken::new(), || {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
provisioner.run((PathBuf::from("/data"), 25), &CancellationToken::new(), || panic!("retried"));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_versions_are_still_single_flight() {
|
||||
let provisioner = Provisioner::default();
|
||||
let active = AtomicUsize::new(0);
|
||||
let calls = AtomicUsize::new(0);
|
||||
std::thread::scope(|scope| {
|
||||
for feature in [25, 26, 27] {
|
||||
let provisioner = &provisioner;
|
||||
let active = &active;
|
||||
let calls = &calls;
|
||||
scope.spawn(move || {
|
||||
provisioner.run((PathBuf::from("/data"), feature), &CancellationToken::new(), || {
|
||||
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_waiter_does_not_consume_an_attempt() {
|
||||
let provisioner = Provisioner::default();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
provisioner.run((PathBuf::from("/data"), 25), &cancel, || panic!("cancelled"));
|
||||
assert!(provisioner.state.lock().attempted.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
|
||||
|
||||
pub mod environment;
|
||||
mod java_runtime;
|
||||
pub mod notebook;
|
||||
pub mod ops;
|
||||
mod project;
|
||||
|
||||
@@ -87,8 +87,14 @@ pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
}
|
||||
|
||||
pub async fn create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
host.project(window)?.agents.create(request).await
|
||||
pub async fn create(host: &Host, window: &str, mut request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let requested = request.project_root.take();
|
||||
request.project_root = Some(IpcPath(
|
||||
host.blocking(move || validate_project_root(&root, requested.as_ref().map(|p| p.0.as_path()))).await?,
|
||||
));
|
||||
project.agents.create(request).await
|
||||
}
|
||||
|
||||
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
|
||||
@@ -140,6 +146,10 @@ pub fn archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.archive(&task)
|
||||
}
|
||||
|
||||
pub fn unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unarchive(&task)
|
||||
}
|
||||
|
||||
pub async fn delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
@@ -183,6 +193,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
d.add("agent_unarchive", |c| async move { unarchive(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_archive", |c| async move { archive(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add(
|
||||
"agent_delete",
|
||||
@@ -191,3 +202,43 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_changes", |c| async move { changes(&c.host, &c.window, c.arg("task")?).await });
|
||||
d.add("agent_base_text", |c| async move { base_text(&c.host, &c.window, c.arg("task")?, c.arg("path")?).await });
|
||||
}
|
||||
|
||||
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
|
||||
let Some(requested) = requested else {
|
||||
return Ok(root.to_path_buf());
|
||||
};
|
||||
if !requested.is_absolute() {
|
||||
return Err(IdeError::invalid("Choose an absolute project root"));
|
||||
}
|
||||
let requested = dunce::canonicalize(requested)?;
|
||||
let window_root = dunce::canonicalize(root)?;
|
||||
if requested == window_root
|
||||
|| ide_workspace::workspace::Workspace::load(root)?.is_some_and(|w| w.projects.contains(&requested))
|
||||
{
|
||||
return Ok(requested);
|
||||
}
|
||||
Err(IdeError::invalid("Agent project must be the window project or a workspace member"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn agent_roots_are_exact_window_or_workspace_members() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("workspace");
|
||||
let member = tmp.path().join("member");
|
||||
let other = tmp.path().join("other");
|
||||
for dir in [&root, &member, &other, &member.join("child")] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
assert_eq!(validate_project_root(&root, None).unwrap(), root);
|
||||
assert_eq!(validate_project_root(&root, Some(&root)).unwrap(), dunce::canonicalize(&root).unwrap());
|
||||
assert!(validate_project_root(&root, Some(&member)).is_err());
|
||||
ide_workspace::workspace::Workspace::save(&root, "Workspace", vec![member.clone()], true).unwrap();
|
||||
assert_eq!(validate_project_root(&root, Some(&member)).unwrap(), dunce::canonicalize(&member).unwrap());
|
||||
for rejected in [other, member.join("child"), member.join("../other"), "relative".into()] {
|
||||
assert!(validate_project_root(&root, Some(&rejected)).is_err(), "{rejected:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,12 +123,27 @@ pub async fn build_sync(
|
||||
BuildTool::Maven => ide_build::sync_maven(&root, &cache, &options, &token, &progress)?,
|
||||
BuildTool::Gradle => ide_build::sync_gradle(&root, &cache, &options, &token, &progress)?,
|
||||
}
|
||||
Ok(load(&root, &cache, &settings))
|
||||
Ok::<BuildModel, IdeError>(load(&root, &cache, &settings))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result?
|
||||
let model = result??;
|
||||
if tool == BuildTool::Maven
|
||||
&& let Some(maven) = &model.maven
|
||||
{
|
||||
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
|
||||
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
|
||||
// to update the project configurations re-resolves them (#436).
|
||||
let lsp = project.lsp.clone();
|
||||
let uris = maven.projects.iter().map(|p| ide_lsp::path_to_uri_string(&project.root.join(&p.pom))).collect();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
|
||||
tracing::debug!("java/projectConfigurationsUpdate: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
/// The POM declaring `dependency` for the Maven module `pom` (project-relative): the
|
||||
@@ -211,6 +226,7 @@ pub async fn build_run(
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let settings = project.settings.effective();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
for path in clear {
|
||||
@@ -220,7 +236,23 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let plan = compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?;
|
||||
let plan = if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache = cache.join(crate::project::project_key(member));
|
||||
let plan = compile::plan(member, &load(member, &member_cache, &settings), kind, file.as_deref())?;
|
||||
match &mut combined {
|
||||
Some(combined) => combined.steps.extend(plan.steps),
|
||||
None => combined = Some(plan),
|
||||
}
|
||||
}
|
||||
let mut plan = combined.ok_or_else(|| IdeError::invalid("No workspace project to build"))?;
|
||||
plan.title = workspace.name;
|
||||
plan
|
||||
} else {
|
||||
compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?
|
||||
};
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
@@ -291,7 +323,10 @@ mod gradle_settings_tests {
|
||||
let model = load(root, &root.join("cache"), &settings).gradle.unwrap();
|
||||
assert_eq!(
|
||||
model.command,
|
||||
root.join("gradle-install/bin").join(if cfg!(windows) { "gradle.bat" } else { "gradle" }).to_string_lossy()
|
||||
root.join("gradle-install")
|
||||
.join("bin")
|
||||
.join(if cfg!(windows) { "gradle.bat" } else { "gradle" })
|
||||
.to_string_lossy()
|
||||
);
|
||||
assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy());
|
||||
assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy());
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
mod output;
|
||||
|
||||
use crate::Host;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::{DebugSessionId, IdeResult};
|
||||
@@ -14,17 +16,54 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
|
||||
}
|
||||
let label = window;
|
||||
let owner = SessionOwner::new(host.owner_window(label), host.window_sink(label));
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
let owner = SessionOwner::new(host.owner_window(label), sink);
|
||||
let settings = match host.project(label) {
|
||||
Ok(project) => project.settings.effective(),
|
||||
Err(_) => host.global_settings.effective(),
|
||||
};
|
||||
if config.adapter == ide_dap::kotlin::ADAPTER {
|
||||
let data_dir = host.data_dir.clone();
|
||||
let runtime_root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
let runtime_settings = settings.clone();
|
||||
let runtime = host
|
||||
.blocking(move || {
|
||||
if let Some(jdk) = ide_sdk::apply::jdtls_jdk(&runtime_root, &runtime_settings)
|
||||
.map_err(ide_core::IdeError::unavailable)?
|
||||
{
|
||||
if jdk.major >= 11 {
|
||||
return Ok(jdk);
|
||||
}
|
||||
return Err(ide_core::IdeError::unavailable(
|
||||
"Kotlin debugger needs JDK 11 or newer. Choose a newer language server JDK in Settings.",
|
||||
));
|
||||
}
|
||||
let jdks = ide_sdk::java::jdtls_jdks(11, &data_dir);
|
||||
ide_sdk::java::jdtls_runtime(&jdks, 11).cloned().ok_or_else(|| {
|
||||
ide_core::IdeError::unavailable(
|
||||
"Kotlin debugger needs JDK 11 or newer. Download or choose a language server JDK in Settings.",
|
||||
)
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
let mut extra: serde_json::Value = config
|
||||
.extra_json
|
||||
.as_deref()
|
||||
.map(serde_json::from_str)
|
||||
.transpose()
|
||||
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
|
||||
.unwrap_or_else(|| serde_json::json!({}));
|
||||
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
|
||||
config.extra_json = Some(extra.to_string());
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
let custom = |command: &str| {
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
host.debugger.start_with(config, owner, custom).await
|
||||
let result = host.debugger.start_with(config, owner, custom).await;
|
||||
flush_output();
|
||||
result
|
||||
}
|
||||
|
||||
/// A JVM launched by java-debug writes what java-debug decodes its output as
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const WINDOW: Duration = Duration::from_millis(50);
|
||||
const MAX_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Pending {
|
||||
sessions: HashMap<DebugSessionId, (String, String)>,
|
||||
scheduled: bool,
|
||||
}
|
||||
|
||||
fn flush(pending: &mut Pending, sink: &SharedSink, session: DebugSessionId) {
|
||||
if let Some((category, output)) = pending.sessions.remove(&session) {
|
||||
sink.emit(IdeEvent::Debug { session, event: DebugEvent::Output { category, output } });
|
||||
}
|
||||
}
|
||||
|
||||
/// All debug output sources (including build output and child sessions) share this
|
||||
/// bounded batch before reaching desktop or remote IPC. Control events flush
|
||||
/// their session first, so a stop or exit cannot overtake preceding output.
|
||||
pub(super) fn coalescing_sink(sink: SharedSink) -> (SharedSink, impl Fn()) {
|
||||
let pending = Arc::new(Mutex::new(Pending::default()));
|
||||
let flush_pending = {
|
||||
let pending = pending.clone();
|
||||
let sink = sink.clone();
|
||||
move || {
|
||||
let mut state = pending.lock();
|
||||
for (session, (category, output)) in state.sessions.drain() {
|
||||
sink.emit(IdeEvent::Debug { session, event: DebugEvent::Output { category, output } });
|
||||
}
|
||||
}
|
||||
};
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let output: SharedSink = Arc::new(move |event| {
|
||||
let mut state = pending.lock();
|
||||
match event {
|
||||
IdeEvent::Debug { session, event: DebugEvent::Output { category, output } } => {
|
||||
if output.is_empty() {
|
||||
return;
|
||||
}
|
||||
if state.sessions.get(&session).is_some_and(|(c, _)| *c != category) {
|
||||
flush(&mut state, &sink, session);
|
||||
}
|
||||
let mut rest = output.as_str();
|
||||
while !rest.is_empty() {
|
||||
let (_, text) = state.sessions.entry(session).or_insert_with(|| (category.clone(), String::new()));
|
||||
let mut end = rest.len().min(MAX_BYTES - text.len());
|
||||
while !rest.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
text.push_str(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
if text.len() == MAX_BYTES || !rest.is_empty() {
|
||||
flush(&mut state, &sink, session);
|
||||
}
|
||||
}
|
||||
if !state.scheduled && !state.sessions.is_empty() {
|
||||
state.scheduled = true;
|
||||
let pending = pending.clone();
|
||||
let sink = sink.clone();
|
||||
runtime.spawn(async move {
|
||||
tokio::time::sleep(WINDOW).await;
|
||||
let mut state = pending.lock();
|
||||
for (session, (category, output)) in state.sessions.drain() {
|
||||
sink.emit(IdeEvent::Debug { session, event: DebugEvent::Output { category, output } });
|
||||
}
|
||||
state.scheduled = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
IdeEvent::Debug { session, event } => {
|
||||
flush(&mut state, &sink, session);
|
||||
sink.emit(IdeEvent::Debug { session, event });
|
||||
}
|
||||
event => sink.emit(event),
|
||||
}
|
||||
});
|
||||
(output, flush_pending)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn setup() -> (SharedSink, Arc<Mutex<Vec<IdeEvent>>>) {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let saved = events.clone();
|
||||
(coalescing_sink(Arc::new(move |event| saved.lock().push(event))).0, events)
|
||||
}
|
||||
|
||||
fn output(sink: &SharedSink, session: u32, category: &str, output: &str) {
|
||||
sink.emit(IdeEvent::Debug {
|
||||
session: DebugSessionId(session),
|
||||
event: DebugEvent::Output { category: category.into(), output: output.into() },
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn explicit_start_completion_flush_does_not_duplicate_output() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let saved = events.clone();
|
||||
let (sink, flush) = coalescing_sink(Arc::new(move |event| saved.lock().push(event)));
|
||||
output(&sink, 1, "console", "build failed\n");
|
||||
flush();
|
||||
assert_eq!(events.lock().len(), 1);
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(WINDOW).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(events.lock().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn batches_per_session_and_flushes_idle_output() {
|
||||
let (sink, events) = setup();
|
||||
for _ in 0..500 {
|
||||
output(&sink, 1, "stdout", "line\n");
|
||||
}
|
||||
output(&sink, 2, "stdout", "other\n");
|
||||
assert!(events.lock().is_empty());
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(WINDOW).await;
|
||||
tokio::task::yield_now().await;
|
||||
let events = events.lock();
|
||||
assert_eq!(events.len(), 2);
|
||||
assert!(events.iter().any(|event| matches!(event,
|
||||
IdeEvent::Debug { session: DebugSessionId(1), event: DebugEvent::Output { output, .. } }
|
||||
if output == &"line\n".repeat(500))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn categories_and_control_events_keep_order() {
|
||||
let (sink, events) = setup();
|
||||
output(&sink, 1, "stdout", "out");
|
||||
output(&sink, 1, "stderr", "err");
|
||||
sink.emit(IdeEvent::Debug { session: DebugSessionId(1), event: DebugEvent::Terminated });
|
||||
let events = events.lock();
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(matches!(&events[0], IdeEvent::Debug { event: DebugEvent::Output { category, output }, .. }
|
||||
if category == "stdout" && output == "out"));
|
||||
assert!(matches!(&events[1], IdeEvent::Debug { event: DebugEvent::Output { category, output }, .. }
|
||||
if category == "stderr" && output == "err"));
|
||||
assert!(matches!(&events[2], IdeEvent::Debug { event: DebugEvent::Terminated, .. }));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn terminating_one_session_preserves_other_pending_output() {
|
||||
let (sink, events) = setup();
|
||||
output(&sink, 1, "stdout", "first");
|
||||
output(&sink, 2, "stdout", "second");
|
||||
sink.emit(IdeEvent::Debug { session: DebugSessionId(1), event: DebugEvent::Terminated });
|
||||
assert_eq!(events.lock().len(), 2);
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(WINDOW).await;
|
||||
tokio::task::yield_now().await;
|
||||
let events = events.lock();
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(matches!(&events[2],
|
||||
IdeEvent::Debug { session: DebugSessionId(2), event: DebugEvent::Output { output, .. } }
|
||||
if output == "second"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn large_unicode_events_are_bounded_without_loss() {
|
||||
let (sink, events) = setup();
|
||||
let text = "日志\n".repeat(100_000);
|
||||
output(&sink, 1, "stdout", &text);
|
||||
sink.emit(IdeEvent::Debug { session: DebugSessionId(1), event: DebugEvent::Terminated });
|
||||
let mut combined = String::new();
|
||||
for event in events.lock().iter() {
|
||||
if let IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } = event {
|
||||
assert!(output.len() <= MAX_BYTES);
|
||||
combined.push_str(output);
|
||||
}
|
||||
}
|
||||
assert_eq!(combined, text);
|
||||
}
|
||||
}
|
||||
@@ -28,12 +28,14 @@ pub fn edit(host: &Host, window: &str, doc: DocId, base_version: u32, changes: C
|
||||
|
||||
pub async fn save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
pub async fn save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
pub async fn snapshot(host: &Host, window: &str, doc: DocId) -> IdeResult<DocumentInfo> {
|
||||
|
||||
@@ -21,6 +21,8 @@ pub async fn java_resolve_launch(
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let settings = project.settings.effective();
|
||||
// Let jdtls finish its build before the external compiler writes Kotlin/Scala classes.
|
||||
let mut info = project.lsp.java_launch(&module, test, build).await?;
|
||||
let built = if build && compile::has_non_java_sources(&module) {
|
||||
let (root, cache, module, settings) =
|
||||
(project.root.clone(), project.build_cache_dir(), module.clone(), settings.clone());
|
||||
@@ -32,7 +34,6 @@ pub async fn java_resolve_launch(
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut info = project.lsp.java_launch(&module, test, build).await?;
|
||||
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
for p in std::mem::take(&mut info.class_paths) {
|
||||
if !class_paths.contains(&p) {
|
||||
|
||||
@@ -186,8 +186,19 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos)
|
||||
}
|
||||
|
||||
/// Computes the rename edit without applying it, so the UI can preview conflicts.
|
||||
pub async fn lsp_rename(host: &Host, window: &str, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
|
||||
host.project(window)?.lsp.rename(doc, pos, new_name).await
|
||||
pub async fn lsp_rename(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
) -> IdeResult<Renamed> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = lsp.rename(doc, pos, new_name, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn lsp_format(
|
||||
@@ -220,11 +231,16 @@ pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeRes
|
||||
pub async fn lsp_call_hierarchy(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
direction: HierarchyDirection,
|
||||
) -> IdeResult<Vec<HierarchyItem>> {
|
||||
host.project(window)?.lsp.call_hierarchy(doc, pos, direction).await
|
||||
) -> IdeResult<CallHierarchy> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = lsp.call_hierarchy(doc, pos, direction, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn lsp_type_hierarchy(
|
||||
@@ -335,7 +351,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
lsp_prepare_rename(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?).await
|
||||
});
|
||||
d.add("lsp_rename", |c| async move {
|
||||
lsp_rename(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("newName")?).await
|
||||
lsp_rename(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, c.arg("newName")?).await
|
||||
});
|
||||
d.add("lsp_format", |c| async move {
|
||||
lsp_format(&c.host, &c.window, c.arg("doc")?, c.arg("range")?, c.arg("options")?).await
|
||||
@@ -348,7 +364,8 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_code_lens", |c| async move { lsp_code_lens(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("lsp_document_links", |c| async move { lsp_document_links(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("lsp_call_hierarchy", |c| async move {
|
||||
lsp_call_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
|
||||
lsp_call_hierarchy(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?)
|
||||
.await
|
||||
});
|
||||
d.add("lsp_type_hierarchy", |c| async move {
|
||||
lsp_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
|
||||
|
||||
@@ -14,6 +14,8 @@ pub struct ProjectInfo {
|
||||
pub name: String,
|
||||
pub is_git: bool,
|
||||
pub settings: Settings,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub workspace: Option<ide_workspace::workspace::Workspace>,
|
||||
}
|
||||
|
||||
pub fn info(project: &Project) -> ProjectInfo {
|
||||
@@ -28,6 +30,7 @@ pub fn info(project: &Project) -> ProjectInfo {
|
||||
is_git: !project.repos.read().is_empty(),
|
||||
settings,
|
||||
root: project.root.clone().into(),
|
||||
workspace: ide_workspace::workspace::Workspace::load(&project.root).ok().flatten(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +56,42 @@ pub fn roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots
|
||||
Ok(host.project(window)?.roots())
|
||||
}
|
||||
|
||||
pub fn save_workspace(host: &Host, window: &str, name: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<ProjectInfo> {
|
||||
let project = host.project(window)?;
|
||||
ide_workspace::workspace::Workspace::save(&project.root, name, paths, false)?;
|
||||
project.settings.reload();
|
||||
project.refresh_index_scope();
|
||||
project.refresh_repositories();
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
Ok(info(&project))
|
||||
}
|
||||
|
||||
/// Links a folder, or prepares an automatic workspace for the caller to open in place.
|
||||
pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult<ide_core::IpcPath> {
|
||||
let project = host.project(window)?;
|
||||
let path = dunce::canonicalize(path)?;
|
||||
if project.light {
|
||||
return Err(ide_core::IdeError::invalid("Open a project before attaching a folder"));
|
||||
}
|
||||
if let Some(mut workspace) = ide_workspace::workspace::Workspace::load(&project.root)? {
|
||||
if !workspace.projects.contains(&path) {
|
||||
workspace.projects.push(path);
|
||||
save_workspace(host, window, &workspace.name, workspace.projects)?;
|
||||
}
|
||||
return Ok(project.root.clone().into());
|
||||
}
|
||||
if path == project.root {
|
||||
return Ok(project.root.clone().into());
|
||||
}
|
||||
Ok(ide_workspace::workspace::Workspace::create_for_project(
|
||||
&host.data_dir,
|
||||
&project.root,
|
||||
&info(&project).name,
|
||||
&path,
|
||||
)?
|
||||
.into())
|
||||
}
|
||||
|
||||
/// What [`set_settings`] changed; the caller tells the windows.
|
||||
pub struct SettingsApplied {
|
||||
pub settings: Settings,
|
||||
|
||||
@@ -9,22 +9,52 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let user = ide_run::load_user_configs(&root)?;
|
||||
let suppressed = ide_run::load_suppressed_config_ids(&root)?;
|
||||
let root_suppressed = ide_run::load_suppressed_config_ids(&root)?;
|
||||
let settings = project.settings.effective();
|
||||
let excluded_poms = crate::project::unlinked_maven_poms(&root, &settings);
|
||||
let mut all: Vec<RunConfig> = ide_run::detect_excluding(&root, &excluded_poms)
|
||||
.into_iter()
|
||||
.filter(|d| !suppressed.contains(&d.id) && !user.iter().any(|u| u.id == d.id))
|
||||
.collect();
|
||||
all.extend(user);
|
||||
// Project interpreter / package manager / toolchains from Languages & Frameworks.
|
||||
// Keep Gradle choices unmodified in the editor: derived defaults must not be saved as explicit env.
|
||||
for config in all.iter_mut().filter(|c| c.kind != "gradle") {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(config), &root, &settings);
|
||||
let mut all = detected_and_saved(&root, &settings, &user, &root_suppressed);
|
||||
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
for member in workspace.projects.into_iter().filter(|p| p.is_dir()) {
|
||||
let settings = ide_workspace::SettingsStore::load(&host.config_dir, Some(&member)).effective();
|
||||
let saved = ide_run::load_user_configs(&member)?;
|
||||
let suppressed = ide_run::load_suppressed_config_ids(&member)?;
|
||||
let configs = detected_and_saved(&member, &settings, &saved, &suppressed);
|
||||
let key = crate::project::project_key(&member);
|
||||
let name = member.file_name().unwrap_or_default().to_string_lossy();
|
||||
for mut config in configs {
|
||||
config.id = format!("workspace:{}:{}", key, config.id);
|
||||
config.name = format!("{name} / {}", config.name);
|
||||
config.cwd = Some(config.cwd.map(|p| member.join(&*p)).unwrap_or_else(|| member.clone()).into());
|
||||
config.detected = true;
|
||||
if !user.iter().any(|u| u.id == config.id) && !root_suppressed.contains(&config.id) {
|
||||
all.push(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// A project's detected configurations (minus removed ones and unlinked Maven projects), then
|
||||
/// its saved ones; toolchains from Languages & Frameworks applied. Gradle choices stay as saved:
|
||||
/// derived defaults must not be written back as explicit environment.
|
||||
fn detected_and_saved(
|
||||
root: &std::path::Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
saved: &[RunConfig],
|
||||
suppressed: &[String],
|
||||
) -> Vec<RunConfig> {
|
||||
let excluded_poms = crate::project::unlinked_maven_poms(root, settings);
|
||||
let mut all: Vec<RunConfig> = ide_run::detect_excluding(root, &excluded_poms)
|
||||
.into_iter()
|
||||
.filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id))
|
||||
.collect();
|
||||
all.extend(saved.iter().cloned());
|
||||
for config in all.iter_mut().filter(|c| c.kind != "gradle") {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(config), root, settings);
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
pub fn save_configs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -40,6 +70,9 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
return Err(IdeError::invalid("run configuration has no command"));
|
||||
}
|
||||
// Settings › Run Targets: over SSH.
|
||||
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
|
||||
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
|
||||
}
|
||||
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
|
||||
let settings = project.settings.effective();
|
||||
let out = on_output.clone();
|
||||
@@ -48,21 +81,41 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
.run(&settings, &project.root, &config, project.sink.clone(), Box::new(move |c| out(c)))
|
||||
.await;
|
||||
}
|
||||
let settings = project.settings.effective();
|
||||
let member = ide_workspace::workspace::Workspace::load(&project.root)?.and_then(|workspace| {
|
||||
let cwd = config.cwd.as_deref()?;
|
||||
workspace.projects.into_iter().filter(|root| cwd.starts_with(root)).max_by_key(|root| root.components().count())
|
||||
});
|
||||
let root = member.as_ref().unwrap_or(&project.root);
|
||||
let settings = match &member {
|
||||
Some(root) => ide_workspace::SettingsStore::load(&host.config_dir, Some(root)).effective(),
|
||||
None => project.settings.effective(),
|
||||
};
|
||||
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
|
||||
let mut config = config;
|
||||
if config.kind == "gradle" {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), &project.root, &settings);
|
||||
if matches!(config.kind.as_str(), "gradle" | "tomcat") {
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
|
||||
} else {
|
||||
ide_sdk::apply::resolve_run_command(&mut config, &project.root, &settings);
|
||||
ide_sdk::apply::resolve_run_command(&mut config, root, &settings);
|
||||
}
|
||||
if config.command == ide_sdk::godot::COMMAND {
|
||||
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
|
||||
}
|
||||
if config.kind == "tomcat" {
|
||||
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
|
||||
return Err(IdeError::invalid("This Tomcat configuration is already running"));
|
||||
}
|
||||
let (root, cache) = (root.clone(), project.cache_dir.clone());
|
||||
config = tokio::task::spawn_blocking(move || {
|
||||
ide_run::tomcat::prepare(&root, &cache, &mut config)?;
|
||||
Ok::<_, IdeError>(config)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: super::python::paths(&project),
|
||||
python_paths: if member.is_some() { vec![root.clone()] } else { super::python::paths(&project) },
|
||||
};
|
||||
host.processes.start(&project.root, &config, &options, project.sink.clone(), Box::new(move |c| on_output(c)))
|
||||
}
|
||||
|
||||
@@ -49,8 +49,87 @@ pub async fn run_test_reports(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_home(host: &Host, window: &str, home: String) -> IdeResult<ide_run::tomcat::TomcatHome> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
tokio::task::spawn_blocking(move || ide_run::tomcat::validate_home(&root.join(home)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<ide_build::web::WebArtifact>> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
ide_build::web::artifacts(&project.root, &model)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> IdeResult<Option<RunConfig>> {
|
||||
if config.extras.params.get("deployment").is_some_and(|v| v != "artifact") {
|
||||
return Ok(None);
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
let artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
let id = config
|
||||
.extras
|
||||
.params
|
||||
.get("artifact")
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| artifacts.first().map(|a| &a.id))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
|
||||
let plan = ide_build::web::build(
|
||||
&project.root,
|
||||
&model,
|
||||
id,
|
||||
&ide_run::tomcat::base_dir(&project.cache_dir, &config.id),
|
||||
)?;
|
||||
let mut env = plan.env;
|
||||
env.extend(config.env.clone());
|
||||
Ok(Some(RunConfig {
|
||||
id: format!("tomcat-build:{}", config.id),
|
||||
name: format!("Build {}", config.name),
|
||||
kind: if id.starts_with("maven:") { "maven" } else { "gradle" }.into(),
|
||||
command: plan.command,
|
||||
args: plan.args,
|
||||
cwd: Some(std::path::PathBuf::from(plan.cwd).into()),
|
||||
env,
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: ide_run::RunExtras {
|
||||
include_system_env: config.extras.include_system_env,
|
||||
env_files: config.extras.env_files,
|
||||
..Default::default()
|
||||
},
|
||||
}))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_update(host: &Host, window: &str, config: RunConfig, mode: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
if !host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
|
||||
return Err(IdeError::invalid("Start this Tomcat configuration before updating it"));
|
||||
}
|
||||
tokio::task::spawn_blocking(move || ide_run::tomcat::update(&project.root, &project.cache_dir, &config, &mode))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("run_tomcat_home", |c| async move { run_tomcat_home(&c.host, &c.window, c.arg("home")?).await });
|
||||
d.add("run_tomcat_artifacts", |c| async move { run_tomcat_artifacts(&c.host, &c.window).await });
|
||||
d.add("run_tomcat_build", |c| async move { run_tomcat_build(&c.host, &c.window, c.arg("config")?).await });
|
||||
d.add("run_tomcat_update", |c| async move {
|
||||
run_tomcat_update(&c.host, &c.window, c.arg("config")?, c.arg("mode")?).await
|
||||
});
|
||||
d.add("run_templates", |c| async move { run_templates(&c.host, &c.window) });
|
||||
d.add("run_save_templates", |c| async move { run_save_templates(&c.host, &c.window, c.arg("templates")?) });
|
||||
d.add("run_system_env", |c| async move { Ok(run_system_env(&c.host, &c.window)) });
|
||||
|
||||
@@ -42,13 +42,16 @@ pub async fn start(
|
||||
let cancel = host.begin_request(request);
|
||||
let documents = project.documents.clone();
|
||||
let root = project.root.clone();
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&root)?.is_some();
|
||||
// The whole project also covers the Project Structure content roots.
|
||||
let content_roots = match query.scope {
|
||||
ide_search::SearchScope::Project | ide_search::SearchScope::FileSet { set: ProjectFileSet::All } => {
|
||||
project.content_roots()
|
||||
}
|
||||
ide_search::SearchScope::Project
|
||||
| ide_search::SearchScope::FileSet { .. }
|
||||
| ide_search::SearchScope::Pattern { .. } => project.content_roots(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let include_root = !workspace
|
||||
|| matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. });
|
||||
let languages = project.languages.clone();
|
||||
let syntax = host.syntax();
|
||||
let events = on_event.clone();
|
||||
@@ -66,7 +69,7 @@ pub async fn start(
|
||||
Some(found.into_iter().map(literal_range).collect())
|
||||
};
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(&root).chain(&content_roots) {
|
||||
for dir in std::iter::once(&root).filter(|_| include_root).chain(&content_roots) {
|
||||
let s = ide_search::search_in_context(
|
||||
dir,
|
||||
&query,
|
||||
@@ -74,7 +77,13 @@ pub async fn start(
|
||||
Some(&literals),
|
||||
&|p| documents.text_of(p),
|
||||
&cancel,
|
||||
&|file| events(SearchEvent::File { file }),
|
||||
&|mut file| {
|
||||
if dir != &root {
|
||||
let name = dir.file_name().unwrap_or_default().to_string_lossy();
|
||||
file.rel_path = format!("{name}/{}", file.rel_path);
|
||||
}
|
||||
events(SearchEvent::File { file });
|
||||
},
|
||||
)?;
|
||||
total.files += s.files;
|
||||
total.matches += s.matches;
|
||||
|
||||
@@ -45,13 +45,16 @@ pub enum RemoteOp {
|
||||
branch: String,
|
||||
},
|
||||
/// Pushes local `branch` (only up to `revision` when set) to its upstream, or to
|
||||
/// remote branch `target` of the same remote.
|
||||
/// remote branch `target`; `remote` overrides the upstream's remote (Push dialog's
|
||||
/// remote picker).
|
||||
PushBranch {
|
||||
branch: String,
|
||||
revision: Option<String>,
|
||||
force_with_lease: bool,
|
||||
#[serde(default)]
|
||||
target: Option<String>,
|
||||
#[serde(default)]
|
||||
remote: Option<String>,
|
||||
},
|
||||
/// Fast-forwards local `branch` (not checked out) to its upstream.
|
||||
UpdateBranch {
|
||||
@@ -198,11 +201,20 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_blame(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<BlameLine>> {
|
||||
pub async fn vcs_blame(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
text: Option<String>,
|
||||
revision: Option<String>,
|
||||
) -> IdeResult<Vec<BlameLine>> {
|
||||
let project = host.project(window)?;
|
||||
let text = project.documents.text_of(&path);
|
||||
// An explicit text wins (merge view annotates its side panes, not the worktree).
|
||||
let text = text.or_else(|| project.documents.text_of(&path));
|
||||
blocking(move || {
|
||||
project.with_repo_of(&path, |r| r.blame(&path, text.as_deref(), project.vcs_encoding(&path, None)?))
|
||||
project.with_repo_of(&path, |r| {
|
||||
r.blame(&path, text.as_deref(), revision.as_deref(), project.vcs_encoding(&path, revision.as_deref())?)
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -249,12 +261,13 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeRes
|
||||
}
|
||||
|
||||
/// Project-host operation (also registered with the remote dispatcher).
|
||||
/// Returns the ignore files that were updated, so the UI can show them.
|
||||
pub async fn vcs_add_to_ignore(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
paths: Vec<PathBuf>,
|
||||
destination: IgnoreDestination,
|
||||
) -> IdeResult<()> {
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
for path in &paths {
|
||||
@@ -270,7 +283,7 @@ pub async fn vcs_add_to_ignore(
|
||||
watcher.reload_ignore_rules();
|
||||
}
|
||||
project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() });
|
||||
result.map(|_| ())
|
||||
result.map(|files| files.into_iter().map(|p| p.to_string_lossy().into_owned()).collect())
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -454,12 +467,17 @@ pub async fn vcs_remote(
|
||||
r.push_with_tags(force_with_lease, set_upstream, tags, &cancel, &out)
|
||||
}
|
||||
RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out),
|
||||
RemoteOp::PushBranch { branch, revision, force_with_lease, target } => match target {
|
||||
Some(target) => {
|
||||
r.push_branch_to(&branch, revision.as_deref(), &target, force_with_lease, &cancel, &out)
|
||||
}
|
||||
None => r.push_branch(&branch, revision.as_deref(), force_with_lease, &cancel, &out),
|
||||
},
|
||||
RemoteOp::PushBranch { branch, revision, force_with_lease, target, remote } => r.push_branch_to(
|
||||
&branch,
|
||||
PushBranchOptions {
|
||||
revision: revision.as_deref(),
|
||||
target: target.as_deref(),
|
||||
remote: remote.as_deref(),
|
||||
force_with_lease,
|
||||
},
|
||||
&cancel,
|
||||
&out,
|
||||
),
|
||||
RemoteOp::UpdateBranch { branch } => r.update_branch(&branch, &cancel, &out),
|
||||
RemoteOp::PullFrom { remote, branches, rebase, options } => {
|
||||
r.pull_from(&remote, &branches, rebase, &options, &cancel, &out)
|
||||
@@ -827,7 +845,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_branch_info", |c| async move { vcs_branch_info(&c.host, &c.window, c.arg("repo")?).await });
|
||||
d.add("vcs_line_hunks", |c| async move { vcs_line_hunks(&c.host, &c.window, c.arg("path")?) });
|
||||
d.add("vcs_file_at", |c| async move { vcs_file_at(&c.host, &c.window, c.arg("path")?, c.arg("rev")?).await });
|
||||
d.add("vcs_blame", |c| async move { vcs_blame(&c.host, &c.window, c.arg("path")?).await });
|
||||
d.add("vcs_blame", |c| async move {
|
||||
vcs_blame(&c.host, &c.window, c.arg("path")?, c.arg("text")?, c.arg("revision")?).await
|
||||
});
|
||||
d.add("vcs_log", |c| async move { vcs_log(&c.host, &c.window, c.arg("repo")?, c.arg("query")?).await });
|
||||
d.add("vcs_commit_files", |c| async move {
|
||||
vcs_commit_files(&c.host, &c.window, c.arg("repo")?, c.arg("commit")?).await
|
||||
|
||||
@@ -67,6 +67,8 @@ impl Host {
|
||||
lap = std::time::Instant::now();
|
||||
};
|
||||
let root = dunce::canonicalize(root)?;
|
||||
// Reject a damaged manifest before replacing the currently open project.
|
||||
ide_workspace::workspace::Workspace::load(&root)?;
|
||||
// The window reloaded (or asked again) for the project it already has: keep
|
||||
// it, with its warm index, language servers and unsaved documents.
|
||||
if let Ok(current) = self.project(window)
|
||||
@@ -104,7 +106,7 @@ impl Host {
|
||||
let index = ProjectIndex::open(
|
||||
&root,
|
||||
&self.data_dir.join("index").join(&project_key),
|
||||
extra_roots.clone(),
|
||||
index_roots(&root, extra_roots.clone()),
|
||||
excludes.clone(),
|
||||
languages.clone(),
|
||||
self.syntax(),
|
||||
@@ -112,31 +114,40 @@ impl Host {
|
||||
)?;
|
||||
mark("index");
|
||||
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
|
||||
lsp.set_content_roots(extra_roots.clone());
|
||||
let settings = Arc::new(settings);
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let root = root.clone();
|
||||
let data_dir = self.data_dir.clone();
|
||||
let config_dir = self.config_dir.clone();
|
||||
lsp.set_config_hook(Box::new(move |cfg, server_root| {
|
||||
let effective = settings.effective();
|
||||
let member = ide_workspace::workspace::Workspace::load(&root).ok().flatten().and_then(|w| {
|
||||
w.projects.into_iter().filter(|p| server_root.starts_with(p)).max_by_key(|p| p.components().count())
|
||||
});
|
||||
let effective = member
|
||||
.as_ref()
|
||||
.map(|p| SettingsStore::load(&config_dir, Some(p)).effective())
|
||||
.unwrap_or_else(|| settings.effective());
|
||||
let root = member.as_ref().unwrap_or(&root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, &root, server_root, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
|
||||
if cfg.name == "jdtls" {
|
||||
let bundles: Vec<PathBuf> =
|
||||
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
|
||||
let min_java = ide_sdk::java::jdtls_min_java(cfg);
|
||||
let jdks = ide_sdk::java::jdtls_jdks(min_java);
|
||||
let jdks = ide_sdk::java::jdtls_jdks(min_java, &data_dir);
|
||||
let lombok = ide_sdk::lombok::lombok_agent(
|
||||
server_root,
|
||||
ide_sdk::lombok::agent_in_args(cfg.args.iter().map(String::as_str)),
|
||||
ide_tools::managed_bundle(&data_dir, "lombok"),
|
||||
ide_sdk::apply::maven_local_repository(&root, &effective),
|
||||
ide_sdk::apply::maven_local_repository(root, &effective),
|
||||
);
|
||||
if let Some(problem) = lombok.problem() {
|
||||
tracing::warn!("{problem}");
|
||||
}
|
||||
let server_jdk = ide_sdk::apply::jdtls_jdk(&root, &effective).unwrap_or_else(|e| {
|
||||
let server_jdk = ide_sdk::apply::jdtls_jdk(root, &effective).unwrap_or_else(|e| {
|
||||
cfg.launch_error = Some(e);
|
||||
None
|
||||
});
|
||||
@@ -145,7 +156,7 @@ impl Host {
|
||||
server_root,
|
||||
&data_dir,
|
||||
&jdks,
|
||||
ide_sdk::apply::project_jdk(&root, &effective).as_ref(),
|
||||
ide_sdk::apply::project_jdk(root, &effective).as_ref(),
|
||||
server_jdk.as_ref(),
|
||||
min_java,
|
||||
&bundles,
|
||||
@@ -154,8 +165,27 @@ impl Host {
|
||||
ide_sdk::jdtls::launch_directly(cfg);
|
||||
}
|
||||
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
|
||||
let excluded_poms = unlinked_maven_poms(&root, &effective);
|
||||
ide_sdk::apply::configure_maven_import(cfg, &root, &excluded_poms);
|
||||
let excluded_poms = unlinked_maven_poms(root, &effective);
|
||||
ide_sdk::apply::configure_maven_import(cfg, root, &excluded_poms);
|
||||
}));
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let root = root.clone();
|
||||
let data_dir = self.data_dir.clone();
|
||||
let sink = sink.clone();
|
||||
lsp.set_prepare_hook(Box::new(move |cfg, _, cancel| {
|
||||
let effective = settings.effective();
|
||||
if cfg.name == "jdtls" {
|
||||
crate::java_runtime::prepare(
|
||||
cfg,
|
||||
&data_dir,
|
||||
!effective.languages.java.jdtls_jdk.trim().is_empty()
|
||||
|| ide_sdk::apply::jdtls_jdk(&root, &effective).is_err(),
|
||||
&sink,
|
||||
cancel,
|
||||
);
|
||||
}
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -226,7 +256,10 @@ impl Host {
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
let effective = settings.effective();
|
||||
index.set_scope(content_roots(&effective, &root), exclude_globs(&root, &effective, &fresh));
|
||||
index.set_scope(
|
||||
index_roots(&root, content_roots(&effective, &root)),
|
||||
exclude_globs(&root, &effective, &fresh),
|
||||
);
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
@@ -234,7 +267,7 @@ impl Host {
|
||||
// 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 git_dirs = changed.iter().chain(&batch.removed).any(|p| {
|
||||
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;
|
||||
@@ -244,7 +277,10 @@ impl Host {
|
||||
if git_dirs {
|
||||
scan_repositories(&root, &repos, &settings, &sink);
|
||||
}
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
let vcs_moved = batch.vcs.iter().any(|p| vcs_path_changed(p));
|
||||
if git_dirs || vcs_moved {
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
}),
|
||||
)?
|
||||
};
|
||||
@@ -486,7 +522,9 @@ fn light_watcher(
|
||||
fn scan_repositories(root: &Path, repos: &RwLock<Repos>, settings: &SettingsStore, sink: &SharedSink) {
|
||||
let ignored = settings.effective().ignored_names();
|
||||
let skip = |p: &Path| p.file_name().is_some_and(|n| ignored.is_ignored_name(&n.to_string_lossy()));
|
||||
match Repos::discover(root, &skip) {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(&settings.effective(), root));
|
||||
match Repos::discover_roots(&roots, &skip) {
|
||||
Ok(found) => {
|
||||
if found.roots() != repos.read().roots() {
|
||||
*repos.write() = found;
|
||||
@@ -498,6 +536,10 @@ fn scan_repositories(root: &Path, repos: &RwLock<Repos>, settings: &SettingsStor
|
||||
}
|
||||
|
||||
impl Project {
|
||||
pub fn refresh_repositories(&self) {
|
||||
scan_repositories(&self.root, &self.repos, &self.settings, &self.sink);
|
||||
}
|
||||
|
||||
/// The project's git repositories.
|
||||
pub fn repos(&self) -> Repos {
|
||||
self.repos.read().clone()
|
||||
@@ -623,17 +665,23 @@ impl Project {
|
||||
q: &ide_lsp::CandidateQuery,
|
||||
cancel: &CancellationToken,
|
||||
) -> ide_lsp::CandidateFiles {
|
||||
if !q.root.starts_with(&self.root) {
|
||||
let root = self
|
||||
.content_roots()
|
||||
.into_iter()
|
||||
.chain(std::iter::once(self.root.clone()))
|
||||
.filter(|root| q.root.starts_with(root))
|
||||
.max_by_key(|root| root.components().count());
|
||||
let Some(root) = root else {
|
||||
return ide_lsp::CandidateFiles::default();
|
||||
}
|
||||
};
|
||||
let query = ide_search::WordQuery {
|
||||
word: q.word.clone(),
|
||||
dir: q.root.clone(),
|
||||
exclude: self.search_excludes(),
|
||||
limit: q.limit,
|
||||
};
|
||||
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&self.root.join(rel), None));
|
||||
match ide_search::files_with_word(&self.root, &query, Some(&filter), &|p| self.documents.text_of(p), cancel) {
|
||||
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&root.join(rel), None));
|
||||
match ide_search::files_with_word(&root, &query, Some(&filter), &|p| self.documents.text_of(p), cancel) {
|
||||
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
|
||||
Err(e) => {
|
||||
tracing::debug!("reference candidates: {}", e.message);
|
||||
@@ -670,7 +718,8 @@ impl Project {
|
||||
return;
|
||||
}
|
||||
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
|
||||
self.index.set_scope(roots.clone(), excludes.clone());
|
||||
self.lsp.set_content_roots(roots.clone());
|
||||
self.index.set_scope(index_roots(&self.root, roots.clone()), excludes.clone());
|
||||
self.watcher.set_excludes(&excludes);
|
||||
let mut watchers = self.content_watchers.lock();
|
||||
watchers.retain(|(p, _)| roots.contains(p));
|
||||
@@ -774,8 +823,16 @@ pub fn history_retention(settings: &ide_core::settings::Settings) -> ide_workspa
|
||||
}
|
||||
}
|
||||
|
||||
/// Project Structure content roots outside `root` (existing absolute directories).
|
||||
/// A workspace uses its root only for state, never as indexed content.
|
||||
fn index_roots(root: &Path, folders: Vec<PathBuf>) -> ide_index::IndexRoots {
|
||||
ide_index::IndexRoots { include_root: !root.join(ide_workspace::workspace::FILE).is_file(), folders }
|
||||
}
|
||||
|
||||
/// Workspace members in manifest order, or extra Project Structure directories.
|
||||
fn content_roots(settings: &ide_core::settings::Settings, root: &Path) -> Vec<PathBuf> {
|
||||
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root) {
|
||||
return workspace.projects;
|
||||
}
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for r in &settings.project_structure.content_roots {
|
||||
let p = PathBuf::from(r.trim());
|
||||
@@ -832,7 +889,7 @@ fn exclude_globs(root: &Path, settings: &ide_core::settings::Settings, detected:
|
||||
globs
|
||||
}
|
||||
|
||||
fn project_key(root: &Path) -> String {
|
||||
pub(crate) fn project_key(root: &Path) -> String {
|
||||
// Stable FNV-1a directory name per project for caches.
|
||||
let s = root.to_string_lossy();
|
||||
let mut h: u64 = 0xcbf29ce484222325;
|
||||
@@ -1008,3 +1065,49 @@ mod maven_linkage_tests {
|
||||
assert!(model.maven.unwrap().projects.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
fn vcs_path_changed(path: &Path) -> bool {
|
||||
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod index_event_tests {
|
||||
use super::vcs_path_changed;
|
||||
|
||||
#[test]
|
||||
fn status_write_is_suppressed_but_external_index_and_refs_refresh() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let git = |args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(dir).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&["init", "-q"]);
|
||||
let file = dir.join("file.txt");
|
||||
std::fs::write(&file, "original\n").unwrap();
|
||||
git(&["add", "file.txt"]);
|
||||
// Same contents, different stat data: status must refresh the index.
|
||||
std::fs::File::options()
|
||||
.write(true)
|
||||
.open(&file)
|
||||
.unwrap()
|
||||
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
|
||||
.unwrap();
|
||||
let index = dir.join(".git/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
let repo = ide_vcs::Repo::discover(dir).unwrap().unwrap();
|
||||
repo.status().unwrap();
|
||||
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
|
||||
assert!(!vcs_path_changed(&index));
|
||||
assert!(!vcs_path_changed(&index), "duplicate notifications for the same identity");
|
||||
for path in [".git/HEAD", ".git/refs/heads/main", ".git/packed-refs"] {
|
||||
assert!(vcs_path_changed(&dir.join(path)));
|
||||
}
|
||||
std::fs::write(&file, "external staged change\n").unwrap();
|
||||
git(&["add", "file.txt"]);
|
||||
assert!(vcs_path_changed(&index));
|
||||
assert!(vcs_path_changed(&index));
|
||||
std::fs::remove_file(&index).unwrap();
|
||||
assert!(vcs_path_changed(&index));
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
|
||||
project.documents.save(doc.id).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap().is_empty());
|
||||
assert!(vcs::vcs_blame(&host, "main", path.clone()).await.unwrap().iter().all(|l| l.author == "Test"));
|
||||
assert!(vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap().iter().all(|l| l.author == "Test"));
|
||||
// Missing working files still use configured encoding for historical content.
|
||||
project.documents.close(doc.id);
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
use ide_core::{ChangeSet, NullSink, RequestId, TextChange};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_workspace::workspace::Workspace;
|
||||
use std::{
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let roots = vec![base.join("frontend"), base.join("backend")];
|
||||
for (index, root) in roots.iter().enumerate() {
|
||||
std::fs::create_dir(root).unwrap();
|
||||
assert!(std::process::Command::new("git").args(["init", "-q"]).current_dir(root).status().unwrap().success());
|
||||
std::fs::write(root.join("same.txt"), format!("shared needle {index}\n")).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{"scripts":{"test":"echo test"}}"#).unwrap();
|
||||
}
|
||||
let root = base.join("workspace");
|
||||
Workspace::save(&root, "Full stack", vec![roots[0].clone()], true).unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
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,
|
||||
});
|
||||
std::fs::write(root.join("internal-needle.txt"), "needle").unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
assert_eq!(ops::project::info(&project).name, "Full stack");
|
||||
assert_eq!(ops::project::attach_workspace(&host, "main", &roots[1]).unwrap().as_ref(), root.as_path());
|
||||
ops::project::attach_workspace(&host, "main", &roots[1]).unwrap();
|
||||
assert_eq!(project.content_roots(), roots);
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(project.index.find_files("internal-needle", 100).is_empty());
|
||||
assert!(project.index.find_files("workspace.json", 100).is_empty());
|
||||
assert_eq!(project.index.find_files("same.txt", 100).len(), 2);
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
let configs = ops::run::configs(&host, "main").unwrap();
|
||||
for member in &roots {
|
||||
assert!(configs.iter().any(|c| c.cwd.as_ref().is_some_and(|cwd| &**cwd == member)));
|
||||
}
|
||||
let mut ids = configs.iter().map(|c| c.id.clone()).collect::<Vec<_>>();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), configs.len());
|
||||
let a = ops::doc::open(&host, "main", roots[0].join("same.txt")).await.unwrap();
|
||||
let b = ops::doc::open(&host, "main", roots[1].join("same.txt")).await.unwrap();
|
||||
assert_ne!(a.id, b.id);
|
||||
ops::doc::edit(
|
||||
&host,
|
||||
"main",
|
||||
a.id,
|
||||
a.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "unsaved ".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
let hits = Arc::new(Mutex::new(Vec::new()));
|
||||
let out = hits.clone();
|
||||
let query = serde_json::from_value(serde_json::json!({"pattern":"needle", "isRegex":false, "caseSensitive":false,"wholeWord":false,"include":[],"exclude":[],"scope":{"kind":"project"},"maxMatches":100})).unwrap();
|
||||
ops::search::start(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query,
|
||||
Arc::new(move |event| {
|
||||
if let ops::search::SearchEvent::File { file } = event {
|
||||
out.lock().unwrap().push(file);
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(hits.lock().unwrap().len(), 2);
|
||||
let found = hits.lock().unwrap().iter().map(|f| f.rel_path.clone()).collect::<Vec<_>>();
|
||||
assert!(found.contains(&"frontend/same.txt".to_owned()));
|
||||
assert!(found.contains(&"backend/same.txt".to_owned()));
|
||||
let updated = ops::project::save_workspace(&host, "main", "Frontend", vec![roots[0].clone()]).unwrap();
|
||||
assert_eq!(updated.workspace.unwrap().projects, vec![roots[0].clone()]);
|
||||
assert_eq!(project.content_roots(), vec![roots[0].clone()]);
|
||||
assert!(project.documents.text_of(&roots[0].join("same.txt")).unwrap().starts_with("unsaved"));
|
||||
assert!(roots[1].join("same.txt").exists());
|
||||
assert!(!roots[1].join(".openidea").exists());
|
||||
let invalid = base.join("invalid");
|
||||
std::fs::create_dir_all(invalid.join(".openidea")).unwrap();
|
||||
std::fs::write(invalid.join(ide_workspace::workspace::FILE), "broken").unwrap();
|
||||
assert!(host.open_project("main", &invalid).is_err());
|
||||
assert!(Arc::ptr_eq(&host.project("main").unwrap(), &project));
|
||||
host.open_project("main", &roots[0]).unwrap();
|
||||
let automatic = ops::project::attach_workspace(&host, "main", &roots[1]).unwrap();
|
||||
assert_eq!(host.project("main").unwrap().root, roots[0]);
|
||||
let automatic = host.open_project("main", &automatic).unwrap();
|
||||
assert_eq!(automatic.content_roots(), roots);
|
||||
assert_eq!(ops::project::info(&automatic).name, "frontend");
|
||||
assert!(automatic.root.starts_with(base.join("data/workspaces")));
|
||||
assert!(automatic.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(automatic.index.find_files("workspace.json", 100).is_empty());
|
||||
let updated = ops::project::save_workspace(&host, "main", "frontend", vec![roots[1].clone()]).unwrap();
|
||||
assert_eq!(updated.workspace.unwrap().projects, vec![roots[1].clone()]);
|
||||
assert_eq!(automatic.root, updated.root.as_ref());
|
||||
assert!(automatic.index.wait_idle(Duration::from_secs(10)));
|
||||
assert_eq!(automatic.index.find_files("same.txt", 100).len(), 1);
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -15,6 +15,7 @@ const ALWAYS_SKIP: &[&str] = &[".git", ".hg", ".svn", ".jj"];
|
||||
|
||||
pub(crate) struct PathFilter {
|
||||
root: PathBuf,
|
||||
include_root: bool,
|
||||
/// Content roots outside `root`, indexed as `<folder name>/<path>`.
|
||||
extra: Vec<ExtraRoot>,
|
||||
excludes: GlobSet,
|
||||
@@ -22,7 +23,7 @@ pub(crate) struct PathFilter {
|
||||
/// applies nested ignore files itself).
|
||||
gitignore: Gitignore,
|
||||
/// What the filter was built from: `(extra roots, exclude globs)`.
|
||||
config: (Vec<PathBuf>, Vec<String>),
|
||||
config: (crate::IndexRoots, Vec<String>),
|
||||
}
|
||||
|
||||
struct ExtraRoot {
|
||||
@@ -68,7 +69,7 @@ pub(crate) fn mtime_of(meta: &std::fs::Metadata) -> u64 {
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
pub(crate) fn new(root: &Path, extra_roots: &[PathBuf], exclude_globs: &[String]) -> Self {
|
||||
pub(crate) fn new(root: &Path, extra_roots: &crate::IndexRoots, exclude_globs: &[String]) -> Self {
|
||||
let mut set = GlobSetBuilder::new();
|
||||
for raw in exclude_globs {
|
||||
let p = raw.trim().trim_end_matches('/');
|
||||
@@ -92,10 +93,9 @@ impl PathFilter {
|
||||
}
|
||||
let excludes = set.build().unwrap_or_else(|_| GlobSet::empty());
|
||||
let mut extra: Vec<ExtraRoot> = Vec::new();
|
||||
for r in extra_roots {
|
||||
for r in &extra_roots.folders {
|
||||
let path = dunce::canonicalize(r).unwrap_or_else(|_| r.clone());
|
||||
let nested = path.starts_with(root)
|
||||
|| root.starts_with(&path)
|
||||
let nested = (extra_roots.include_root && (path.starts_with(root) || root.starts_with(&path)))
|
||||
|| extra.iter().any(|e| path.starts_with(&e.path) || e.path.starts_with(&path));
|
||||
if nested || !path.is_dir() {
|
||||
continue;
|
||||
@@ -105,16 +105,17 @@ impl PathFilter {
|
||||
}
|
||||
Self {
|
||||
root: root.to_owned(),
|
||||
include_root: extra_roots.include_root,
|
||||
extra,
|
||||
excludes,
|
||||
gitignore: root_ignores(root),
|
||||
config: (extra_roots.to_vec(), exclude_globs.to_vec()),
|
||||
config: (extra_roots.clone(), exclude_globs.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the filter was built from these roots and globs.
|
||||
pub(crate) fn same_config(&self, extra_roots: &[PathBuf], excludes: &[String]) -> bool {
|
||||
self.config.0 == extra_roots && self.config.1 == excludes
|
||||
pub(crate) fn same_config(&self, extra_roots: &crate::IndexRoots, excludes: &[String]) -> bool {
|
||||
&self.config.0 == extra_roots && self.config.1 == excludes
|
||||
}
|
||||
|
||||
pub(crate) fn root(&self) -> &Path {
|
||||
@@ -123,12 +124,14 @@ impl PathFilter {
|
||||
|
||||
/// The project root, then the extra content roots.
|
||||
pub(crate) fn roots(&self) -> impl Iterator<Item = &Path> {
|
||||
std::iter::once(self.root.as_path()).chain(self.extra.iter().map(|e| e.path.as_path()))
|
||||
std::iter::once(self.root.as_path())
|
||||
.filter(|_| self.include_root)
|
||||
.chain(self.extra.iter().map(|e| e.path.as_path()))
|
||||
}
|
||||
|
||||
/// The root containing `path`, its display prefix (`None` for the project root) and ignore rules.
|
||||
fn base_of(&self, path: &Path) -> Option<(&Path, Option<&str>, &Gitignore)> {
|
||||
if path.starts_with(&self.root) {
|
||||
if self.include_root && path.starts_with(&self.root) {
|
||||
return Some((&self.root, None, &self.gitignore));
|
||||
}
|
||||
self.extra
|
||||
@@ -159,6 +162,9 @@ impl PathFilter {
|
||||
/// Key of `path` in the persistent store: only files below the project root
|
||||
/// are persisted (extra content roots are rescanned when the project opens).
|
||||
pub(crate) fn store_key(&self, path: &Path) -> Option<String> {
|
||||
if !self.include_root {
|
||||
return None;
|
||||
}
|
||||
let rel = rel_string(path.strip_prefix(&self.root).ok()?);
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
@@ -290,7 +296,8 @@ mod tests {
|
||||
touch(&root, f);
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "build/\n").unwrap();
|
||||
let filter = PathFilter::new(&root, &[], &["**/node_modules".into(), "target".into(), "docs/**".into()]);
|
||||
let filter =
|
||||
PathFilter::new(&root, &vec![].into(), &["**/node_modules".into(), "target".into(), "docs/**".into()]);
|
||||
let mut found: Vec<String> =
|
||||
filter.walk(&root, &AtomicBool::new(false)).iter().filter_map(|f| filter.rel(&f.path)).collect();
|
||||
found.sort();
|
||||
@@ -313,7 +320,7 @@ mod tests {
|
||||
touch(&base, f);
|
||||
}
|
||||
std::fs::write(shared.join(".gitignore"), "out/\n").unwrap();
|
||||
let filter = PathFilter::new(&root, &[shared.clone(), root.join("src")], &["target".into()]);
|
||||
let filter = PathFilter::new(&root, &vec![shared.clone(), root.join("src")].into(), &["target".into()]);
|
||||
assert_eq!(filter.roots().count(), 2, "roots inside the project are not extra roots");
|
||||
let mut found: Vec<String> = filter
|
||||
.roots()
|
||||
@@ -327,7 +334,7 @@ mod tests {
|
||||
assert!(!filter.is_excluded(&shared.join("src/new.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("target/y.rs"), false));
|
||||
assert!(filter.is_excluded(&shared.join("out/y.rs"), false));
|
||||
assert!(filter.same_config(&[shared.clone(), root.join("src")], &["target".into()]));
|
||||
assert!(!filter.same_config(&[shared], &["target".into()]));
|
||||
assert!(filter.same_config(&vec![shared.clone(), root.join("src")].into(), &["target".into()]));
|
||||
assert!(!filter.same_config(&vec![shared].into(), &["target".into()]));
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,19 @@ pub struct ProjectIndex {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
/// Folders indexed alongside the internal state root.
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct IndexRoots {
|
||||
pub include_root: bool,
|
||||
pub folders: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl From<Vec<PathBuf>> for IndexRoots {
|
||||
fn from(folders: Vec<PathBuf>) -> Self {
|
||||
Self { include_root: true, folders }
|
||||
}
|
||||
}
|
||||
|
||||
impl ProjectIndex {
|
||||
/// Opens (or creates) the persistent index at `cache_dir` and starts a
|
||||
/// background full scan that skips files whose content hash is unchanged.
|
||||
@@ -77,7 +90,7 @@ impl ProjectIndex {
|
||||
pub fn open(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
content_roots: Vec<PathBuf>,
|
||||
content_roots: impl Into<IndexRoots>,
|
||||
excludes: Vec<String>,
|
||||
languages: Arc<LanguageRegistry>,
|
||||
syntax: Arc<Syntax>,
|
||||
@@ -88,7 +101,7 @@ impl ProjectIndex {
|
||||
return Err(ide_core::IdeError::not_found(format!("{} is not a directory", root.display())));
|
||||
}
|
||||
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
|
||||
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
|
||||
let filter = filter::PathFilter::new(&root, &content_roots.into(), &excludes);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
|
||||
Self::start(shared, root, true)
|
||||
}
|
||||
@@ -102,7 +115,7 @@ impl ProjectIndex {
|
||||
sink: SharedSink,
|
||||
) -> IdeResult<Arc<Self>> {
|
||||
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_owned());
|
||||
let filter = filter::PathFilter::new(&root, &[], &[]);
|
||||
let filter = filter::PathFilter::new(&root, &Vec::new().into(), &[]);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, None));
|
||||
Self::start(shared, root, false)
|
||||
}
|
||||
@@ -121,7 +134,8 @@ impl ProjectIndex {
|
||||
/// Changes what is indexed besides the root (content roots) and the exclude
|
||||
/// globs, rescanning in the background (unchanged files are not re-read).
|
||||
/// Returns whether anything changed.
|
||||
pub fn set_scope(&self, content_roots: Vec<PathBuf>, excludes: Vec<String>) -> bool {
|
||||
pub fn set_scope(&self, content_roots: impl Into<IndexRoots>, excludes: Vec<String>) -> bool {
|
||||
let content_roots = content_roots.into();
|
||||
if self.shared.filter().same_config(&content_roots, &excludes) {
|
||||
return false;
|
||||
}
|
||||
@@ -222,7 +236,14 @@ impl ProjectIndex {
|
||||
/// the IDE was closed) are left out. Virtual documents are always listed.
|
||||
pub fn recent_files(&self) -> Vec<PathBuf> {
|
||||
let recent = self.shared.recent.lock().clone();
|
||||
recent.into_iter().filter(|p| p.to_str().is_some_and(ide_core::text::is_virtual_uri) || p.exists()).collect()
|
||||
let filter = self.shared.filter();
|
||||
recent
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
p.to_str().is_some_and(ide_core::text::is_virtual_uri)
|
||||
|| (p.exists() && (!p.starts_with(&self.root) || filter.contains(p)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Blocks until the initial scan and every queued update has been applied
|
||||
|
||||
@@ -508,3 +508,38 @@ fn unindexed_index_never_scans_or_persists() {
|
||||
assert!(!fx.cache.exists());
|
||||
assert!(!events.lock().iter().any(|e| matches!(e, IdeEvent::Task { .. })), "no indexing task");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
|
||||
let fx = Fixture::new(&[(".openidea/workspace.json", "{}"), ("internal.rs", "fn hidden() {}")]);
|
||||
// Simulate a cache produced before the settings root was excluded.
|
||||
let old = fx.open();
|
||||
old.mark_recent(&fx.root.join("internal.rs"));
|
||||
assert!(old.wait_idle(WAIT));
|
||||
drop(old);
|
||||
let member = fx.root.join("member");
|
||||
std::fs::create_dir_all(&member).unwrap();
|
||||
std::fs::write(member.join("visible.rs"), "fn visible() {}").unwrap();
|
||||
let idx = ProjectIndex::open(
|
||||
&fx.root,
|
||||
&fx.cache,
|
||||
crate::IndexRoots { include_root: false, folders: vec![member.clone()] },
|
||||
Vec::new(),
|
||||
Arc::new(LanguageRegistry::load(None).unwrap()),
|
||||
Arc::new(Syntax::new()),
|
||||
Arc::new(NullSink),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(idx.find_files("internal", 100).is_empty());
|
||||
assert!(idx.find_files("workspace.json", 100).is_empty());
|
||||
assert!(idx.recent_files().is_empty());
|
||||
assert_eq!(idx.find_files("visible", 100).len(), 1);
|
||||
idx.update(&[fx.root.join("internal.rs"), fx.root.join(".openidea/workspace.json")], &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(symbols(&idx, "hidden", SymbolFilter::All).is_empty());
|
||||
assert_eq!(symbols(&idx, "visible", SymbolFilter::All), ["visible"]);
|
||||
idx.set_scope(crate::IndexRoots { include_root: false, folders: Vec::new() }, Vec::new());
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert!(idx.find_files("", 100).is_empty());
|
||||
}
|
||||
@@ -168,11 +168,15 @@ impl Shared {
|
||||
|
||||
fn load_persisted(&self) {
|
||||
let Some(store) = &self.store else { return };
|
||||
let root = self.filter().root().to_owned();
|
||||
let filter = self.filter();
|
||||
let root = filter.root().to_owned();
|
||||
match store.load() {
|
||||
Ok(records) => {
|
||||
let entries: Vec<FileEntry> =
|
||||
records.into_par_iter().map(|(rel, rec)| FileEntry::new(root.join(&rel), rel, rec)).collect();
|
||||
let entries: Vec<FileEntry> = records
|
||||
.into_par_iter()
|
||||
.filter(|(rel, _)| !filter.is_excluded(&root.join(rel), false))
|
||||
.map(|(rel, rec)| FileEntry::new(root.join(&rel), rel, rec))
|
||||
.collect();
|
||||
let mut d = self.data.write();
|
||||
for e in entries {
|
||||
d.insert(e);
|
||||
|
||||
@@ -21,7 +21,6 @@ futures.workspace = true
|
||||
globset.workspace = true
|
||||
toml.workspace = true
|
||||
percent-encoding = "2"
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -1176,6 +1176,40 @@ mod tests {
|
||||
assert!(matches!(back.text_edit, Some(lsp::CompletionTextEdit::InsertAndReplace(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_completion_defaults_preserve_prefix_range_and_edit_text() {
|
||||
// JDT.LS 1.63: request after `System.out.` or `System.out.Print`.
|
||||
for end in [19, 24] {
|
||||
let (_, items) = parse_completion_response(json!({
|
||||
"isIncomplete": false,
|
||||
"itemDefaults": {
|
||||
"editRange": {
|
||||
"insert": {"start": {"line":2,"character":19}, "end": {"line":2,"character":end}},
|
||||
"replace": {"start": {"line":2,"character":19}, "end": {"line":2,"character":end}}
|
||||
},
|
||||
"insertTextFormat": 2,
|
||||
"data": {"completionKinds": [2, 6]}
|
||||
},
|
||||
"items": [{
|
||||
"label": "print",
|
||||
"labelDetails": {"detail": "(Object obj)", "description": "void"},
|
||||
"kind": 2,
|
||||
"detail": "PrintStream.print(Object obj) : void",
|
||||
"filterText": "print(Object obj) : void",
|
||||
"insertText": "print",
|
||||
"textEditText": "print(${0});",
|
||||
"data": {"pid": "0", "rid": "0"}
|
||||
}]
|
||||
}));
|
||||
let item = completion_item(&Conv::utf16(), Path::new("/Main.java"), items[0].clone(), ServerId(1));
|
||||
assert_eq!(item.replace_range, Some(Range::new(p(2, 19), p(2, end))));
|
||||
assert_eq!(item.replace_range_tab, None);
|
||||
assert_eq!(item.filter_text.as_deref(), Some("print(Object obj) : void"));
|
||||
assert_eq!(item.insert_text, "print(${0});");
|
||||
assert!(item.is_snippet);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_normalisation() {
|
||||
let conv = Conv::utf16();
|
||||
|
||||
@@ -225,6 +225,24 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells jdtls the build files of `uris` changed (`java/projectConfigurationsUpdate`),
|
||||
/// so it re-imports their projects (e.g. after `~/.m2` gained an artifact it could
|
||||
/// not resolve). Best-effort: skipped while jdtls is not already running.
|
||||
pub async fn java_update_project_configs(&self, path: &Path, uris: Vec<String>) -> IdeResult<()> {
|
||||
if uris.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let java = LanguageId::new("java");
|
||||
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(run) = server.running() else { return Ok(()) };
|
||||
let identifiers: Vec<Value> = uris.iter().map(|u| json!({ "uri": u })).collect();
|
||||
run.peer
|
||||
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
|
||||
.map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e))
|
||||
}
|
||||
|
||||
/// Incremental build of the jdtls workspace (`java/buildWorkspace`), so
|
||||
/// class files are up to date before a launch.
|
||||
pub async fn java_build(&self, path: &Path) -> IdeResult<JavaBuildStatus> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Starting server processes: binary resolution and the [`Launcher`] seam.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::tool_path::search_path;
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LaunchError {
|
||||
@@ -72,8 +73,7 @@ impl Launcher for ProcessLauncher {
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<Peer, LaunchError> {
|
||||
let search = server_search_path(config);
|
||||
let binary = which::which_in(&config.command, Some(&search), root)
|
||||
.ok()
|
||||
let binary = ide_core::tool_path::find_command(&config.command, &search, root)
|
||||
.and_then(|b| resolve_rustup_proxy(&config.command, b));
|
||||
let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())];
|
||||
env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone())));
|
||||
@@ -95,7 +95,7 @@ impl Launcher for ProcessLauncher {
|
||||
}
|
||||
|
||||
fn available(&self, config: &LanguageServerConfig, root: &Path) -> bool {
|
||||
which::which_in(&config.command, Some(server_search_path(config)), root).is_ok()
|
||||
ide_core::tool_path::find_command(&config.command, &server_search_path(config), root).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,9 +104,6 @@ fn server_search_path(config: &LanguageServerConfig) -> OsString {
|
||||
config.env.get("PATH").map(OsString::from).unwrap_or_else(search_path)
|
||||
}
|
||||
|
||||
/// `PATH` plus the login shell's `PATH` and common tool directories, so
|
||||
/// servers resolve even when the app is launched from a GUI shell with a
|
||||
/// minimal environment.
|
||||
/// `~/.cargo/bin/<tool>` is usually a rustup proxy that fails when the active
|
||||
/// toolchain lacks the component (common for rust-analyzer). In that case use
|
||||
/// the newest installed toolchain that ships the binary; with none, the tool is
|
||||
@@ -153,74 +150,6 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn search_path() -> OsString {
|
||||
static PATH: OnceLock<OsString> = OnceLock::new();
|
||||
PATH.get_or_init(|| {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(shell_path) = login_shell_path() {
|
||||
dirs.extend(std::env::split_paths(&shell_path));
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".bun/bin", ".deno/bin", ".npm-global/bin", ".volta/bin"]
|
||||
{
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
// nvm: newest installed node's bin.
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
dirs.retain(|d| !d.as_os_str().is_empty() && seen.insert(d.clone()));
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn login_shell_path() -> Option<OsString> {
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
let shell = std::env::var_os("SHELL")?;
|
||||
const MARK: &str = "__OPENIDEA_PATH__";
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(shell))
|
||||
.args(["-l", "-c", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
child.stdout.take()?.read_to_string(&mut out).ok()?;
|
||||
let start = out.find(MARK)? + MARK.len();
|
||||
let end = start + out[start..].find(MARK)?;
|
||||
Some(OsString::from(&out[start..end]))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn login_shell_path() -> Option<OsString> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Workspace root for `file`: the outermost ancestor within `project_root`
|
||||
/// containing a root marker (so a Cargo/npm workspace gets one server, not one
|
||||
/// per member), else `project_root`. `None` when `file` is outside the project.
|
||||
@@ -258,11 +187,26 @@ mod tests {
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_root_needs_a_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("apps/web/src/app.ts");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["angular.json".to_string(), "node_modules/@angular/core".to_string()];
|
||||
assert_eq!(marked_root(root, &file, &markers), None);
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
|
||||
assert_eq!(marked_root(root, &file, &markers), Some(root.join("apps/web")));
|
||||
assert_eq!(marked_root(root, &root.join("apps/api/main.ts"), &markers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_path_contains_env_path() {
|
||||
let p = search_path();
|
||||
let dirs: Vec<PathBuf> = std::env::split_paths(&p).collect();
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")));
|
||||
// The process's own `PATH` starts the search, then per-user and system dirs.
|
||||
let first_env = std::env::split_paths(&std::env::var_os("PATH").unwrap()).find(|d| d.is_absolute()).unwrap();
|
||||
assert_eq!(dirs.first(), Some(&first_env), "{dirs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ mod uri;
|
||||
mod virtual_doc;
|
||||
|
||||
pub use inspect::{FileInspection, InspectHost, InspectOptions};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
|
||||
|
||||
@@ -75,6 +75,8 @@ pub type ApplyEditHook = Arc<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>;
|
||||
/// settings before each launch; receives the server's workspace root.
|
||||
pub type ConfigFn = dyn Fn(&mut LanguageServerConfig, &Path) + Send + Sync;
|
||||
pub type ConfigHook = Arc<ConfigFn>;
|
||||
/// Prepares dependencies on a blocking worker immediately before launching an installed server.
|
||||
pub type PrepareFn = dyn Fn(&LanguageServerConfig, &Path, &CancellationToken) + Send + Sync;
|
||||
/// The servers a language uses, from its definition's list (user settings
|
||||
/// disable some and add others).
|
||||
pub type ServersFn = dyn Fn(&LanguageId, &[LanguageServerConfig]) -> Vec<LanguageServerConfig> + Send + Sync;
|
||||
@@ -155,6 +157,7 @@ impl DocSnap {
|
||||
pub struct LspManager {
|
||||
me: Weak<LspManager>,
|
||||
project_root: PathBuf,
|
||||
content_roots: RwLock<Vec<PathBuf>>,
|
||||
languages: Arc<LanguageRegistry>,
|
||||
sink: SharedSink,
|
||||
launcher: Arc<dyn Launcher>,
|
||||
@@ -163,6 +166,7 @@ pub struct LspManager {
|
||||
docs: Mutex<HashMap<DocId, DocState>>,
|
||||
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
|
||||
config_hook: RwLock<Option<ConfigHook>>,
|
||||
prepare_hook: RwLock<Option<Arc<PrepareFn>>>,
|
||||
servers_hook: RwLock<Option<Arc<ServersFn>>>,
|
||||
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
@@ -283,6 +287,7 @@ impl LspManager {
|
||||
Arc::new_cyclic(|me| Self {
|
||||
me: me.clone(),
|
||||
project_root,
|
||||
content_roots: RwLock::new(Vec::new()),
|
||||
languages,
|
||||
sink,
|
||||
launcher,
|
||||
@@ -291,6 +296,7 @@ impl LspManager {
|
||||
docs: Mutex::new(HashMap::new()),
|
||||
apply_edit_hook: RwLock::new(None),
|
||||
config_hook: RwLock::new(None),
|
||||
prepare_hook: RwLock::new(None),
|
||||
servers_hook: RwLock::new(None),
|
||||
candidates_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
@@ -302,9 +308,24 @@ impl LspManager {
|
||||
|
||||
// ---- server lookup & lifecycle ----
|
||||
|
||||
pub fn set_content_roots(&self, roots: Vec<PathBuf>) {
|
||||
*self.content_roots.write() = roots;
|
||||
}
|
||||
|
||||
fn project_root_for(&self, path: &Path) -> PathBuf {
|
||||
self.content_roots
|
||||
.read()
|
||||
.iter()
|
||||
.chain(std::iter::once(&self.project_root))
|
||||
.filter(|root| path.starts_with(root))
|
||||
.max_by_key(|root| root.components().count())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| self.project_root.clone())
|
||||
}
|
||||
|
||||
fn server_for(&self, cfg: &LanguageServerConfig, language: &LanguageId, path: &Path) -> Arc<Server> {
|
||||
let mut servers = self.servers.lock();
|
||||
let root = launch::find_root(&self.project_root, path, &cfg.root_markers).unwrap_or_else(|| {
|
||||
let root = launch::find_root(&self.project_root_for(path), path, &cfg.root_markers).unwrap_or_else(|| {
|
||||
// Outside the project (library sources, …): reuse a running instance.
|
||||
servers
|
||||
.iter()
|
||||
@@ -332,7 +353,9 @@ impl LspManager {
|
||||
if sc.fallback && available_before {
|
||||
continue;
|
||||
}
|
||||
if sc.require_root_marker && launch::marked_root(&self.project_root, path, &sc.root_markers).is_none() {
|
||||
if sc.require_root_marker
|
||||
&& launch::marked_root(&self.project_root_for(path), path, &sc.root_markers).is_none()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let server = self.server_for(sc, language, path);
|
||||
@@ -408,7 +431,16 @@ impl LspManager {
|
||||
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
|
||||
// servers may take a while to start listening.
|
||||
let launched = tokio::task::spawn_blocking(move || {
|
||||
let cfg = me.configured(&tail);
|
||||
let mut cfg = me.configured(&tail);
|
||||
tail.set_effective_config(cfg.clone());
|
||||
let prepare = me.prepare_hook.read().clone();
|
||||
if !cancel.is_cancelled()
|
||||
&& me.launcher.available(&cfg, &tail.root)
|
||||
&& let Some(prepare) = prepare
|
||||
{
|
||||
prepare(&cfg, &tail.root, &cancel);
|
||||
cfg = me.configured(&tail);
|
||||
}
|
||||
tail.set_effective_config(cfg.clone());
|
||||
let root = tail.root.clone();
|
||||
if let Some(message) = &cfg.launch_error {
|
||||
@@ -1380,21 +1412,34 @@ impl LspManager {
|
||||
/// server's analysis scope that mention the name are opened for the request.
|
||||
/// Every server that can rename there does: the Angular server adds the
|
||||
/// templates to vtsls's edit, whose own edits win where both change the same text.
|
||||
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
|
||||
pub async fn rename(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Renamed> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let renaming = self.rename_targets(&snap, &targets, pos).await;
|
||||
let edits = join_all(renaming.into_iter().map(|t| self.rename_on(&snap, t, pos, &new_name))).await;
|
||||
let edits = join_all(renaming.into_iter().map(|t| self.rename_on(&snap, t, pos, &new_name, &cancel))).await;
|
||||
let mut out = Outcome::new();
|
||||
let mut incomplete = None;
|
||||
for edit in edits {
|
||||
match edit {
|
||||
Ok(edit) => match &mut out.value {
|
||||
Some(merged) => convert::merge_workspace_edit(merged, edit),
|
||||
None => out.value = Some(edit),
|
||||
},
|
||||
Ok(renamed) => {
|
||||
incomplete = incomplete.or(renamed.incomplete);
|
||||
match &mut out.value {
|
||||
Some(merged) => convert::merge_workspace_edit(merged, renamed.edit),
|
||||
None => out.value = Some(renamed.edit),
|
||||
}
|
||||
}
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(WorkspaceEdit::default())
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(Renamed { edit: out.finish(WorkspaceEdit::default())?, incomplete })
|
||||
}
|
||||
|
||||
/// The servers that can rename at `pos`, the first one when none can (a
|
||||
@@ -1411,16 +1456,27 @@ impl LspManager {
|
||||
vec![&targets[0]]
|
||||
}
|
||||
|
||||
async fn rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos, new_name: &str) -> IdeResult<WorkspaceEdit> {
|
||||
async fn rename_on(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
t: &Target,
|
||||
pos: Pos,
|
||||
new_name: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Renamed> {
|
||||
let query = || async {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["newName"] = json!(new_name);
|
||||
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
|
||||
let r: Option<lsp::WorkspaceEdit> =
|
||||
self.call(t, "textDocument/rename", params, Some(cancel), LONG_TIMEOUT).await?;
|
||||
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
|
||||
};
|
||||
// The Angular server renames in the file's own project only, whatever is open.
|
||||
if t.server.name == angular::SERVER {
|
||||
return query().await;
|
||||
let edit = query().await?;
|
||||
let empty = edit.files.is_empty();
|
||||
let w = scope::Widened::only((), empty, &t.server);
|
||||
return Ok(Renamed { edit, incomplete: w.incomplete });
|
||||
}
|
||||
let files = |e: &WorkspaceEdit| {
|
||||
e.files
|
||||
@@ -1431,9 +1487,9 @@ impl LspManager {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let w = self.widened(snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
let w = self.widened(snap, t, pos, cancel, query, files).await?;
|
||||
// The second edit covers the first: its files stay analysed.
|
||||
Ok(w.second.unwrap_or(w.first))
|
||||
Ok(Renamed { edit: w.second.unwrap_or(w.first), incomplete: w.incomplete })
|
||||
}
|
||||
|
||||
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
|
||||
@@ -1728,11 +1784,14 @@ impl LspManager {
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
direction: HierarchyDirection,
|
||||
) -> IdeResult<Vec<HierarchyItem>> {
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<CallHierarchy> {
|
||||
let (snap, targets) = self.doc_targets(doc, "call hierarchy", |c| c.has("callHierarchyProvider")).await?;
|
||||
let t = &targets[0];
|
||||
let items: Option<Vec<lsp::CallHierarchyItem>> =
|
||||
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
|
||||
let cancel = &cancel;
|
||||
let items: Option<Vec<lsp::CallHierarchyItem>> = self
|
||||
.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), Some(cancel), DEFAULT_TIMEOUT)
|
||||
.await?;
|
||||
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
|
||||
let query = || async {
|
||||
let mut out = Vec::new();
|
||||
@@ -1741,7 +1800,7 @@ impl LspManager {
|
||||
match direction {
|
||||
HierarchyDirection::Incoming => {
|
||||
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
|
||||
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
|
||||
self.call(t, "callHierarchy/incomingCalls", params, Some(cancel), LONG_TIMEOUT).await?;
|
||||
let conv = self.conv(t.enc());
|
||||
for c in calls.unwrap_or_default() {
|
||||
let (path, _) = uri_target(c.from.uri.as_str());
|
||||
@@ -1751,7 +1810,7 @@ impl LspManager {
|
||||
}
|
||||
HierarchyDirection::Outgoing => {
|
||||
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
|
||||
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
|
||||
self.call(t, "callHierarchy/outgoingCalls", params, Some(cancel), LONG_TIMEOUT).await?;
|
||||
let conv = self.conv(t.enc());
|
||||
let (src, _) = uri_target(item.uri.as_str());
|
||||
for c in calls.unwrap_or_default() {
|
||||
@@ -1763,19 +1822,22 @@ impl LspManager {
|
||||
}
|
||||
Ok(out)
|
||||
};
|
||||
let out = match direction {
|
||||
let (out, incomplete) = match direction {
|
||||
// Callers are references: they may sit in files outside the server's scope.
|
||||
HierarchyDirection::Incoming => {
|
||||
let files = |v: &Vec<HierarchyItem>| {
|
||||
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
|
||||
};
|
||||
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
w.second.unwrap_or(w.first)
|
||||
let w = self.widened(&snap, t, pos, cancel, query, files).await?;
|
||||
(w.second.unwrap_or(w.first), w.incomplete)
|
||||
}
|
||||
HierarchyDirection::Outgoing => query().await?,
|
||||
HierarchyDirection::Outgoing => (query().await?, None),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
|
||||
Ok(out)
|
||||
Ok(CallHierarchy { items: out, incomplete })
|
||||
}
|
||||
|
||||
pub async fn type_hierarchy(
|
||||
@@ -1901,6 +1963,10 @@ impl LspManager {
|
||||
*self.config_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
pub fn set_prepare_hook(&self, hook: Box<PrepareFn>) {
|
||||
*self.prepare_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// Installed by `src-tauri` to apply the servers enabled / defined in settings.
|
||||
pub fn set_servers_hook(&self, hook: Box<ServersFn>) {
|
||||
*self.servers_hook.write() = Some(Arc::from(hook));
|
||||
@@ -1921,9 +1987,22 @@ impl LspManager {
|
||||
/// Servers no longer enabled stop; newly enabled ones attach to open documents.
|
||||
pub async fn reconfigure(&self) {
|
||||
self.stop_unlisted().await;
|
||||
let Some(me) = self.me.upgrade() else { return };
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
for s in servers {
|
||||
let next = self.configured(&s);
|
||||
// The settings hook may run tools (`npm root -g`), as when the server starts.
|
||||
let next = match tokio::task::spawn_blocking({
|
||||
let (me, s) = (me.clone(), s.clone());
|
||||
move || me.configured(&s)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(next) => next,
|
||||
Err(e) => {
|
||||
tracing::warn!("{}: settings hook failed: {e}", s.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let current = s.effective_config();
|
||||
if next == current {
|
||||
continue;
|
||||
@@ -2216,7 +2295,7 @@ mod send_check {
|
||||
assert_send(m.hover(doc, Pos::default(), CancellationToken::new()));
|
||||
assert_send(m.code_lens(doc));
|
||||
assert_send(m.workspace_symbols("", CancellationToken::new()));
|
||||
assert_send(m.call_hierarchy(doc, Pos::default(), HierarchyDirection::Incoming));
|
||||
assert_send(m.call_hierarchy(doc, Pos::default(), HierarchyDirection::Incoming, CancellationToken::new()));
|
||||
assert_send(m.restart(ide_core::ServerId(1)));
|
||||
assert_send(m.shutdown_all());
|
||||
assert_send(m.semantic_tokens(doc));
|
||||
|
||||
@@ -138,6 +138,9 @@ impl LspManager {
|
||||
return Ok(Widened { first, second: None, incomplete });
|
||||
}
|
||||
let opened = self.open_transient(t, files, cancel).await;
|
||||
if opened.skipped {
|
||||
incomplete = incomplete.or(Some(ReferencesIncomplete::FilesSkipped));
|
||||
}
|
||||
if opened.files.is_empty() {
|
||||
return Ok(Widened { first, second: None, incomplete });
|
||||
}
|
||||
@@ -160,22 +163,37 @@ impl LspManager {
|
||||
}
|
||||
|
||||
/// Opens `files` on `t` (read from disk) unless the user has them open;
|
||||
/// they are closed when the returned guard drops.
|
||||
/// they are closed when the returned guard drops. Files too large or not
|
||||
/// readable as text are left out and flagged on the guard.
|
||||
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
|
||||
let read = {
|
||||
// The server already sees the user's files, however large.
|
||||
let open: HashSet<PathBuf> = self.docs.lock().values().map(|d| d.path.clone()).collect();
|
||||
let (read, skipped) = {
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
files
|
||||
.into_iter()
|
||||
.take_while(|_| !cancel.is_cancelled())
|
||||
.filter(|f| std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() <= MAX_CANDIDATE_BYTES))
|
||||
.filter_map(|f| std::fs::read_to_string(&f).ok().map(|text| (f, text)))
|
||||
.collect::<Vec<_>>()
|
||||
let mut read = Vec::new();
|
||||
let mut skipped = false;
|
||||
for f in files.into_iter().filter(|f| !open.contains(f)) {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
// A file gone since the search no longer mentions anything.
|
||||
let Ok(meta) = std::fs::metadata(&f) else { continue };
|
||||
if !meta.is_file() {
|
||||
continue;
|
||||
}
|
||||
match (meta.len() <= MAX_CANDIDATE_BYTES).then(|| std::fs::read_to_string(&f)) {
|
||||
Some(Ok(text)) => read.push((f, text)),
|
||||
_ => skipped = true,
|
||||
}
|
||||
}
|
||||
(read, skipped)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let mut guard = TransientFiles { mgr: self, server: t.server.clone(), run: t.run.clone(), files: Vec::new() };
|
||||
let mut guard = TransientFiles::empty(self, t);
|
||||
guard.skipped = skipped;
|
||||
if cancel.is_cancelled() {
|
||||
return guard;
|
||||
}
|
||||
@@ -206,6 +224,8 @@ pub(crate) struct TransientFiles<'a> {
|
||||
server: Arc<Server>,
|
||||
run: Running,
|
||||
pub files: Vec<(PathBuf, lsp::Uri)>,
|
||||
/// Candidates that could not be opened.
|
||||
pub skipped: bool,
|
||||
}
|
||||
|
||||
impl TransientFiles<'_> {
|
||||
@@ -226,7 +246,7 @@ impl TransientFiles<'_> {
|
||||
|
||||
impl<'a> TransientFiles<'a> {
|
||||
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
|
||||
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new() }
|
||||
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new(), skipped: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +331,8 @@ pub enum ReferencesIncomplete {
|
||||
Indexing,
|
||||
/// More project files mention the name than were checked.
|
||||
TooManyFiles,
|
||||
/// Files that mention the name were too large or unreadable to check.
|
||||
FilesSkipped,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
@@ -339,3 +341,17 @@ pub struct References {
|
||||
pub locations: Vec<Location>,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Renamed {
|
||||
pub edit: WorkspaceEdit,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CallHierarchy {
|
||||
pub items: Vec<HierarchyItem>,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
@@ -359,6 +359,29 @@ fn change(range: Range, text: &str) -> AppliedChange {
|
||||
|
||||
// ------------------------------------------------------------------ tests
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn linked_projects_initialize_separate_language_server_roots() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let first = tempfile::tempdir().unwrap();
|
||||
let second = tempfile::tempdir().unwrap();
|
||||
let roots = vec![first.path().to_path_buf(), second.path().to_path_buf()];
|
||||
h.mgr.set_content_roots(roots.clone());
|
||||
for root in &roots {
|
||||
let file = root.join("same.mk");
|
||||
std::fs::write(&file, "hello").unwrap();
|
||||
h.mgr.did_open(DocId::next(), &file, &h.lang, 1, "hello");
|
||||
}
|
||||
let server = h.launcher.state("mock");
|
||||
eventually(|| server.requested("initialize").len() == 2).await;
|
||||
let mut actual: Vec<_> =
|
||||
server.requested("initialize").iter().map(|r| r["rootUri"].as_str().unwrap().to_owned()).collect();
|
||||
let mut expected: Vec<_> = roots.iter().map(|p| uri_of(p)).collect();
|
||||
actual.sort();
|
||||
expected.sort();
|
||||
assert_eq!(actual, expected);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn initialize_and_incremental_sync() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -905,6 +928,38 @@ async fn launch_error_fails_without_starting_the_server() {
|
||||
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn preparation_refreshes_config_and_survives_unchanged_settings() {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let prepared = Arc::new(AtomicBool::new(false));
|
||||
let started = Arc::new(AtomicUsize::new(0));
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let wait = Mutex::new(wait);
|
||||
h.mgr.set_config_hook(Box::new({
|
||||
let prepared = prepared.clone();
|
||||
move |cfg, _| {
|
||||
cfg.launch_error = (!prepared.load(Ordering::SeqCst)).then(|| "needs runtime".into());
|
||||
}
|
||||
}));
|
||||
h.mgr.set_prepare_hook(Box::new({
|
||||
let started = started.clone();
|
||||
move |_, _, cancel| {
|
||||
started.fetch_add(1, Ordering::SeqCst);
|
||||
wait.lock().recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(!cancel.is_cancelled(), "unchanged settings cancelled preparation");
|
||||
prepared.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
h.open("a.mk", "x");
|
||||
eventually(|| started.load(Ordering::SeqCst) > 0).await;
|
||||
h.mgr.reconfigure().await;
|
||||
release.send(()).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
assert_eq!(started.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_changes_reach_servers_without_restarts() {
|
||||
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
|
||||
@@ -1113,7 +1168,7 @@ async fn navigation_rename_format_and_decorations() {
|
||||
s.respond("textDocument/prepareRename", json!({ "range": r(1,0,1,3), "placeholder": "foo" }));
|
||||
assert_eq!(h.mgr.prepare_rename(doc, Pos::new(1, 1)).await.unwrap(), Some(rng(1, 0, 1, 3)));
|
||||
s.respond("textDocument/rename", json!({ "changes": { uri.clone(): [{ "range": r(0,3,0,6), "newText": "bar" }, { "range": r(1,0,1,3), "newText": "bar" }] } }));
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 1), "bar".into()).await.unwrap();
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 1), "bar".into(), Default::default()).await.unwrap().edit;
|
||||
assert!(matches!(&edit.files[0], FileEdit::Edit { edits, .. } if edits.len() == 2));
|
||||
assert_eq!(s.requested("textDocument/rename")[0]["newName"], "bar");
|
||||
|
||||
@@ -1150,13 +1205,19 @@ async fn navigation_rename_format_and_decorations() {
|
||||
|
||||
// Nothing to prepare at the position: NotFound, so the UI can retry at the enclosing declaration.
|
||||
s.respond("textDocument/prepareCallHierarchy", json!(null));
|
||||
let err = h.mgr.call_hierarchy(doc, Pos::new(0, 1), HierarchyDirection::Incoming).await.unwrap_err();
|
||||
let err =
|
||||
h.mgr.call_hierarchy(doc, Pos::new(0, 1), HierarchyDirection::Incoming, Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
|
||||
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
|
||||
s.respond("textDocument/prepareCallHierarchy", json!([item]));
|
||||
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
|
||||
let calls = h.mgr.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming).await.unwrap();
|
||||
let calls = h
|
||||
.mgr
|
||||
.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.items;
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].name, "main");
|
||||
assert_eq!(calls[0].from_ranges, vec![rng(1, 0, 1, 3)]);
|
||||
@@ -1201,7 +1262,7 @@ async fn rename_merges_the_servers_that_can_rename_there() {
|
||||
);
|
||||
|
||||
assert_eq!(h.mgr.prepare_rename(doc, Pos::new(0, 15)).await.unwrap(), Some(rng(0, 14, 0, 19)));
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 15), "heading".into()).await.unwrap();
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 15), "heading".into(), Default::default()).await.unwrap().edit;
|
||||
assert_eq!(edits_in(&edit, &path).len(), 2);
|
||||
assert!(h.launcher.state("ts").requested("textDocument/rename").is_empty());
|
||||
|
||||
@@ -1213,7 +1274,7 @@ async fn rename_merges_the_servers_that_can_rename_there() {
|
||||
"textDocument/rename",
|
||||
json!({ "changes": { uri: [{ "range": r(1, 0, 5), "newText": "heading: x" }] } }),
|
||||
);
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 2), "heading".into()).await.unwrap();
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 2), "heading".into(), Default::default()).await.unwrap().edit;
|
||||
assert_eq!(edits_in(&edit, &path), [(rng(0, 14, 0, 19), "heading".into()), (rng(1, 0, 1, 5), "heading: x".into())]);
|
||||
assert_eq!(edits_in(&edit, &html), [(rng(0, 3, 0, 8), "heading".into())]);
|
||||
}
|
||||
@@ -1749,7 +1810,7 @@ fn occurrences(uri: &str, text: &str) -> Vec<Value> {
|
||||
/// A server that only analyses its open documents (minus `blind` URIs), like
|
||||
/// Pyright for files outside its `include`.
|
||||
fn open_files_only(blind: Vec<String>) -> Responder {
|
||||
Arc::new(move |s, method, _| {
|
||||
Arc::new(move |s, method, params| {
|
||||
let docs: Vec<(String, String)> =
|
||||
s.docs.lock().iter().filter(|(u, _)| !blind.contains(u)).map(|(u, t)| (u.clone(), t.clone())).collect();
|
||||
let locs = || docs.iter().flat_map(|(u, t)| occurrences(u, t));
|
||||
@@ -1763,6 +1824,19 @@ fn open_files_only(blind: Vec<String>) -> Responder {
|
||||
}
|
||||
Some(json!({ "changes": changes }))
|
||||
}
|
||||
"textDocument/prepareCallHierarchy" => {
|
||||
let uri = ¶ms["textDocument"]["uri"];
|
||||
let at = json!({ "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } });
|
||||
Some(json!([{ "name": WORD, "kind": 12, "uri": uri, "range": at, "selectionRange": at }]))
|
||||
}
|
||||
"callHierarchy/incomingCalls" => Some(Value::Array(
|
||||
locs()
|
||||
.map(|l| {
|
||||
let from = json!({ "name": "caller", "kind": 12, "uri": l["uri"], "range": l["range"], "selectionRange": l["range"] });
|
||||
json!({ "from": from, "fromRanges": [l["range"]] })
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
@@ -1884,6 +1958,113 @@ async fn references_report_a_capped_candidate_search() {
|
||||
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
|
||||
}
|
||||
|
||||
/// What each search widened with candidate files reports for the symbol at the start of `doc`.
|
||||
async fn incomplete_reports(h: &Harness, doc: DocId) -> Vec<(&'static str, Option<ReferencesIncomplete>)> {
|
||||
let at = Pos::new(0, 5);
|
||||
let cancel = ide_core::CancellationToken::new;
|
||||
vec![
|
||||
("references", h.mgr.references(doc, at, true, true, cancel()).await.unwrap().incomplete),
|
||||
("rename", h.mgr.rename(doc, at, "renamed".into(), cancel()).await.unwrap().incomplete),
|
||||
("callers", h.mgr.call_hierarchy(doc, at, HierarchyDirection::Incoming, cancel()).await.unwrap().incomplete),
|
||||
]
|
||||
}
|
||||
|
||||
fn expect_all(reports: Vec<(&'static str, Option<ReferencesIncomplete>)>, want: Option<ReferencesIncomplete>) {
|
||||
for (search, got) in reports {
|
||||
assert_eq!(got, want, "{search}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn every_widened_search_reports_a_capped_candidate_search() {
|
||||
let (h, s) = scope_harness();
|
||||
h.mgr.set_candidates_hook(Box::new(|q, _| ide_lsp::CandidateFiles {
|
||||
files: vec![q.root.join("b.mk")],
|
||||
limit_hit: true,
|
||||
}));
|
||||
std::fs::write(h.root.join("b.mk"), "target\n").unwrap();
|
||||
let (doc, _) = h.open("a.mk", "def target\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
expect_all(incomplete_reports(&h, doc).await, Some(ReferencesIncomplete::TooManyFiles));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn every_widened_search_reports_candidates_it_could_not_open() {
|
||||
let oversized = "target\n".repeat(200_000);
|
||||
// Name, content (`None`: not on disk), whether the search misses it.
|
||||
let cases: [(&str, Option<&[u8]>, bool); 4] = [
|
||||
("large.mk", Some(oversized.as_bytes()), true),
|
||||
("binary.mk", Some(b"target \xff\xfe\n"), true),
|
||||
("deleted.mk", None, false),
|
||||
("small.mk", Some(b"target\n"), false),
|
||||
];
|
||||
for (name, content, missed) in cases {
|
||||
let (h, s) = scope_harness();
|
||||
let file = h.root.join(name);
|
||||
if let Some(content) = content {
|
||||
std::fs::write(&file, content).unwrap();
|
||||
}
|
||||
let listed = file.clone();
|
||||
h.mgr.set_candidates_hook(Box::new(move |_, _| ide_lsp::CandidateFiles {
|
||||
files: vec![listed.clone()],
|
||||
limit_hit: false,
|
||||
}));
|
||||
let (doc, _) = h.open("a.mk", "def target\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let want = missed.then_some(ReferencesIncomplete::FilesSkipped);
|
||||
for (search, got) in incomplete_reports(&h, doc).await {
|
||||
assert_eq!(got, want, "{name}: {search}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_large_file_the_user_has_open_is_not_reported_as_skipped() {
|
||||
let (h, s) = scope_harness();
|
||||
let large = "target\n".repeat(200_000);
|
||||
let (_, path) = h.open("large.mk", &large);
|
||||
let (doc, _) = h.open("a.mk", "def target\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 2).await;
|
||||
h.mgr.set_candidates_hook(Box::new(move |_, _| ide_lsp::CandidateFiles {
|
||||
files: vec![path.clone()],
|
||||
limit_hit: false,
|
||||
}));
|
||||
// `covered` would hide the file: answer as if the server had not listed it.
|
||||
*s.responder.lock() = Some(open_files_only(vec![uri_of(&h.root.join("large.mk"))]));
|
||||
expect_all(incomplete_reports(&h, doc).await, None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_and_callers_can_be_cancelled() {
|
||||
let (h, s) = scope_harness();
|
||||
h.mgr.set_candidates_hook(Box::new(|_, cancel| {
|
||||
while !cancel.is_cancelled() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
ide_lsp::CandidateFiles::default()
|
||||
}));
|
||||
let (doc, _) = h.open("a.mk", "def target\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let cancel_later = || {
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
let later = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
later.cancel();
|
||||
});
|
||||
cancel
|
||||
};
|
||||
let err = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into(), cancel_later()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
let err =
|
||||
h.mgr.call_hierarchy(doc, Pos::new(0, 5), HierarchyDirection::Incoming, cancel_later()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelling_a_references_search_stops_the_candidate_search_and_closes_files() {
|
||||
let (h, s) = scope_harness();
|
||||
@@ -2064,7 +2245,7 @@ async fn rename_edits_files_outside_the_analysis_scope() {
|
||||
let (doc, a) = h.open("a.mk", "def target\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
eventually(|| s.docs.lock().len() == 1).await;
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into()).await.unwrap();
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into(), Default::default()).await.unwrap().edit;
|
||||
let mut paths: Vec<PathBuf> = edit
|
||||
.files
|
||||
.iter()
|
||||
|
||||
@@ -297,7 +297,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
|
||||
/// Vue Language Server 3 in hybrid mode: its `tsserver/request`s go through the
|
||||
/// client to vtsls with `@vue/typescript-plugin` (issue #25). Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@"<7" @vtsls/language-server`.
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vue/language-server typescript@6 @vtsls/language-server`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vue/language-server and @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn vue_hybrid_mode_end_to_end() {
|
||||
@@ -444,13 +444,13 @@ async fn angular_language_server_end_to_end() {
|
||||
let count = Pos::new(4, 20);
|
||||
let range = mgr.prepare_rename(inline, count).await.unwrap();
|
||||
assert_eq!(range, Some(Range::new(Pos::new(4, 19), Pos::new(4, 24))));
|
||||
let edit = mgr.rename(inline, count, "total".into()).await.unwrap();
|
||||
let edit = mgr.rename(inline, count, "total".into(), Default::default()).await.unwrap().edit;
|
||||
assert_eq!(edited_lines(&edit, &inline_ts), [4, 7], "{edit:?}");
|
||||
|
||||
// `title` in the class, which both servers rename: vtsls's edit and the
|
||||
// template's from the Angular server.
|
||||
let title = Pos::new(7, 3);
|
||||
let edit = mgr.rename(ts, title, "heading".into()).await.unwrap();
|
||||
let edit = mgr.rename(ts, title, "heading".into(), Default::default()).await.unwrap().edit;
|
||||
assert_eq!((edited_lines(&edit, &app_ts), edited_lines(&edit, &app_html)), (vec![7], vec![0]), "{edit:?}");
|
||||
// Its usage in the template, the declaration left out, from either file.
|
||||
for (doc, pos) in [(ts, title), (html, Pos::new(0, 8))] {
|
||||
|
||||
@@ -17,7 +17,8 @@ tokio.workspace = true
|
||||
portable-pty.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
zip.workspace = true
|
||||
quick-xml = "0.42"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -8,6 +8,7 @@ pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
pub mod tomcat;
|
||||
mod utf8;
|
||||
pub mod which;
|
||||
pub mod wrap;
|
||||
|
||||
@@ -139,7 +139,7 @@ pub(crate) fn invocation(config: &RunConfig, cwd: &Path) -> Invocation {
|
||||
if config.args.is_empty() && looks_like_shell && !cwd.join(command).is_file() {
|
||||
return shell_invocation(command, windows, std::env::var("COMSPEC").ok());
|
||||
}
|
||||
let program = resolve_program(command, cwd, &config.env, windows);
|
||||
let program = resolve_program(command, cwd, config, windows);
|
||||
let mut display = quote(command);
|
||||
for a in &config.args {
|
||||
display.push(' ');
|
||||
@@ -239,22 +239,18 @@ fn shell_invocation(command: &str, windows: bool, comspec: Option<String>) -> In
|
||||
}
|
||||
|
||||
/// The program to spawn: relative paths like `./gradlew` or `.venv/bin/python`
|
||||
/// against the run directory; on Windows a bare name through `PATH` × `PATHEXT`
|
||||
/// (`kotlinc` → `kotlinc.bat`), which `Command` would only try as `.exe`.
|
||||
fn resolve_program(command: &str, cwd: &Path, env: &BTreeMap<String, String>, windows: bool) -> PathBuf {
|
||||
/// against the run directory; a bare name through the configuration's search path
|
||||
/// (on Windows also `PATHEXT`: `kotlinc` → `kotlinc.bat`), so launchers installed
|
||||
/// outside the app's own `PATH` (`mvn` in a version manager's shims) still start.
|
||||
fn resolve_program(command: &str, cwd: &Path, config: &RunConfig, windows: bool) -> PathBuf {
|
||||
let path = Path::new(command);
|
||||
if path.is_relative() && path.components().count() > 1 {
|
||||
return cwd.join(path);
|
||||
}
|
||||
if windows && path.components().count() == 1 && path.is_relative() {
|
||||
let search = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| std::env::var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
if path.components().count() == 1 && path.is_relative() {
|
||||
let search = crate::wrap::search_path(config);
|
||||
let pathext = std::env::var("PATHEXT").ok();
|
||||
if let Some(found) = crate::which::find_executable_in(command, &search, true, pathext.as_deref()) {
|
||||
if let Some(found) = crate::which::find_executable_in(command, &search, windows, pathext.as_deref()) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -1032,14 +1028,28 @@ mod tests {
|
||||
let cwd = dir.path();
|
||||
let path = std::env::join_paths([&bin]).unwrap().to_string_lossy().into_owned();
|
||||
// Windows environment keys are case-insensitive (`Path`).
|
||||
let env = BTreeMap::from([("Path".to_owned(), path)]);
|
||||
assert_eq!(resolve_program("kotlinc", cwd, &env, true), bin.join("kotlinc.bat"));
|
||||
let config = |env: BTreeMap<String, String>| RunConfig {
|
||||
id: "c".into(),
|
||||
name: "c".into(),
|
||||
kind: "maven".into(),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
cwd: None,
|
||||
env,
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
let config = config(BTreeMap::from([("Path".to_owned(), path)]));
|
||||
assert_eq!(resolve_program("kotlinc", cwd, &config, true), bin.join("kotlinc.bat"));
|
||||
// Not found: left to the OS (`command not found` at spawn).
|
||||
assert_eq!(resolve_program("nope", cwd, &env, true), PathBuf::from("nope"));
|
||||
// Unix: bare names are left to `execvp`.
|
||||
assert_eq!(resolve_program("kotlinc", cwd, &env, false), PathBuf::from("kotlinc"));
|
||||
assert_eq!(resolve_program("nope", cwd, &config, true), PathBuf::from("nope"));
|
||||
// Unix: extensionless names only (`kotlinc.bat` does not match `kotlinc`).
|
||||
assert_eq!(resolve_program("kotlinc", cwd, &config, false), PathBuf::from("kotlinc"));
|
||||
// Relative paths resolve against the run directory on every platform.
|
||||
assert_eq!(resolve_program("./gradlew", cwd, &env, true), cwd.join("./gradlew"));
|
||||
assert_eq!(resolve_program(".venv/bin/python", cwd, &env, false), cwd.join(".venv/bin/python"));
|
||||
assert_eq!(resolve_program("./gradlew", cwd, &config, true), cwd.join("./gradlew"));
|
||||
assert_eq!(resolve_program(".venv/bin/python", cwd, &config, false), cwd.join(".venv/bin/python"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
//! Isolated local Tomcat installations and deployments. Never writes to CATALINA_HOME.
|
||||
use crate::RunConfig;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{
|
||||
Reader, Writer,
|
||||
events::{BytesStart, Event},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::{
|
||||
fs,
|
||||
io::Read,
|
||||
net::TcpListener,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn invalid(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::invalid(e.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TomcatHome {
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub fn validate_home(home: &Path) -> IdeResult<TomcatHome> {
|
||||
if !(home.join("bin/catalina.sh").is_file() || home.join("bin/catalina.bat").is_file())
|
||||
|| !home.join("lib/catalina.jar").is_file()
|
||||
{
|
||||
return Err(invalid("Tomcat home must contain bin/catalina.sh or bin/catalina.bat and lib/catalina.jar"));
|
||||
}
|
||||
let mut jar = zip::ZipArchive::new(fs::File::open(home.join("lib/catalina.jar"))?).map_err(invalid)?;
|
||||
let mut properties = String::new();
|
||||
jar.by_name("org/apache/catalina/util/ServerInfo.properties").map_err(invalid)?.read_to_string(&mut properties)?;
|
||||
let version =
|
||||
properties.lines().find_map(|l| l.strip_prefix("server.info=")).unwrap_or("Apache Tomcat").trim().to_owned();
|
||||
Ok(TomcatHome { version })
|
||||
}
|
||||
|
||||
pub fn base_dir(cache: &Path, id: &str) -> PathBuf {
|
||||
// Stable and collision-free for configuration IDs, including Windows path characters.
|
||||
let key: String = id.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
||||
cache.join("tomcat").join(key)
|
||||
}
|
||||
|
||||
pub fn free_port() -> IdeResult<u16> {
|
||||
Ok(TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
|
||||
}
|
||||
|
||||
pub fn context_name(context: &str) -> IdeResult<String> {
|
||||
if context.is_empty() || context == "/" {
|
||||
return Ok("ROOT".into());
|
||||
}
|
||||
if !context.starts_with('/')
|
||||
|| context.ends_with('/')
|
||||
|| context[1..].split('/').any(|p| {
|
||||
p.is_empty() || p == "." || p == ".." || !p.chars().all(|c| c.is_alphanumeric() || "-_".contains(c))
|
||||
})
|
||||
{
|
||||
return Err(invalid("Context path must start with / and contain only letters, digits, /, - or _"));
|
||||
}
|
||||
Ok(context[1..].replace('/', "#"))
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
quick_xml::escape::escape(text).into_owned()
|
||||
}
|
||||
|
||||
pub fn context_xml(doc_base: &Path, reload: bool) -> String {
|
||||
format!("<Context docBase=\"{}\" reloadable=\"{reload}\" />\n", escape(&doc_base.to_string_lossy()))
|
||||
}
|
||||
|
||||
pub fn patch_server_xml(xml: &str, http: u16, shutdown: u16, secret: &str) -> IdeResult<String> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut writer = Writer::new(Vec::new());
|
||||
let mut http_found = false;
|
||||
loop {
|
||||
let event = reader.read_event().map_err(invalid)?;
|
||||
if matches!(event, Event::Eof) {
|
||||
break;
|
||||
}
|
||||
let event = match event {
|
||||
Event::Start(ref tag) | Event::Empty(ref tag) => {
|
||||
let name = tag.name().as_ref().to_owned();
|
||||
let mut attrs: Vec<(String, String)> = tag
|
||||
.attributes()
|
||||
.map(|a| {
|
||||
let a = a.map_err(invalid)?;
|
||||
Ok((
|
||||
a.key.as_ref().to_owned(),
|
||||
a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_err(invalid)?.into_owned(),
|
||||
))
|
||||
})
|
||||
.collect::<IdeResult<_>>()?;
|
||||
let mut set = |key: &str, value: String| {
|
||||
attrs.retain(|(k, _)| k != key);
|
||||
attrs.push((key.into(), value));
|
||||
};
|
||||
match name.as_str() {
|
||||
"Server" => {
|
||||
set("port", shutdown.to_string());
|
||||
set("address", "127.0.0.1".into());
|
||||
set("shutdown", secret.into());
|
||||
}
|
||||
"Connector" => {
|
||||
let protocol = tag
|
||||
.try_get_attribute("protocol")
|
||||
.map_err(invalid)?
|
||||
.map(|a| a.value.into_owned())
|
||||
.unwrap_or_default();
|
||||
let is_http = !http_found
|
||||
&& (protocol.is_empty() || protocol.contains("HTTP") || protocol.contains("Http"));
|
||||
set("port", if is_http { http } else { free_port()? }.to_string());
|
||||
if is_http {
|
||||
http_found = true;
|
||||
}
|
||||
}
|
||||
"Engine" => set("name", "Catalina".into()),
|
||||
"Host" => {
|
||||
set("name", "localhost".into());
|
||||
set("appBase", "webapps".into());
|
||||
set("autoDeploy", "true".into());
|
||||
set("deployOnStartup", "true".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut new = BytesStart::new(name);
|
||||
for (k, v) in &attrs {
|
||||
new.push_attribute((k.as_str(), v.as_str()));
|
||||
}
|
||||
if matches!(event, Event::Empty(_)) { Event::Empty(new) } else { Event::Start(new) }
|
||||
}
|
||||
e => e.into_owned(),
|
||||
};
|
||||
writer.write_event(event).map_err(invalid)?;
|
||||
}
|
||||
if !http_found {
|
||||
return Err(invalid("Tomcat server.xml has no HTTP connector"));
|
||||
}
|
||||
String::from_utf8(writer.into_inner()).map_err(invalid)
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
fs::create_dir_all(to)?;
|
||||
for entry in fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let target = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &target)?;
|
||||
} else {
|
||||
fs::copy(entry.path(), target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Synchronize an archive into a private exploded deployment, preserving unchanged class timestamps.
|
||||
pub fn explode(war: &Path, destination: &Path, resources_only: bool) -> IdeResult<()> {
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(war)?).map_err(invalid)?;
|
||||
fs::create_dir_all(destination)?;
|
||||
let mut expected = std::collections::HashSet::new();
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).map_err(invalid)?;
|
||||
let path = entry.enclosed_name().ok_or_else(|| invalid("WAR contains an invalid path"))?;
|
||||
expected.insert(path.clone());
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if resources_only && (path.extension().is_some_and(|e| e == "class") || path.starts_with("WEB-INF/lib")) {
|
||||
continue;
|
||||
}
|
||||
let target = destination.join(&path);
|
||||
let mut bytes = Vec::new();
|
||||
entry.read_to_end(&mut bytes)?;
|
||||
if fs::read(&target).ok().as_deref() != Some(&bytes) {
|
||||
fs::create_dir_all(target.parent().unwrap())?;
|
||||
fs::write(target, bytes)?;
|
||||
}
|
||||
}
|
||||
fn remove_stale(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
expected: &std::collections::HashSet<PathBuf>,
|
||||
resources: bool,
|
||||
) -> IdeResult<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if entry.file_type()?.is_dir() {
|
||||
remove_stale(root, &path, expected, resources)?;
|
||||
} else {
|
||||
let rel = path.strip_prefix(root).map_err(invalid)?;
|
||||
if !expected.contains(rel)
|
||||
&& !(resources && (rel.extension().is_some_and(|e| e == "class") || rel.starts_with("WEB-INF/lib")))
|
||||
{
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
remove_stale(destination, destination, &expected, resources_only)
|
||||
}
|
||||
|
||||
pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only: bool) -> IdeResult<PathBuf> {
|
||||
let p = &config.extras.params;
|
||||
match p.get("deployment").map(String::as_str).unwrap_or("artifact") {
|
||||
"artifact" => {
|
||||
if let Some(id) = p.get("artifact").filter(|s| !s.is_empty())
|
||||
&& fs::read_to_string(base.join("artifact-id.txt")).ok().as_ref() != Some(id)
|
||||
{
|
||||
return Err(invalid("Build the selected WAR artifact before launching Tomcat"));
|
||||
}
|
||||
let war = fs::read_to_string(base.join("artifact-path.txt"))
|
||||
.map_err(|_| invalid("Build the WAR artifact before launching Tomcat"))?;
|
||||
let war = PathBuf::from(war.trim());
|
||||
if !war.is_file() || !war.extension().is_some_and(|e| e.eq_ignore_ascii_case("war")) {
|
||||
return Err(invalid("The built WAR artifact does not exist"));
|
||||
}
|
||||
let dest = base.join("deployment");
|
||||
explode(&war, &dest, resources_only)?;
|
||||
Ok(dest)
|
||||
}
|
||||
kind @ ("war" | "directory") => {
|
||||
let value = p
|
||||
.get("deploymentPath")
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.ok_or_else(|| invalid("Choose a WAR file or exploded directory"))?;
|
||||
let path = root.join(value).canonicalize()?;
|
||||
if (kind == "war" && (!path.is_file() || !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("war"))))
|
||||
|| (kind == "directory" && !path.is_dir())
|
||||
{
|
||||
return Err(invalid("Invalid Tomcat deployment"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
_ => Err(invalid("Unknown Tomcat deployment type")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn effective_context(config: &RunConfig, doc: &Path) -> String {
|
||||
config.extras.params.get("contextPath").filter(|s| !s.is_empty()).cloned().unwrap_or_else(|| {
|
||||
let name = config
|
||||
.extras
|
||||
.params
|
||||
.get("artifactName")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| doc.file_stem().unwrap_or_default().to_string_lossy().into_owned());
|
||||
if name == "ROOT" { "/".into() } else { format!("/{name}") }
|
||||
})
|
||||
}
|
||||
|
||||
/// Platform-neutral plan; Windows uses the process manager's raw cmd quoting for batch scripts.
|
||||
pub fn script_command(home: &Path, windows: bool, verb: &str) -> (String, Vec<String>) {
|
||||
if windows {
|
||||
(format!("\"{}\" {verb}", home.join("bin/catalina.bat").display()), vec![])
|
||||
} else {
|
||||
("sh".into(), vec![home.join("bin/catalina.sh").to_string_lossy().into_owned(), verb.into()])
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<()> {
|
||||
let home = root
|
||||
.join(config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?)
|
||||
.canonicalize()?;
|
||||
validate_home(&home)?;
|
||||
let base = base_dir(cache, &config.id);
|
||||
fs::create_dir_all(&base)?;
|
||||
let base = base.canonicalize()?;
|
||||
let doc = deployment(root, &base, config, false)?;
|
||||
let context = effective_context(config, &doc);
|
||||
let context = context_name(&context)?;
|
||||
let port: u16 =
|
||||
config.extras.params.get("httpPort").map(String::as_str).unwrap_or("8080").parse().map_err(invalid)?;
|
||||
if port == 0 {
|
||||
return Err(invalid("HTTP port must be between 1 and 65535"));
|
||||
}
|
||||
let shutdown = free_port()?;
|
||||
let secret = format!(
|
||||
"OPENIDEA_{}_{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(invalid)?.as_nanos()
|
||||
);
|
||||
// Refresh only the IDE-owned configuration, leaving logs and deployed artifacts available.
|
||||
if base.join("conf").exists() {
|
||||
fs::remove_dir_all(base.join("conf"))?;
|
||||
}
|
||||
copy_tree(&home.join("conf"), &base.join("conf"))?;
|
||||
let contexts = base.join("conf/Catalina/localhost");
|
||||
if contexts.exists() {
|
||||
fs::remove_dir_all(&contexts)?;
|
||||
}
|
||||
for dir in ["logs", "temp", "work", "webapps", "conf/Catalina/localhost"] {
|
||||
fs::create_dir_all(base.join(dir))?;
|
||||
}
|
||||
let server = patch_server_xml(&fs::read_to_string(home.join("conf/server.xml"))?, port, shutdown, &secret)?;
|
||||
fs::write(base.join("conf/server.xml"), server)?;
|
||||
let debug = config.extras.params.get("tomcatDebug").is_some_and(|v| v == "true");
|
||||
fs::write(contexts.join(format!("{context}.xml")), context_xml(&doc, !debug))?;
|
||||
config.env.insert("CATALINA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
config.env.insert("CATALINA_BASE".into(), base.to_string_lossy().into_owned());
|
||||
if let Some(jre) = config.extras.params.get("jre").filter(|s| !s.trim().is_empty()) {
|
||||
let jre = root.join(jre).canonicalize()?;
|
||||
config.env.insert("JAVA_HOME".into(), jre.to_string_lossy().into_owned());
|
||||
config.env.insert("JRE_HOME".into(), jre.to_string_lossy().into_owned());
|
||||
} else if let Some(java) = config.env.get("JAVA_HOME").cloned() {
|
||||
config.env.insert("JRE_HOME".into(), java);
|
||||
}
|
||||
let vm = config.extras.params.get("vmOptions").cloned().unwrap_or_default();
|
||||
let jmx = free_port()?;
|
||||
let mut opts = config.env.get("CATALINA_OPTS").cloned().unwrap_or_default();
|
||||
opts.push_str(&format!(" {vm} -Dcom.sun.management.jmxremote.port={jmx} -Dcom.sun.management.jmxremote.rmi.port={jmx} -Dcom.sun.management.jmxremote.host=127.0.0.1 -Djava.rmi.server.hostname=127.0.0.1 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"));
|
||||
if debug {
|
||||
opts.push_str(" -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:0");
|
||||
}
|
||||
config.env.insert("CATALINA_OPTS".into(), opts);
|
||||
(config.command, config.args) = script_command(&home, cfg!(windows), "run");
|
||||
config.extras.stop_command = Some(if cfg!(windows) {
|
||||
script_command(&home, true, "stop").0
|
||||
} else {
|
||||
format!("sh '{}' stop", home.join("bin/catalina.sh").to_string_lossy().replace('\'', "'\\''"))
|
||||
});
|
||||
config.extras.emulate_terminal = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update(root: &Path, cache: &Path, config: &RunConfig, mode: &str) -> IdeResult<()> {
|
||||
if !matches!(mode, "resources" | "classes" | "redeploy") {
|
||||
return Err(invalid("Unknown Tomcat update operation"));
|
||||
}
|
||||
let base = base_dir(cache, &config.id);
|
||||
let doc = deployment(root, &base, config, mode == "resources")?;
|
||||
let context = context_name(&effective_context(config, &doc))?;
|
||||
let file = base.join("conf/Catalina/localhost").join(format!("{context}.xml"));
|
||||
if !file.is_file() {
|
||||
return Err(invalid("Start this Tomcat configuration before updating it"));
|
||||
}
|
||||
if mode == "redeploy" {
|
||||
let content = fs::read(&file)?;
|
||||
fs::write(file, content)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
fn archive(path: &Path, entries: &[(&str, &str)]) {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap());
|
||||
for (name, text) in entries {
|
||||
zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(text.as_bytes()).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
fn config() -> RunConfig {
|
||||
RunConfig {
|
||||
id: "local:demo".into(),
|
||||
name: "Tomcat".into(),
|
||||
kind: "tomcat".into(),
|
||||
command: "catalina".into(),
|
||||
args: vec!["run".into()],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: Some("java-debug".into()),
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn validates_home_and_reads_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(validate_home(tmp.path()).is_err());
|
||||
fs::create_dir_all(tmp.path().join("bin")).unwrap();
|
||||
fs::write(tmp.path().join("bin/catalina.bat"), "").unwrap();
|
||||
archive(
|
||||
&tmp.path().join("lib/catalina.jar"),
|
||||
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1.61\n")],
|
||||
);
|
||||
assert_eq!(validate_home(tmp.path()).unwrap().version, "Apache Tomcat/10.1.61");
|
||||
}
|
||||
#[test]
|
||||
fn patches_ports_without_changing_comments_and_escapes_context() {
|
||||
let xml = "<Server port='8005' shutdown='SHUTDOWN'><!-- <Connector port=\"8080\"/> --><Service><Connector port='8080' protocol='HTTP/1.1'/><Connector port='8009' protocol='AJP/1.3'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
let patched = patch_server_xml(xml, 18080, 18005, "SECRET").unwrap();
|
||||
assert!(patched.contains("port=\"18080\""));
|
||||
assert!(patched.contains("port=\"18005\""));
|
||||
assert!(!patched.contains("port=\"8009\""));
|
||||
assert!(patched.contains("<!-- <Connector port=\"8080\"/> -->"));
|
||||
assert_eq!(context_name("/").unwrap(), "ROOT");
|
||||
assert_eq!(context_name("/a/b").unwrap(), "a#b");
|
||||
for path in ["../escape", "/../escape", "/x#y", "/a//b", "/a/"] {
|
||||
assert!(context_name(path).is_err());
|
||||
}
|
||||
assert!(context_xml(Path::new("/tmp/a & b/\"web\""), false).contains("a & b/"web""));
|
||||
}
|
||||
#[test]
|
||||
fn constructs_platform_commands_without_splitting_paths() {
|
||||
let home = if cfg!(windows) { Path::new("C:/some path/tomcat") } else { Path::new("/some path/tomcat") };
|
||||
assert_eq!(
|
||||
script_command(home, false, "run"),
|
||||
("sh".into(), vec![home.join("bin/catalina.sh").to_string_lossy().into_owned(), "run".into()])
|
||||
);
|
||||
let (command, args) = script_command(home, true, "run");
|
||||
assert_eq!(command, format!("\"{}\" run", home.join("bin/catalina.bat").display()));
|
||||
assert!(args.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn resolves_manual_deployments_and_synchronizes_war_resources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let war = tmp.path().join("web app.war");
|
||||
archive(&war, &[("index.html", "old"), ("WEB-INF/classes/App.class", "class1"), ("removed.txt", "delete")]);
|
||||
let base = tmp.path().join("cache");
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes()).unwrap();
|
||||
let mut c = config();
|
||||
let dest = deployment(tmp.path(), &base, &c, false).unwrap();
|
||||
archive(&war, &[("index.html", "new"), ("WEB-INF/classes/App.class", "class2")]);
|
||||
deployment(tmp.path(), &base, &c, true).unwrap();
|
||||
assert_eq!(fs::read_to_string(dest.join("index.html")).unwrap(), "new");
|
||||
assert_eq!(fs::read_to_string(dest.join("WEB-INF/classes/App.class")).unwrap(), "class1");
|
||||
assert!(!dest.join("removed.txt").exists());
|
||||
deployment(tmp.path(), &base, &c, false).unwrap();
|
||||
assert_eq!(fs::read_to_string(dest.join("WEB-INF/classes/App.class")).unwrap(), "class2");
|
||||
c.extras.params.insert("deployment".into(), "war".into());
|
||||
c.extras.params.insert("deploymentPath".into(), "web app.war".into());
|
||||
assert_eq!(deployment(tmp.path(), &base, &c, false).unwrap(), war.canonicalize().unwrap());
|
||||
fs::create_dir_all(tmp.path().join("WebContent")).unwrap();
|
||||
c.extras.params.insert("deployment".into(), "directory".into());
|
||||
c.extras.params.insert("deploymentPath".into(), "WebContent".into());
|
||||
assert!(deployment(tmp.path(), &base, &c, false).unwrap().ends_with("WebContent"));
|
||||
}
|
||||
#[test]
|
||||
fn prepares_isolated_base_and_jdwp_only_for_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("Tomcat Home");
|
||||
fs::create_dir_all(home.join("bin")).unwrap();
|
||||
fs::create_dir_all(home.join("conf")).unwrap();
|
||||
fs::create_dir_all(tmp.path().join("WebRoot")).unwrap();
|
||||
fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
archive(
|
||||
&home.join("lib/catalina.jar"),
|
||||
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
|
||||
);
|
||||
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
fs::write(home.join("conf/server.xml"), server).unwrap();
|
||||
let mut c = config();
|
||||
for (k, v) in [
|
||||
("tomcatHome", "Tomcat Home"),
|
||||
("deployment", "directory"),
|
||||
("deploymentPath", "WebRoot"),
|
||||
("contextPath", "/app"),
|
||||
("tomcatDebug", "true"),
|
||||
("vmOptions", "-Xmx256m"),
|
||||
] {
|
||||
c.extras.params.insert(k.into(), v.into());
|
||||
}
|
||||
c.env.insert("JAVA_HOME".into(), "/jdk with spaces".into());
|
||||
prepare(tmp.path(), &tmp.path().join("cache"), &mut c).unwrap();
|
||||
assert_eq!(fs::read_to_string(home.join("conf/server.xml")).unwrap(), server);
|
||||
let base = PathBuf::from(&c.env["CATALINA_BASE"]);
|
||||
assert!(base.join("conf/Catalina/localhost/app.xml").is_file());
|
||||
assert!(c.env["CATALINA_OPTS"].contains("suspend=n,address=127.0.0.1:0"));
|
||||
assert!(c.env["CATALINA_OPTS"].contains("-Xmx256m"));
|
||||
assert!(!c.env.get("JAVA_OPTS").is_some_and(|s| s.contains("jdwp")));
|
||||
assert_eq!(c.env["JRE_HOME"], "/jdk with spaces");
|
||||
let stop = c.extras.stop_command.unwrap();
|
||||
assert!(stop.contains("stop"));
|
||||
let script = if cfg!(windows) { "catalina.bat" } else { "catalina.sh" };
|
||||
assert!(stop.contains(script));
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,16 @@ pub fn is_python(command: &str) -> bool {
|
||||
n == "py" || n.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
}
|
||||
|
||||
/// The search path the configuration runs with (its `PATH` override, else the IDE's).
|
||||
/// The search path the configuration runs with (its `PATH` override, else the IDE's:
|
||||
/// the login shell's and the version managers', so `mvn` / `gradle` installed by mise,
|
||||
/// asdf or Homebrew resolve when the app's own `PATH` is minimal).
|
||||
pub fn search_path(config: &RunConfig) -> OsString {
|
||||
config
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| OsString::from(v))
|
||||
.or_else(|| std::env::var_os("PATH"))
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_else(ide_core::tool_path::search_path)
|
||||
}
|
||||
|
||||
/// `node_modules/.bin/<name>` in `dir` or an ancestor up to (and including) `root`.
|
||||
|
||||
@@ -17,8 +17,7 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1,15 +1,18 @@
|
||||
//! Angular Language Server (`ngserver`): its package, where TypeScript and
|
||||
//! `@angular/language-service` come from, and the project's Angular version.
|
||||
|
||||
use crate::npm::package_dir;
|
||||
use crate::npm::{package_dir, shim_package};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const SERVER: &str = "angular-language-server";
|
||||
const PACKAGE: &str = "@angular/language-server";
|
||||
|
||||
/// `@angular/language-server`'s directory for an `ngserver` executable.
|
||||
pub(crate) fn server_package(bin: &Path) -> Option<PathBuf> {
|
||||
package_dir(bin, PACKAGE)
|
||||
/// `@angular/language-server`'s directory for an `ngserver` executable found on
|
||||
/// `path` and run in `cwd` with `env`.
|
||||
pub(crate) fn server_package(bin: &Path, path: &OsStr, cwd: &Path, env: &BTreeMap<String, String>) -> Option<PathBuf> {
|
||||
package_dir(bin, PACKAGE).or_else(|| shim_package(bin, PACKAGE, path, cwd, env))
|
||||
}
|
||||
|
||||
/// Why an `ngserver` whose package isn't found can't start: it loads TypeScript
|
||||
|
||||
@@ -519,8 +519,8 @@ fn configure_vue_typescript(cfg: &mut LanguageServerConfig, root: &Path, server_
|
||||
fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
// Found as the launcher finds it; missing, it asks to be installed.
|
||||
let path = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
|
||||
let Ok(bin) = which::which_in(&cfg.command, Some(path), server_root) else { return };
|
||||
let Some(package) = angular::server_package(&bin) else {
|
||||
let Some(bin) = ide_core::tool_path::find_command(&cfg.command, &path, server_root) else { return };
|
||||
let Some(package) = angular::server_package(&bin, &path, server_root, &cfg.env) else {
|
||||
cfg.launch_error = Some(angular::missing_package_message(&bin));
|
||||
return;
|
||||
};
|
||||
@@ -651,7 +651,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
c.env.entry(key).or_insert(value);
|
||||
}
|
||||
}
|
||||
"maven" => {
|
||||
"maven" | "tomcat" => {
|
||||
if let Some(jdk) = &jdk {
|
||||
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
@@ -662,6 +662,17 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
if !c.args.starts_with(&mvn_options) {
|
||||
c.args.splice(0..0, mvn_options.iter().cloned());
|
||||
}
|
||||
} else if c.kind == "maven"
|
||||
&& matches!(c.command.as_str(), "mvn" | "mvn.cmd" | "mvn.bat")
|
||||
&& let Some(mvn) = &mvn
|
||||
{
|
||||
// A goal configuration saved from the tool window keeps the
|
||||
// literal `mvn` / `mvn.cmd` the launcher resolved to; without a
|
||||
// wrapper it cannot start when Maven lives on a version
|
||||
// manager's shims or a configured home (#328). Detected configs
|
||||
// take the Maven options too, but the saved ones already baked
|
||||
// them into `args`.
|
||||
c.command = mvn.to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -3,35 +3,13 @@
|
||||
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::ffi::OsString;
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The process `PATH` (already the login shell's in the app) plus common tool dirs.
|
||||
pub fn search_path() -> OsString {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(home) = crate::home_dir() {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".bun/bin", ".npm-global/bin", ".volta/bin"] {
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
// nvm: newest installed node's bin, as language servers are launched.
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
dirs.retain(|d| !d.as_os_str().is_empty() && seen.insert(d.clone()));
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
}
|
||||
pub(crate) use ide_core::tool_path::search_path;
|
||||
|
||||
/// `dir` in front of the search path, as a `PATH` value.
|
||||
pub(crate) fn path_with(dirs: &[&Path]) -> String {
|
||||
@@ -45,7 +23,7 @@ pub(crate) fn path_with(dirs: &[&Path]) -> String {
|
||||
/// Resolves a command name on the search path.
|
||||
pub(crate) fn which(name: &str) -> Option<PathBuf> {
|
||||
let path = search_path();
|
||||
std::env::split_paths(&path).map(|d| d.join(crate::exe(name))).find(|p| p.is_file())
|
||||
ide_core::process::find_executable(name, &path)
|
||||
}
|
||||
|
||||
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
|
||||
@@ -66,27 +44,41 @@ pub(crate) fn query_in(
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
if !env.iter().any(|(k, _)| *k == "PATH") {
|
||||
cmd.env("PATH", search_path());
|
||||
}
|
||||
let mut child = ide_core::process::prepare(&mut cmd)
|
||||
.args(args)
|
||||
.env("PATH", search_path())
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut stdout = child.stdout.take()?;
|
||||
let mut stderr = child.stderr.take()?;
|
||||
let out = std::thread::spawn(move || {
|
||||
let mut s = Vec::new();
|
||||
let _ = stdout.read_to_end(&mut s);
|
||||
decode_tool_output(&s)
|
||||
});
|
||||
let err = std::thread::spawn(move || {
|
||||
let mut s = Vec::new();
|
||||
let _ = stderr.read_to_end(&mut s);
|
||||
decode_tool_output(&s)
|
||||
});
|
||||
// Chunks as they come, `None` at the end of a pipe. A reader stops once the query
|
||||
// has returned, closing the pipe on whatever still writes to it.
|
||||
let (tx, rx) = mpsc::channel::<(bool, Option<Vec<u8>>)>();
|
||||
let pipes: [(bool, Box<dyn Read + Send>); 2] =
|
||||
[(true, Box::new(child.stdout.take()?)), (false, Box::new(child.stderr.take()?))];
|
||||
for (is_out, mut pipe) in pipes {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
let chunk = match pipe.read(&mut buf) {
|
||||
Ok(0) => None,
|
||||
Ok(n) => Some(buf[..n].to_vec()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(_) => None,
|
||||
};
|
||||
let end = chunk.is_none();
|
||||
if tx.send((is_out, chunk)).is_err() || end {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
@@ -99,12 +91,27 @@ pub(crate) fn query_in(
|
||||
}
|
||||
}
|
||||
};
|
||||
let (out, err) = (out.join().unwrap_or_default(), err.join().unwrap_or_default());
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = if out.trim().is_empty() { err } else { out };
|
||||
Some(text.trim().to_owned())
|
||||
// Up to the deadline, or briefly past it for a program that exited just before:
|
||||
// a process it left running (a wrapper's background job) can hold the pipes
|
||||
// open, or keep writing to them, after it exits.
|
||||
let until = deadline.max(Instant::now() + Duration::from_millis(100));
|
||||
let (mut out, mut err, mut open) = (Vec::new(), Vec::new(), 2);
|
||||
while open > 0 {
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
break;
|
||||
}
|
||||
match rx.recv_timeout(left) {
|
||||
Ok((is_out, Some(chunk))) => if is_out { &mut out } else { &mut err }.extend(chunk),
|
||||
Ok((_, None)) => open -= 1,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let text = if out.trim_ascii().is_empty() { err } else { out };
|
||||
Some(decode_tool_output(&text).trim().to_owned())
|
||||
}
|
||||
|
||||
/// Runs a command to completion, reporting every output line (stdout and
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn find(custom: Option<PathBuf>) -> Option<PathBuf> {
|
||||
if let Some(p) = custom {
|
||||
return Some(p);
|
||||
}
|
||||
find_in(&crate::search_path(), &install_locations(crate::home_dir().as_deref()))
|
||||
find_in(&crate::exec::search_path(), &install_locations(crate::home_dir().as_deref()))
|
||||
}
|
||||
|
||||
pub(crate) fn find_in(search: &OsStr, locations: &[PathBuf]) -> Option<PathBuf> {
|
||||
|
||||
@@ -44,6 +44,12 @@ fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
fn jdk_homes(root: &Path) -> impl Iterator<Item = PathBuf> {
|
||||
children(root)
|
||||
.into_iter()
|
||||
.flat_map(|dir| [dir.join("Contents/Home"), dir.join("libexec/openjdk.jdk/Contents/Home"), dir])
|
||||
}
|
||||
|
||||
/// Vendor directories JDK installers use on Windows, under `Program Files`
|
||||
/// and (per-user installs) `%LOCALAPPDATA%\Programs`.
|
||||
const WINDOWS_VENDORS: &[&str] =
|
||||
@@ -106,9 +112,7 @@ fn scan() -> Vec<Jdk> {
|
||||
if roots[..i].contains(root) {
|
||||
continue;
|
||||
}
|
||||
for dir in children(root) {
|
||||
homes.extend([dir.join("Contents/Home"), dir.join("libexec/openjdk.jdk/Contents/Home"), dir]);
|
||||
}
|
||||
homes.extend(jdk_homes(root));
|
||||
}
|
||||
// mise keeps a macOS JDK as its bundle (`<version>/Contents/Home`), asdf flattens it.
|
||||
for (dir, _) in ide_core::version_managers::installs(ide_core::version_managers::Tool::Java) {
|
||||
@@ -157,12 +161,24 @@ pub fn installed_jdks() -> Arc<[Jdk]> {
|
||||
/// Like [`installed_jdks`], but while none can run jdtls (on Java `min_java`)
|
||||
/// the list is rescanned (at most every [`RESCAN_AFTER`]), so a JDK installed
|
||||
/// after startup is picked up when the server is restarted.
|
||||
pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
|
||||
pub fn jdtls_jdks(min_java: u32, data_dir: &Path) -> Arc<[Jdk]> {
|
||||
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match &*slot {
|
||||
let installed = match &*slot {
|
||||
Some(s) if jdtls_runtime(&s.jdks, min_java).is_some() || s.at.elapsed() < RESCAN_AFTER => s.jdks.clone(),
|
||||
_ => rescan(&mut slot),
|
||||
}
|
||||
};
|
||||
runtime_candidates(&installed, data_dir).into()
|
||||
}
|
||||
|
||||
/// Runtime-only downloads are never registered as project discovery roots.
|
||||
pub fn language_server_runtimes_dir(data_dir: &Path) -> PathBuf {
|
||||
data_dir.join("language-server-runtimes")
|
||||
}
|
||||
|
||||
fn runtime_candidates(installed: &[Jdk], data_dir: &Path) -> Vec<Jdk> {
|
||||
let mut jdks = installed.to_vec();
|
||||
jdks.extend(jdk_homes(&language_server_runtimes_dir(data_dir)).filter_map(|home| jdk_at(&home)));
|
||||
jdks
|
||||
}
|
||||
|
||||
/// For a server with `max-java`: when the `JAVA_HOME` it would get (its env,
|
||||
@@ -341,6 +357,14 @@ pub fn configure_jdtls(
|
||||
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
|
||||
}
|
||||
crate::jdtls::add_default_vm_args(&mut cfg.args);
|
||||
let managed = language_server_runtimes_dir(data_dir);
|
||||
let managed = dunce::canonicalize(&managed).unwrap_or(managed);
|
||||
let project_jdks: Vec<_> = project_jdk
|
||||
.into_iter()
|
||||
.chain(jdks)
|
||||
.filter(|jdk| !jdk.home.starts_with(&managed) || project_jdk == Some(*jdk))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut all: Vec<Jdk> = Vec::new();
|
||||
for j in project_jdk.into_iter().chain(jdks).chain(server_jdk) {
|
||||
if !all.contains(j) {
|
||||
@@ -361,11 +385,12 @@ pub fn configure_jdtls(
|
||||
Err(e) => cfg.launch_error = Some(e),
|
||||
}
|
||||
}
|
||||
let mut runtimes = runtimes(jdks);
|
||||
if let Some(project) = project_jdk {
|
||||
let home = project.home.to_string_lossy();
|
||||
let mut runtimes = runtimes(&project_jdks);
|
||||
if let Some(project) = project_jdk.or_else(|| pick_jdk(&project_jdks, project_java_version(server_root))) {
|
||||
let name = if project.major == 8 { "JavaSE-1.8".to_owned() } else { format!("JavaSE-{}", project.major) };
|
||||
for r in &mut runtimes {
|
||||
if r["path"] == *home {
|
||||
if r["name"] == name {
|
||||
r["path"] = json!(project.home.to_string_lossy());
|
||||
r["default"] = json!(true);
|
||||
}
|
||||
}
|
||||
@@ -502,6 +527,58 @@ fn parse_java_version(v: &str) -> Option<u32> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn provisioning_runtime_preserves_implicit_project_jdk() {
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let project_root = data.path().join("tools/jdks");
|
||||
let project_home = project_root.join("temurin-21");
|
||||
std::fs::create_dir_all(project_home.join("bin")).unwrap();
|
||||
std::fs::write(project_home.join("release"), "JAVA_VERSION=\"21.0.1\"\n").unwrap();
|
||||
std::fs::write(java_executable(&project_home), "").unwrap();
|
||||
let project = jdk_at(&project_home).unwrap();
|
||||
let discover = || jdk_homes(&project_root).filter_map(|home| jdk_at(&home)).collect::<Vec<_>>();
|
||||
let installed = discover();
|
||||
assert_eq!(pick_jdk(&installed, None), Some(&project));
|
||||
assert!(jdtls_runtime(&runtime_candidates(&installed, data.path()), 25).is_none());
|
||||
let home = language_server_runtimes_dir(data.path()).join("temurin-25");
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
|
||||
std::fs::write(java_executable(&home), "").unwrap();
|
||||
let candidates = runtime_candidates(&installed, data.path());
|
||||
assert_eq!(jdtls_runtime(&candidates, 25).unwrap().major, 25);
|
||||
assert_eq!(jdtls_runtime(&candidates, 21), Some(&project));
|
||||
assert_eq!(pick_jdk(&discover(), None), Some(&project));
|
||||
let explicit = jdk_at(&home).unwrap();
|
||||
assert_eq!(pick_jdk(std::slice::from_ref(&explicit), None), Some(&explicit));
|
||||
let mut cfg: LanguageServerConfig = serde_json::from_value(json!({"name":"jdtls", "command":"jdtls"})).unwrap();
|
||||
configure_jdtls(&mut cfg, data.path(), data.path(), &candidates, None, None, 25, &[], None);
|
||||
assert_eq!(cfg.env["JAVA_HOME"], explicit.home.to_string_lossy());
|
||||
let options = serde_json::to_string(&cfg.initialization_options).unwrap();
|
||||
assert!(!options.contains("temurin-25"), "runtime-only JDK must not become a compiler runtime");
|
||||
assert_eq!(
|
||||
cfg.initialization_options.as_ref().unwrap()["settings"]["java"]["configuration"]["runtimes"][0]["default"]
|
||||
.as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_compiler_default_matches_project_pick_with_duplicate_versions() {
|
||||
let installed =
|
||||
[Jdk { major: 21, home: PathBuf::from("/jdk21a") }, Jdk { major: 21, home: PathBuf::from("/jdk21b") }];
|
||||
let server = Jdk { major: 25, home: PathBuf::from("/custom-server-runtime") };
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, Some(&server), 25, &[], None);
|
||||
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
opts["settings"]["java"]["configuration"]["runtimes"],
|
||||
json!([{
|
||||
"name": "JavaSE-21", "path": pick_jdk(&installed, None).unwrap().home, "default": true
|
||||
}])
|
||||
);
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/custom-server-runtime");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_versions() {
|
||||
assert_eq!(parse_release("IMPLEMENTOR=\"x\"\nJAVA_VERSION=\"21.0.3\"\n"), Some(21));
|
||||
@@ -544,7 +621,7 @@ mod tests {
|
||||
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
|
||||
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": "/jdk8" }));
|
||||
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21a" }));
|
||||
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": "/jdk25" }));
|
||||
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": "/jdk25", "default": true }));
|
||||
assert_eq!(opts["bundles"], json!(["/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar"]));
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/jdk25", "first JDK new enough to run jdtls");
|
||||
assert_eq!(cfg.launch_error, None);
|
||||
|
||||
@@ -25,7 +25,6 @@ use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub use discover::{detect, jdk_sdk};
|
||||
pub use exec::search_path;
|
||||
|
||||
/// What [`detect`] looks for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Node-based language servers installed with npm: the package behind a command.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `command` as given (a path) or found on `path`, npm shims included.
|
||||
pub(crate) fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
@@ -9,15 +11,13 @@ pub(crate) fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
|
||||
std::env::split_paths(path)
|
||||
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
|
||||
.find(|c| c.is_file())
|
||||
ide_core::process::find_executable(command, path)
|
||||
}
|
||||
|
||||
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
|
||||
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
|
||||
/// Unix global `<prefix>/bin` or a symlink into the package.
|
||||
/// Unix global `<prefix>/bin`, a symlink into the package, Volta's package image
|
||||
/// or the package a shim script runs (pnpm).
|
||||
pub(crate) fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
let dir = bin.parent()?;
|
||||
let mut candidates = vec![dir.join("node_modules").join(package)];
|
||||
@@ -31,6 +31,197 @@ pub(crate) fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
}
|
||||
if let Some(prefix) = dir.parent() {
|
||||
candidates.push(prefix.join("lib").join("node_modules").join(package));
|
||||
// Volta: `<home>/bin/<command>` runs `<home>/tools/image/packages/<package>`.
|
||||
let image = prefix.join("tools").join("image").join("packages").join(package);
|
||||
candidates.push(image.join("lib").join("node_modules").join(package));
|
||||
candidates.push(image.join("node_modules").join(package));
|
||||
}
|
||||
let installed = |c: &PathBuf| c.join("package.json").is_file();
|
||||
candidates.into_iter().find(installed).or_else(|| script_targets(bin, package).into_iter().find(installed))
|
||||
}
|
||||
|
||||
/// How shim scripts name their own directory: sh and PowerShell `$basedir` (pnpm
|
||||
/// 11's sh shims also `$basedir_abs` and `$basedir_win`), cmd `%~dp0` (pnpm's
|
||||
/// `%dp0%` is set from it).
|
||||
const SCRIPT_DIR: [&str; 8] =
|
||||
["${basedir}", "$basedir", "${basedir_abs}", "$basedir_abs", "${basedir_win}", "$basedir_win", "%~dp0", "%dp0%"];
|
||||
|
||||
/// `path` after the [`SCRIPT_DIR`] it starts with. sh reads `$basedir_abs` as one
|
||||
/// name, not as `$basedir` followed by `_abs`.
|
||||
fn after_script_dir(path: &str) -> Option<&str> {
|
||||
SCRIPT_DIR.iter().find_map(|d| {
|
||||
let rest = path.strip_prefix(d)?;
|
||||
let longer_name = d.starts_with('$')
|
||||
&& !d.ends_with('}')
|
||||
&& rest.starts_with(|c: char| c == '_' || c.is_ascii_alphanumeric());
|
||||
(!longer_name).then_some(rest)
|
||||
})
|
||||
}
|
||||
|
||||
/// The `package` directories a shim script runs from: relative to the script's
|
||||
/// directory, e.g. pnpm's `"$basedir/../global/v11/<hash>/node_modules/<package>/bin/<command>"`
|
||||
/// or `"%~dp0\..\global\..."`, or absolute.
|
||||
fn script_targets(bin: &Path, package: &str) -> Vec<PathBuf> {
|
||||
const MAX_SCRIPT: u64 = 64 * 1024;
|
||||
if std::fs::metadata(bin).map_or(true, |m| m.len() > MAX_SCRIPT) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(bin) else { return Vec::new() };
|
||||
let text = String::from_utf8_lossy(&bytes).replace('\\', "/");
|
||||
let bases: Vec<PathBuf> = [
|
||||
bin.parent().map(Path::to_path_buf),
|
||||
dunce::canonicalize(bin).ok().and_then(|r| r.parent().map(Path::to_path_buf)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
let needle = format!("node_modules/{package}");
|
||||
// What sh and cmd split words on; a folder name may contain a no-break space.
|
||||
let separator = |c: char| c == '"' || c == '\'' || c.is_ascii_whitespace();
|
||||
let mut targets = Vec::new();
|
||||
for (at, _) in text.match_indices(&needle) {
|
||||
let end = at + needle.len();
|
||||
if !text[end..].chars().next().is_none_or(|c| c == '/' || separator(c)) {
|
||||
continue;
|
||||
}
|
||||
// Within quotes the path starts at the opening one and may contain spaces.
|
||||
let line = text[..at].rfind('\n').map_or(0, |i| i + 1);
|
||||
let start = match ['"', '\''].into_iter().find(|q| text[line..at].matches(*q).count() % 2 == 1) {
|
||||
Some(quote) => text[..at].rfind(quote),
|
||||
None => text[..at].rfind(separator),
|
||||
}
|
||||
.map_or(0, |i| i + 1);
|
||||
let path = &text[start..end];
|
||||
// `"$basedir"/../...`: the directory quoted on its own.
|
||||
let after_dir = text[..start]
|
||||
.strip_suffix(['"', '\''])
|
||||
.is_some_and(|before| SCRIPT_DIR.iter().any(|d| before.ends_with(d)));
|
||||
match after_script_dir(path).or(after_dir.then_some(path)) {
|
||||
Some(rest) => targets.extend(bases.iter().map(|b| b.join(rest.trim_start_matches('/')))),
|
||||
None if Path::new(path).is_absolute() => targets.push(PathBuf::from(path)),
|
||||
// `$HOME/...`, `%APPDATA%\...` or relative to wherever the script runs.
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
targets.into_iter().map(|t| dunce::canonicalize(&t).unwrap_or(t)).collect()
|
||||
}
|
||||
|
||||
/// For a version manager's shim (`~/.asdf/shims`, mise's `shims`), which names
|
||||
/// only the command: `package` in the global `node_modules` of the manager's
|
||||
/// npm shim, run as the server is (in `cwd`, with its `env` and `path`), so the
|
||||
/// manager picks the same Node. The shims go first on `path`, as the manager's
|
||||
/// shell setup puts them: npm (`#!/usr/bin/env node`) then runs on the manager's
|
||||
/// Node, not on a system one earlier on `path` that has another global root.
|
||||
pub(crate) fn shim_package(
|
||||
bin: &Path,
|
||||
package: &str,
|
||||
path: &OsStr,
|
||||
cwd: &Path,
|
||||
env: &BTreeMap<String, String>,
|
||||
) -> Option<PathBuf> {
|
||||
let shims = bin.parent()?;
|
||||
if shims.file_name() != Some(OsStr::new("shims")) {
|
||||
return None;
|
||||
}
|
||||
// Only the npm shim next to it: any other npm may be another installation's.
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe"] } else { &[""] };
|
||||
let npm = exts.iter().map(|e| shims.join(format!("npm{e}"))).find(|p| p.is_file())?;
|
||||
let path = std::env::join_paths(std::iter::once(shims.to_path_buf()).chain(std::env::split_paths(path))).ok()?;
|
||||
// The login shell's variables (`ASDF_DATA_DIR`, `MISE_ENV`...) under the server's own.
|
||||
let shell_env: Vec<_> = ide_core::process::shell_env().collect();
|
||||
let mut env: Vec<(&str, &str)> = shell_env
|
||||
.iter()
|
||||
.filter_map(|(k, v)| Some((k.to_str()?, v.to_str()?)))
|
||||
.chain(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
.collect();
|
||||
env.push(("PATH", path.to_str()?));
|
||||
let root = crate::exec::query_in(&npm, &["root", "-g"], Some(cwd), &env, Duration::from_secs(10))?;
|
||||
let dir = PathBuf::from(root.lines().last()?.trim()).join(package);
|
||||
dir.join("package.json").is_file().then_some(dir)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PACKAGE: &str = "@angular/language-server";
|
||||
|
||||
/// `<dir>/bin/ngserver` running `script`.
|
||||
fn shim(dir: &Path, script: &str) -> PathBuf {
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
let shim = dir.join("bin/ngserver");
|
||||
std::fs::write(&shim, script).unwrap();
|
||||
shim
|
||||
}
|
||||
|
||||
/// The package installed in `<dir>/node_modules`.
|
||||
fn install(dir: &Path) -> PathBuf {
|
||||
let package = dir.join("node_modules").join(PACKAGE);
|
||||
std::fs::create_dir_all(&package).unwrap();
|
||||
std::fs::write(package.join("package.json"), "{}").unwrap();
|
||||
dunce::canonicalize(package).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shim_scripts_name_the_package_relative_to_their_directory() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let package = install(&tmp.path().join("global/v11/abc"));
|
||||
for script in [
|
||||
"#!/bin/sh\nexec node \"$basedir/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n",
|
||||
"#!/bin/sh\nexec node \"${basedir}/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n",
|
||||
"#!/bin/sh\nexec node \"$basedir\"/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver \"$@\"\n",
|
||||
// pnpm 11.
|
||||
"#!/bin/sh\nexec \"$basedir/node\" \"$basedir_abs/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n",
|
||||
"#!/bin/sh\nexec node \"${basedir_abs}/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n",
|
||||
"#!/bin/sh\nexec node.exe \"$basedir_win/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n",
|
||||
"@\"%~dp0\\..\\global\\v11\\abc\\node_modules\\@angular\\language-server\\bin\\ngserver\" %*\r\n",
|
||||
"@\"%~dp0..\\global\\v11\\abc\\node_modules\\@angular\\language-server\\bin\\ngserver\" %*\r\n",
|
||||
"@SET dp0=%~dp0\r\n\"%dp0%\\..\\global\\v11\\abc\\node_modules\\@angular\\language-server\\bin\\ngserver\" %*\r\n",
|
||||
] {
|
||||
assert_eq!(package_dir(&shim(tmp.path(), script), PACKAGE), Some(package.clone()), "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_shim_targets_keep_their_spaces() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let package = install(&tmp.path().join("Global Packages/abc"));
|
||||
let absolute = package.display().to_string();
|
||||
for script in [
|
||||
"#!/bin/sh\nexec node \"$basedir/../Global Packages/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n"
|
||||
.to_owned(),
|
||||
"@\"%~dp0\\..\\Global Packages\\abc\\node_modules\\@angular\\language-server\\bin\\ngserver\" %*\r\n".to_owned(),
|
||||
format!("#!/bin/sh\nexec node \"{absolute}/bin/ngserver\" \"$@\"\n"),
|
||||
format!("#!/bin/sh\nexec node '{absolute}/bin/ngserver' \"$@\"\n"),
|
||||
] {
|
||||
assert_eq!(package_dir(&shim(tmp.path(), &script), PACKAGE), Some(package.clone()), "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shim_scripts_with_an_absolute_path_and_non_ascii_spaces() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let package = install(&tmp.path().join("山田\u{3000}太郎\u{a0}x"));
|
||||
let script = format!("#!/bin/sh\nexec node \"{}/bin/ngserver\" \"$@\"\n", package.display());
|
||||
assert_eq!(package_dir(&shim(tmp.path(), &script), PACKAGE), Some(package));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shim_scripts_skip_other_packages_and_other_directories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
install(&tmp.path().join("home"));
|
||||
for script in [
|
||||
"exec node \"$basedir/../home/node_modules/@angular/language-server-next/bin/ngserver\"\n",
|
||||
"exec node \"$HOME/node_modules/@angular/language-server/bin/ngserver\"\n",
|
||||
"exec node \"$basedirx/../home/node_modules/@angular/language-server/bin/ngserver\"\n",
|
||||
"exec node ../home/node_modules/@angular/language-server/bin/ngserver\n",
|
||||
] {
|
||||
assert_eq!(script_targets(&shim(tmp.path(), script), PACKAGE), Vec::<PathBuf>::new(), "{script}");
|
||||
}
|
||||
let large = format!(
|
||||
"{}\n\"$basedir/../home/node_modules/@angular/language-server/bin/ngserver\"\n",
|
||||
"#".repeat(64 * 1024)
|
||||
);
|
||||
assert_eq!(script_targets(&shim(tmp.path(), &large), PACKAGE), Vec::<PathBuf>::new());
|
||||
}
|
||||
candidates.into_iter().find(|c| c.join("package.json").is_file())
|
||||
}
|
||||
@@ -208,6 +208,37 @@ fn project_jdk_and_maven_settings() {
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_maven_goal_configs_take_the_configured_launcher() {
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let maven = tmp.path().join("maven");
|
||||
std::fs::create_dir_all(maven.join("bin")).unwrap();
|
||||
std::fs::write(maven.join("bin/mvn"), "").unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.languages.java.maven.home = maven.to_string_lossy().into_owned();
|
||||
s.languages.java.maven.user_settings = "/m2/settings.xml".into();
|
||||
|
||||
// A goal configuration saved from the tool window (`mvn -s … clean`):
|
||||
// the bare launcher resolves to the configured Maven home (#328) and its
|
||||
// own args are left alone.
|
||||
let mut saved = run("maven", "mvn", &["-s", "/m2/settings.xml", "clean"]);
|
||||
saved.detected = false;
|
||||
// A custom path / the wrapper stay as configured.
|
||||
let mut custom = run("maven", "/opt/other/bin/mvn", &["package"]);
|
||||
custom.detected = false;
|
||||
let mut wrapper = run("maven", "./mvnw", &["package"]);
|
||||
wrapper.detected = false;
|
||||
let mut configs = vec![saved, custom, wrapper];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].command, maven.join("bin/mvn").to_string_lossy());
|
||||
assert_eq!(configs[0].args, ["-s", "/m2/settings.xml", "clean"], "saved args are kept");
|
||||
assert_eq!(configs[1].command, "/opt/other/bin/mvn");
|
||||
assert_eq!(configs[2].command, "./mvnw");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_server_settings_disable_add_and_override() {
|
||||
use crate::apply::{language_servers, server_launch_overrides, server_protocol_overrides, with_custom_servers};
|
||||
@@ -673,6 +704,160 @@ fn angular_language_server_probes_its_own_package_then_the_project() {
|
||||
assert_eq!((cfg.launch_error, cfg.args), (None, vec!["--stdio".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_language_server_is_found_behind_version_manager_shims() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("app");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let install = |node_modules: &Path| {
|
||||
let package = node_modules.join("@angular/language-server");
|
||||
std::fs::create_dir_all(&package).unwrap();
|
||||
std::fs::write(package.join("package.json"), "{}").unwrap();
|
||||
package
|
||||
};
|
||||
let probes = |command: &Path, s: &Settings, env: &[(&str, &str)]| {
|
||||
let mut cfg = server("angular-language-server");
|
||||
cfg.command = command.to_string_lossy().into_owned();
|
||||
cfg.env.extend(env.iter().map(|(k, v)| (k.to_string(), v.to_string())));
|
||||
configure_server(&mut cfg, &project, &project, s);
|
||||
cfg.args.iter().position(|a| a == "--ngProbeLocations").map(|i| cfg.args[i + 1].clone())
|
||||
};
|
||||
let with_project = |package: &Path| Some(format!("{},{}", package.to_string_lossy(), project.to_string_lossy()));
|
||||
|
||||
// pnpm: the shim script runs the package from pnpm's global directory.
|
||||
let pnpm = tmp.path().join("pnpm");
|
||||
let package = install(&pnpm.join("global/v11/abc/node_modules"));
|
||||
let shim = npm_shim(&pnpm.join("bin"), "ngserver");
|
||||
let script = "exec node \"$basedir/../global/v11/abc/node_modules/@angular/language-server/bin/ngserver\" \"$@\"\n";
|
||||
std::fs::write(&shim, format!("#!/bin/sh\n{script}")).unwrap();
|
||||
assert_eq!(probes(&shim, &Settings::default(), &[]), with_project(&dunce::canonicalize(&package).unwrap()));
|
||||
|
||||
// Volta: the package's image, next to the shim's directory. Joined as the lookup
|
||||
// joins it: the probe locations compare as text, and Windows keeps a `/` as given.
|
||||
let volta = tmp.path().join("volta");
|
||||
let image = volta.join("tools").join("image").join("packages").join("@angular/language-server");
|
||||
let package = install(&image.join("lib").join("node_modules"));
|
||||
let shim = npm_shim(&volta.join("bin"), "ngserver");
|
||||
assert_eq!(probes(&shim, &Settings::default(), &[]), with_project(&package));
|
||||
|
||||
// asdf, mise: the shim names only the command; the manager's npm shim knows
|
||||
// where global packages are, run as the server is: in the project (whose
|
||||
// `.tool-versions` picks the Node), with the login shell's and its own variables.
|
||||
let root_of = |package: &Path| package.parent().unwrap().parent().unwrap().display().to_string();
|
||||
let package = install(&tmp.path().join("asdf/installs/nodejs/24/lib/node_modules"));
|
||||
std::fs::write(project.join(".tool-versions"), "nodejs 24\n").unwrap();
|
||||
// The only writer in this test binary.
|
||||
ide_core::process::set_shell_env(vec![("OPENIDEA_TEST_SHELL".into(), "1".into())]);
|
||||
let shims = tmp.path().join(".asdf/shims");
|
||||
// The manager's npm runs on the first Node on PATH (`#!/usr/bin/env node`).
|
||||
std::fs::write(
|
||||
npm_shim(&shims, "npm"),
|
||||
if cfg!(windows) {
|
||||
"@if exist .tool-versions if \"%OPENIDEA_TEST_SHELL%\"==\"1\" call node\r\n"
|
||||
} else {
|
||||
"#!/bin/sh\n[ -f .tool-versions ] && [ \"$OPENIDEA_TEST_SHELL\" = 1 ] && exec node\n"
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
npm_shim(&shims, "node"),
|
||||
if cfg!(windows) {
|
||||
"@echo %OPENIDEA_TEST_NPM_ROOT%\r\n"
|
||||
} else {
|
||||
"#!/bin/sh\necho \"$OPENIDEA_TEST_NPM_ROOT\"\n"
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
// Another installation's npm and Node, first on PATH.
|
||||
let node = tmp.path().join("node/bin");
|
||||
let other = root_of(&install(&tmp.path().join("node/lib/node_modules")));
|
||||
for name in ["npm", "node"] {
|
||||
std::fs::write(
|
||||
npm_shim(&node, name),
|
||||
if cfg!(windows) { format!("@echo {other}\r\n") } else { format!("#!/bin/sh\necho '{other}'\n") },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let mut s = Settings::default();
|
||||
s.languages.node.interpreter = node.join("node").to_string_lossy().into_owned();
|
||||
let root = root_of(&package);
|
||||
let env = [("OPENIDEA_TEST_NPM_ROOT", root.as_str())];
|
||||
assert_eq!(probes(&npm_shim(&shims, "ngserver"), &s, &env), with_project(&package));
|
||||
// Not without the manager's own npm, nor for an executable elsewhere: the npm
|
||||
// on PATH may be another installation's.
|
||||
assert_eq!(probes(&npm_shim(&tmp.path().join("mise/shims"), "ngserver"), &s, &env), None);
|
||||
assert_eq!(probes(&npm_shim(&tmp.path().join("bin"), "ngserver"), &s, &env), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn query_output_is_read_within_the_deadline() {
|
||||
// Keep process startup outside a tight timing budget even under workspace load.
|
||||
let timeout = std::time::Duration::from_secs(60);
|
||||
let env = [("PATH", "/usr/bin:/bin")];
|
||||
let started = std::time::Instant::now();
|
||||
let out = crate::exec::query_in(Path::new("/bin/sh"), &["-c", "printf /global/root"], None, &env, timeout);
|
||||
assert_eq!(out.as_deref(), Some("/global/root"));
|
||||
// EOF must return promptly, without waiting for the generous deadline.
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn query_drains_both_pipes_before_the_child_exits() {
|
||||
let out = crate::exec::query_in(
|
||||
Path::new("/bin/sh"),
|
||||
&["-c", "head -c 262144 /dev/zero; head -c 262144 /dev/zero >&2"],
|
||||
None,
|
||||
&[("PATH", "/usr/bin:/bin")],
|
||||
std::time::Duration::from_secs(60),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out.len(), 262144);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn query_is_bounded_when_descendants_keep_pipes_open() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pid = tmp.path().join("pid");
|
||||
// The descendant outlives the query; clean it up even if an assertion fails.
|
||||
struct Descendant(std::path::PathBuf);
|
||||
impl Drop for Descendant {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(pid) = std::fs::read_to_string(&self.0) {
|
||||
let _ = std::process::Command::new("/bin/kill").arg(pid.trim()).status();
|
||||
}
|
||||
}
|
||||
}
|
||||
let _descendant = Descendant(pid.clone());
|
||||
let started = std::time::Instant::now();
|
||||
let out = crate::exec::query_in(
|
||||
Path::new("/bin/sh"),
|
||||
&["-c", "sleep 120 & echo $! > \"$1\"; printf /global/root", "wrapper", pid.to_str().unwrap()],
|
||||
None,
|
||||
&[("PATH", "/usr/bin:/bin")],
|
||||
std::time::Duration::from_secs(30),
|
||||
);
|
||||
assert_eq!(out.as_deref(), Some("/global/root"));
|
||||
// The descendant keeps both pipes open for longer than the query deadline.
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(90));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn query_times_out_when_the_child_does_not_exit() {
|
||||
// exec avoids leaving a descendant behind when the timed-out child is killed.
|
||||
let out = crate::exec::query_in(
|
||||
Path::new("/bin/sh"),
|
||||
&["-c", "printf /global/root; exec sleep 120"],
|
||||
None,
|
||||
&[("PATH", "/usr/bin:/bin")],
|
||||
std::time::Duration::from_millis(100),
|
||||
);
|
||||
assert_eq!(out, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_java_picks_an_older_jdk() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -724,7 +909,7 @@ fn gradle_settings_precedence() {
|
||||
for local in [false, true] {
|
||||
settings.languages.java.gradle.distribution =
|
||||
if local { GradleDistribution::Local } else { GradleDistribution::Wrapper };
|
||||
let expected = if local { root.join("local-gradle/bin").join(plain) } else { plain.into() };
|
||||
let expected = if local { root.join("local-gradle").join("bin").join(plain) } else { plain.into() };
|
||||
for explicit_java in [false, true] {
|
||||
for is_test in [false, true] {
|
||||
let mut configs =
|
||||
|
||||
@@ -38,7 +38,7 @@ pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
|
||||
pub(crate) fn missing_typescript_message() -> String {
|
||||
"Vue Language Server needs TypeScript 5 or 6 (TypeScript 7 has no language service API). \
|
||||
Reinstall it in Settings › Languages & Frameworks › Language Servers, add typescript@\"<7\" \
|
||||
Reinstall it in Settings › Languages & Frameworks › Language Servers, add typescript@6 \
|
||||
to the project, or pick a TypeScript version in Settings › Languages & Frameworks › TypeScript."
|
||||
.to_owned()
|
||||
}
|
||||
@@ -72,6 +72,10 @@ mod tests {
|
||||
assert_eq!(found, Some(t.join(pkg).parent().unwrap().to_path_buf()), "{bin}");
|
||||
}
|
||||
let path = std::env::join_paths([t.join("tools/node_modules/.bin")]).unwrap();
|
||||
// npm's `.bin` shims on Windows get a `.cmd` (or `.exe`) name; the bare
|
||||
// name is not executable there.
|
||||
let shim = if cfg!(windows) { "vue-language-server.cmd" } else { SERVER };
|
||||
touch(&t.join("tools/node_modules/.bin").join(shim));
|
||||
assert_eq!(server_package(SERVER, &path), Some(t.join("tools/node_modules/@vue/language-server")));
|
||||
assert_eq!(server_package("not-installed", &path), None);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT";
|
||||
pub const COMMAND_ENV: &str = "OPENIDEA_GIT_COMMAND_ID";
|
||||
pub const TOKEN_ENV: &str = "OPENIDEA_ASKPASS_TOKEN";
|
||||
/// An unanswered prompt fails after this long.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
@@ -40,8 +41,16 @@ pub fn classify(prompt: &str) -> AskpassKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the UI's credential dialog should offer to remember the answer:
|
||||
/// git's HTTPS password prompts only (the user name travels inside them).
|
||||
pub fn remembers(prompt: &str) -> bool {
|
||||
crate::git_creds::prompt_key(prompt).is_some() && classify(prompt) == AskpassKind::Secret
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Request {
|
||||
#[serde(default)]
|
||||
command_id: Option<u64>,
|
||||
token: String,
|
||||
prompt: String,
|
||||
}
|
||||
@@ -51,7 +60,13 @@ struct Response {
|
||||
answer: Option<String>,
|
||||
}
|
||||
|
||||
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Option<String>>>>>;
|
||||
type Pending = Arc<Mutex<HashMap<u64, PendingPrompt>>>;
|
||||
|
||||
struct PendingPrompt {
|
||||
command_id: Option<u64>,
|
||||
prompt: String,
|
||||
tx: mpsc::Sender<Option<String>>,
|
||||
}
|
||||
|
||||
/// Serves prompts to `on_prompt`; answers come back through [`AskpassServer::answer`].
|
||||
pub struct AskpassServer {
|
||||
@@ -85,10 +100,17 @@ impl AskpassServer {
|
||||
Ok(Self { port, token, exe, pending })
|
||||
}
|
||||
|
||||
/// Answers prompt `id` (`None`: cancelled).
|
||||
pub fn answer(&self, id: u64, answer: Option<String>) {
|
||||
if let Some(tx) = self.pending.lock().remove(&id) {
|
||||
let _ = tx.send(answer);
|
||||
/// Answers prompt `id` (`None`: cancelled). `remember` asks the git
|
||||
/// credential store to keep the answer once the command succeeds.
|
||||
pub fn answer(&self, id: u64, answer: Option<String>, remember: bool) {
|
||||
if let Some(p) = self.pending.lock().remove(&id) {
|
||||
if let Some(a) = answer.as_deref()
|
||||
&& let Some(command_id) = p.command_id
|
||||
&& let Some(store) = crate::git_creds::get()
|
||||
{
|
||||
store.answered(command_id, &p.prompt, a, remember);
|
||||
}
|
||||
let _ = p.tx.send(answer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,9 +145,20 @@ fn serve(
|
||||
let answer = if req.token != token {
|
||||
None
|
||||
} else {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pending.lock().insert(id, tx);
|
||||
let prompt = req.prompt.trim().to_owned();
|
||||
// A saved git HTTPS credential answers silently; a rejected one is
|
||||
// forgotten by `git_creds::command_finished`, not here (the command
|
||||
// may still be running and could retry).
|
||||
if let Some(command_id) = req.command_id
|
||||
&& let Some(store) = crate::git_creds::get()
|
||||
&& let Some(answer) = store.answer_saved(command_id, &prompt)
|
||||
{
|
||||
let mut out = stream;
|
||||
let _ = writeln!(out, "{}", serde_json::to_string(&Response { answer: Some(answer) }).unwrap_or_default());
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pending.lock().insert(id, PendingPrompt { command_id: req.command_id, prompt: prompt.clone(), tx });
|
||||
on_prompt(AskpassPrompt { id, kind: classify(&prompt), prompt });
|
||||
let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten();
|
||||
pending.lock().remove(&id);
|
||||
@@ -156,9 +189,10 @@ pub fn run_helper() -> Option<i32> {
|
||||
let port: u16 = std::env::var(PORT_ENV).ok()?.parse().ok()?;
|
||||
let token = std::env::var(TOKEN_ENV).unwrap_or_default();
|
||||
let prompt = std::env::args().nth(1).unwrap_or_else(|| "Password:".into());
|
||||
let command_id = std::env::var(COMMAND_ENV).ok().and_then(|id| id.parse().ok());
|
||||
let ask = || -> std::io::Result<Option<String>> {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port))?;
|
||||
writeln!(stream, "{}", serde_json::to_string(&Request { token, prompt }).unwrap_or_default())?;
|
||||
writeln!(stream, "{}", serde_json::to_string(&Request { command_id, token, prompt }).unwrap_or_default())?;
|
||||
let mut line = String::new();
|
||||
BufReader::new(stream).read_line(&mut line)?;
|
||||
Ok(serde_json::from_str::<Response>(&line).ok().and_then(|r| r.answer))
|
||||
@@ -196,8 +230,12 @@ mod tests {
|
||||
let token = server.token.clone();
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
writeln!(stream, "{}", serde_json::to_string(&Request { token, prompt: "Password: ".into() }).unwrap())
|
||||
.unwrap();
|
||||
writeln!(
|
||||
stream,
|
||||
"{}",
|
||||
serde_json::to_string(&Request { command_id: Some(42), token, prompt: "Password: ".into() }).unwrap()
|
||||
)
|
||||
.unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(stream).read_line(&mut line).unwrap();
|
||||
serde_json::from_str::<Response>(&line).unwrap().answer
|
||||
@@ -209,7 +247,8 @@ mod tests {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
};
|
||||
server.answer(id, Some("hunter2".into()));
|
||||
assert_eq!(server.pending.lock().get(&id).unwrap().command_id, Some(42));
|
||||
server.answer(id, Some("hunter2".into()), false);
|
||||
assert_eq!(client.join().unwrap().as_deref(), Some("hunter2"));
|
||||
assert!(server.env().iter().any(|(k, v)| k == "SSH_ASKPASS" && v == "helper"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Saved git HTTPS credentials, in the app's own secret store (next to the SSH
|
||||
//! passwords), never in git's global configuration. Answers to askpass prompts
|
||||
//! are remembered only after the git command that used them succeeded, and a
|
||||
//! stored credential that fails authentication is forgotten so the next command
|
||||
//! asks again.
|
||||
|
||||
use crate::secrets::SecretFile;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A stored credential: `user` answered `Username for …`, `secret` the password.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GitCredential {
|
||||
pub user: String,
|
||||
pub secret: String,
|
||||
}
|
||||
|
||||
/// What [`GitCredentials::lookup`] decided for a prompt.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GitAnswer {
|
||||
/// Answer the prompt with this text without asking the user.
|
||||
Auto(String),
|
||||
/// Nothing stored; the dialog may offer to remember a new credential.
|
||||
PromptNew,
|
||||
}
|
||||
|
||||
/// Shared store: a [`SecretFile`] of `scheme://host[:port]` → `user\nsecret`, plus the
|
||||
/// state of each git command currently running (credentials it consumed and
|
||||
/// answers to save when it succeeds).
|
||||
#[derive(Clone)]
|
||||
pub struct GitCredentials {
|
||||
saved: Arc<SecretFile>,
|
||||
sessions: Arc<Mutex<HashMap<u64, Session>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Session {
|
||||
/// Stored credentials this command used (possibly wrong): forgotten if the
|
||||
/// command fails with an authentication error.
|
||||
used: HashMap<String, GitCredential>,
|
||||
/// `scheme://host[:port]` → credential the user asked to remember: written when the
|
||||
/// command succeeds.
|
||||
pending: HashMap<String, GitCredential>,
|
||||
}
|
||||
|
||||
/// Global instance: the askpass server and every `git` child process agree on it.
|
||||
static INSTANCE: Mutex<Option<GitCredentials>> = Mutex::new(None);
|
||||
|
||||
/// Installs the store of `path` (the app's data directory). Called once at
|
||||
/// start-up; git prompts before that are simply not remembered.
|
||||
pub fn init(path: PathBuf) {
|
||||
*INSTANCE.lock() = Some(GitCredentials { saved: Arc::new(SecretFile::new(path)), sessions: Arc::default() });
|
||||
}
|
||||
|
||||
/// The installed store, if start-up got that far.
|
||||
pub fn get() -> Option<GitCredentials> {
|
||||
INSTANCE.lock().clone()
|
||||
}
|
||||
|
||||
/// `scheme://host[:port]` of an HTTPS prompt (`Username for 'https://host'` /
|
||||
/// `Password for 'https://user@host'`); `None` for anything else (SSH prompts,
|
||||
/// passphrases, host-key questions — none of git's business here).
|
||||
pub fn prompt_key(prompt: &str) -> Option<String> {
|
||||
let quoted = prompt.split('\'').nth(1)?;
|
||||
let (scheme, rest) = quoted.split_once("://")?;
|
||||
if !matches!(scheme, "http" | "https") {
|
||||
return None;
|
||||
}
|
||||
let authority = rest.split('/').next()?;
|
||||
// `user@host` (possibly with a password): keep the host part only.
|
||||
let host = authority.rsplit('@').next()?;
|
||||
if host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{scheme}://{host}"))
|
||||
}
|
||||
|
||||
/// The user name embedded in a password prompt (`https://user@host`), if any.
|
||||
/// Git URL-encodes it (`%40` for `@`), which a lookup must match.
|
||||
fn prompt_user(prompt: &str) -> Option<String> {
|
||||
let quoted = prompt.split('\'').nth(1)?;
|
||||
let authority = quoted.split_once("://")?.1.split('/').next()?;
|
||||
let (user, _) = authority.rsplit_once('@')?;
|
||||
let user = user.split(':').next()?;
|
||||
(!user.is_empty()).then(|| user.to_owned())
|
||||
}
|
||||
|
||||
/// `stderr` of a failed git command says the stored credential was rejected.
|
||||
fn is_auth_failure(stderr: &str) -> bool {
|
||||
let s = stderr.to_ascii_lowercase();
|
||||
s.contains("authentication failed")
|
||||
|| s.contains("authentication unsuccessful")
|
||||
|| s.contains("invalid username or password")
|
||||
|| s.contains("access denied")
|
||||
|| s.contains("authorization failed")
|
||||
|| s.contains("could not read username")
|
||||
|| s.contains("could not read password")
|
||||
|| s.contains("the requested url returned error: 403")
|
||||
|| s.contains("the requested url returned error: 401")
|
||||
}
|
||||
|
||||
impl GitCredentials {
|
||||
/// The stored credential for `key` (`scheme://host[:port]`).
|
||||
pub fn credential(&self, key: &str) -> Option<GitCredential> {
|
||||
let raw = self.saved.get(key)?;
|
||||
let (user, secret) = raw.split_once('\n')?;
|
||||
Some(GitCredential { user: user.to_owned(), secret: secret.to_owned() })
|
||||
}
|
||||
|
||||
/// What to do with a git HTTPS `prompt`: answer it from the store or show
|
||||
/// the dialog.
|
||||
/// `None`: not a git HTTPS credential prompt.
|
||||
pub fn lookup(&self, prompt: &str) -> Option<GitAnswer> {
|
||||
let key = prompt_key(prompt)?;
|
||||
let wants_user = prompt.to_ascii_lowercase().starts_with("username");
|
||||
match self.credential(&key) {
|
||||
Some(c) => {
|
||||
// The password prompt carries the user name git will send: a
|
||||
// mismatch means the stored entry belongs to another account.
|
||||
let answer = if wants_user {
|
||||
Some(c.user)
|
||||
} else {
|
||||
prompt_user(prompt).is_none_or(|u| u == c.user).then_some(c.secret)
|
||||
};
|
||||
Some(answer.map_or(GitAnswer::PromptNew, GitAnswer::Auto))
|
||||
}
|
||||
None => Some(GitAnswer::PromptNew),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored answer to `prompt`; `None` falls through to the UI prompt.
|
||||
/// Only a consumed *password* marks `key` as used — a stored user name
|
||||
/// alone proves nothing about the credential's validity.
|
||||
pub fn answer_saved(&self, command_id: u64, prompt: &str) -> Option<String> {
|
||||
let key = prompt_key(prompt)?;
|
||||
let mut sessions = self.sessions.lock();
|
||||
let credential = self.credential(&key)?;
|
||||
if prompt.to_ascii_lowercase().starts_with("username") {
|
||||
return Some(credential.user);
|
||||
}
|
||||
if prompt_user(prompt).is_some_and(|user| user != credential.user) {
|
||||
return None;
|
||||
}
|
||||
let answer = credential.secret.clone();
|
||||
sessions.entry(command_id).or_default().used.insert(key, credential);
|
||||
Some(answer)
|
||||
}
|
||||
|
||||
/// The user's `answer` to `prompt`, remembered when the current git command
|
||||
/// succeeds (`remember` = the dialog's "Remember" checkbox). Records the
|
||||
/// key only for pending saves: a re-typed answer does not consume the
|
||||
/// stored credential, so an auth failure must not delete it.
|
||||
pub fn answered(&self, command_id: u64, prompt: &str, answer: &str, remember: bool) {
|
||||
if !remember {
|
||||
return;
|
||||
}
|
||||
let Some(key) = prompt_key(prompt) else { return };
|
||||
let mut sessions = self.sessions.lock();
|
||||
let s = sessions.entry(command_id).or_default();
|
||||
let wants_user = prompt.to_ascii_lowercase().starts_with("username");
|
||||
let entry = s.pending.entry(key).or_insert(GitCredential { user: String::new(), secret: String::new() });
|
||||
if wants_user {
|
||||
entry.user = answer.to_owned();
|
||||
} else {
|
||||
entry.secret = answer.to_owned();
|
||||
// The password prompt carries the user name git will send.
|
||||
if entry.user.is_empty()
|
||||
&& let Some(u) = prompt_user(prompt)
|
||||
{
|
||||
entry.user = u;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when a git child process exits: on success, writes the remembered
|
||||
/// credentials and marks used ones as verified; on an authentication
|
||||
/// failure, forgets every credential the command consumed so the next run
|
||||
/// asks again instead of looping on a wrong password.
|
||||
pub fn command_finished(&self, command_id: u64, success: bool, stderr: &str) {
|
||||
let mut sessions = self.sessions.lock();
|
||||
let Some(session) = sessions.remove(&command_id) else { return };
|
||||
if success {
|
||||
for (key, c) in session.pending {
|
||||
if c.secret.is_empty() {
|
||||
continue; // a lone user name is not a credential
|
||||
}
|
||||
if let Err(e) = self.saved.set(&key, &format!("{}\n{}", c.user, c.secret)) {
|
||||
tracing::warn!("git credentials: {}", e.message);
|
||||
}
|
||||
}
|
||||
} else if is_auth_failure(stderr) {
|
||||
// `used` holds exactly the keys whose stored password was sent.
|
||||
for (key, used) in session.used {
|
||||
if self.credential(&key).as_ref() == Some(&used) {
|
||||
self.saved.delete(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Git: `scheme://host[:port]` entries with a saved credential.
|
||||
pub fn list(&self) -> Vec<String> {
|
||||
self.saved.keys()
|
||||
}
|
||||
|
||||
/// Forgets the credential of `key` (Settings › Git › Clear, or a remote edit).
|
||||
pub fn forget(&self, key: &str) {
|
||||
self.saved.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn store() -> (tempfile::TempDir, GitCredentials) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("git-credentials.json");
|
||||
(tmp, GitCredentials { saved: Arc::new(SecretFile::new(path)), sessions: Arc::default() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_https_prompts() {
|
||||
assert_eq!(prompt_key("Username for 'https://github.com': ").as_deref(), Some("https://github.com"));
|
||||
assert_eq!(prompt_key("Password for 'https://[email protected]': ").as_deref(), Some("https://github.com"));
|
||||
assert_eq!(
|
||||
prompt_key("Password for 'https://user%[email protected]:8443/x': ").as_deref(),
|
||||
Some("https://example.com:8443")
|
||||
);
|
||||
assert_eq!(prompt_key("[email protected]'s password: "), None);
|
||||
assert_eq!(prompt_key("Enter passphrase for key '/u/.ssh/id_ed25519': "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saves_only_after_success_and_answers_silently() {
|
||||
let (_t, c) = store();
|
||||
// First run: prompts the user, who checks "remember".
|
||||
assert_eq!(c.lookup("Username for 'https://github.com': "), Some(GitAnswer::PromptNew));
|
||||
c.answered(1, "Username for 'https://github.com': ", "me", true);
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "secret", true);
|
||||
// A failure before the password is verified saves nothing.
|
||||
c.command_finished(1, false, "fatal: some other error");
|
||||
assert_eq!(c.lookup("Username for 'https://github.com': "), Some(GitAnswer::PromptNew));
|
||||
|
||||
c.answered(1, "Username for 'https://github.com': ", "me", true);
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "secret", true);
|
||||
c.command_finished(1, true, "");
|
||||
// Second run: no prompts at all.
|
||||
assert_eq!(c.lookup("Username for 'https://github.com': "), Some(GitAnswer::Auto("me".into())));
|
||||
assert_eq!(c.lookup("Password for 'https://[email protected]': "), Some(GitAnswer::Auto("secret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgets_a_rejected_credential() {
|
||||
let (_t, c) = store();
|
||||
c.answered(1, "Username for 'https://github.com': ", "me", true);
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "wrong", true);
|
||||
c.command_finished(1, true, "");
|
||||
// The next command consumes the stored credential silently.
|
||||
assert_eq!(c.answer_saved(1, "Username for 'https://github.com': ").as_deref(), Some("me"));
|
||||
assert_eq!(c.answer_saved(1, "Password for 'https://[email protected]': ").as_deref(), Some("wrong"));
|
||||
c.command_finished(
|
||||
1,
|
||||
false,
|
||||
"remote: Invalid username or password.\nfatal: Authentication failed for 'https://github.com/x.git/'",
|
||||
);
|
||||
assert_eq!(c.lookup("Username for 'https://github.com': "), Some(GitAnswer::PromptNew));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_and_forgets() {
|
||||
let (_t, c) = store();
|
||||
c.answered(1, "Username for 'https://a.example.com': ", "u", true);
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "p", true);
|
||||
c.answered(1, "Username for 'https://b.example.com': ", "u", true);
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "p", true);
|
||||
c.command_finished(1, true, "");
|
||||
assert_eq!(c.list(), vec!["https://a.example.com", "https://b.example.com"]);
|
||||
c.forget("https://a.example.com");
|
||||
assert_eq!(c.list(), vec!["https://b.example.com"]);
|
||||
}
|
||||
#[test]
|
||||
fn interleaved_commands_do_not_share_pending_or_used_credentials() {
|
||||
for failure_first in [false, true] {
|
||||
let (_t, c) = store();
|
||||
let old = "Password for 'https://[email protected]:8443': ";
|
||||
let new = "Password for 'https://[email protected]:8443': ";
|
||||
c.answered(1, old, "rejected", true);
|
||||
c.command_finished(1, true, "");
|
||||
|
||||
assert_eq!(c.answer_saved(2, old).as_deref(), Some("rejected"));
|
||||
c.answered(3, new, "verified", true);
|
||||
c.command_finished(4, true, "");
|
||||
assert!(c.credential("https://new.example:8443").is_none());
|
||||
assert!(c.credential("https://old.example:8443").is_some());
|
||||
if failure_first {
|
||||
c.command_finished(2, false, "fatal: Authentication failed");
|
||||
assert!(c.credential("https://new.example:8443").is_none());
|
||||
c.command_finished(3, true, "");
|
||||
} else {
|
||||
c.command_finished(3, true, "");
|
||||
assert!(c.credential("https://old.example:8443").is_some());
|
||||
c.command_finished(2, false, "fatal: Authentication failed");
|
||||
}
|
||||
assert!(c.credential("https://old.example:8443").is_none());
|
||||
assert_eq!(c.credential("https://new.example:8443").unwrap().secret, "verified");
|
||||
assert!(c.sessions.lock().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_success_does_not_save_an_unverified_password() {
|
||||
let (_t, c) = store();
|
||||
c.answered(1, "Password for 'https://[email protected]': ", "wrong", true);
|
||||
c.command_finished(2, true, "");
|
||||
assert!(c.list().is_empty());
|
||||
c.command_finished(1, false, "HTTP Basic: Access denied");
|
||||
assert!(c.list().is_empty());
|
||||
assert!(c.sessions.lock().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_failure_does_not_delete_a_newly_verified_password() {
|
||||
let (_t, c) = store();
|
||||
let prompt = "Password for 'https://[email protected]': ";
|
||||
c.answered(1, prompt, "old", true);
|
||||
c.command_finished(1, true, "");
|
||||
c.answer_saved(2, prompt).unwrap();
|
||||
c.answered(3, prompt, "new", true);
|
||||
c.command_finished(3, true, "");
|
||||
c.command_finished(2, false, "Authentication failed");
|
||||
assert_eq!(c.answer_saved(4, prompt).as_deref(), Some("new"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_and_ipv6_are_distinct_credential_keys() {
|
||||
for (url, key) in [
|
||||
("http://[email protected]:8080/repo", "http://example.com:8080"),
|
||||
("https://[email protected]:8443/repo", "https://example.com:8443"),
|
||||
("https://me@[::1]:8443/repo", "https://[::1]:8443"),
|
||||
("https://[::1]/repo", "https://[::1]"),
|
||||
] {
|
||||
assert_eq!(prompt_key(&format!("Password for '{url}': ")).as_deref(), Some(key));
|
||||
}
|
||||
let (_t, c) = store();
|
||||
c.answered(1, "Password for 'https://[email protected]:8443': ", "secret", true);
|
||||
c.command_finished(1, true, "");
|
||||
assert!(c.answer_saved(2, "Password for 'https://[email protected]:9443': ").is_none());
|
||||
assert!(c.answer_saved(2, "Password for 'https://[email protected]': ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_auth_errors_without_matching_arbitrary_numbers() {
|
||||
for message in [
|
||||
"fatal: Authentication failed",
|
||||
"Authentication unsuccessful",
|
||||
"Invalid username or password",
|
||||
"HTTP Basic: Access denied",
|
||||
"Authorization failed",
|
||||
"fatal: could not read Username for 'https://example.com'",
|
||||
"fatal: could not read Password for 'https://example.com'",
|
||||
"fatal: unable to access: The requested URL returned error: 401",
|
||||
"fatal: unable to access: The requested URL returned error: 403",
|
||||
] {
|
||||
assert!(is_auth_failure(message), "{message}");
|
||||
}
|
||||
for message in [
|
||||
"Failed to connect to example.com port 4010",
|
||||
"Could not resolve host: server403.example",
|
||||
"fatal: repository '/repo/401' does not exist",
|
||||
"remote: error in commit abc403def",
|
||||
"The requested URL returned error: 500",
|
||||
] {
|
||||
assert!(!is_auth_failure(message), "{message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! processes, SFTP, local port forwarding, and askpass for `ssh` / `git`.
|
||||
|
||||
pub mod askpass;
|
||||
pub mod git_creds;
|
||||
pub mod manager;
|
||||
pub mod secrets;
|
||||
pub mod session;
|
||||
|
||||
@@ -39,6 +39,12 @@ impl SecretFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stored key, sorted (the secrets themselves stay private).
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
let _g = self.lock.lock();
|
||||
self.read().into_keys().collect()
|
||||
}
|
||||
|
||||
fn read(&self) -> BTreeMap<String, String> {
|
||||
match std::fs::read(&self.path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
|
||||
@@ -16,7 +16,7 @@ tracing.workspace = true
|
||||
which = "8"
|
||||
flate2 = "1"
|
||||
tar = "0.4"
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
zip.workspace = true
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ pub fn extract(
|
||||
ArchiveKind::TarXz => extract_with_tar(archive, dest, "-xJf", cancel),
|
||||
ArchiveKind::TarBz2 => extract_with_tar(archive, dest, "-xjf", cancel),
|
||||
ArchiveKind::Gz => {
|
||||
validate_single_name(dest, single_name)?;
|
||||
let mut gz = flate2::read::GzDecoder::new(BufReader::new(File::open(archive)?));
|
||||
let target = dest.join(single_name);
|
||||
let mut out = File::create(&target)?;
|
||||
@@ -72,6 +73,7 @@ pub fn extract(
|
||||
make_executable(&target)
|
||||
}
|
||||
ArchiveKind::Raw => {
|
||||
validate_single_name(dest, single_name)?;
|
||||
let target = dest.join(single_name);
|
||||
fs::copy(archive, &target)?;
|
||||
make_executable(&target)
|
||||
@@ -80,15 +82,25 @@ pub fn extract(
|
||||
}
|
||||
|
||||
fn extract_tar<R: io::Read>(mut archive: tar::Archive<R>, dest: &Path, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
archive.set_preserve_permissions(true);
|
||||
archive.set_preserve_permissions(false);
|
||||
archive.set_overwrite(true);
|
||||
for entry in archive.entries().map_err(|e| io_err("reading archive", e))? {
|
||||
check(cancel)?;
|
||||
let mut entry = entry.map_err(|e| io_err("reading archive", e))?;
|
||||
// `unpack_in` refuses entries escaping `dest` (returns Ok(false)).
|
||||
entry.unpack_in(dest).map_err(|e| io_err("extracting", e))?;
|
||||
}
|
||||
Ok(())
|
||||
let result = (|| {
|
||||
for entry in archive.entries().map_err(|e| io_err("reading archive", e))? {
|
||||
check(cancel)?;
|
||||
let mut entry = entry.map_err(|e| io_err("reading archive", e))?;
|
||||
if entry.header().entry_type().is_symlink() {
|
||||
let path = entry.path().map_err(|e| io_err("reading archive path", e))?;
|
||||
if let Some(target) = entry.link_name().map_err(|e| io_err("reading archive link", e))? {
|
||||
validate_link(dest, &path, &target)?;
|
||||
}
|
||||
}
|
||||
// `unpack_in` refuses escaping paths and validates link ancestors before writing.
|
||||
entry.unpack_in(dest).map_err(|e| io_err("extracting", e))?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let sanitized = sanitize_tree(dest, dest);
|
||||
result.and(sanitized)
|
||||
}
|
||||
|
||||
fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
@@ -100,6 +112,7 @@ fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeRe
|
||||
if !is_safe_relative(&rel) {
|
||||
continue;
|
||||
}
|
||||
reject_symlink_components(dest, &rel)?;
|
||||
let out = dest.join(&rel);
|
||||
if file.is_dir() {
|
||||
fs::create_dir_all(&out)?;
|
||||
@@ -108,12 +121,16 @@ fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeRe
|
||||
if let Some(parent) = out.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if file.is_symlink() {
|
||||
let mut target = String::new();
|
||||
io::Read::read_to_string(&mut file, &mut target)?;
|
||||
validate_link(dest, &rel, Path::new(&target))?;
|
||||
let _ = fs::remove_file(&out);
|
||||
std::os::unix::fs::symlink(target, &out)?;
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&target, &out)?;
|
||||
// Windows can't create symlinks without SeCreateSymbolicLinkPrivilege
|
||||
// (os error 1314), so we drop in-archive links there rather than fail
|
||||
// the whole extraction. Validation above still rejects escapes.
|
||||
continue;
|
||||
}
|
||||
let mut w = File::create(&out)?;
|
||||
@@ -132,14 +149,121 @@ fn extract_zip(archive: &Path, dest: &Path, cancel: &CancellationToken) -> IdeRe
|
||||
fn extract_with_tar(archive: &Path, dest: &Path, flags: &str, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack this archive"))?;
|
||||
let mut cmd = std::process::Command::new(tar);
|
||||
cmd.arg(flags).arg(archive).arg("-C").arg(dest);
|
||||
let (ok, output, _) = crate::process::run_collect(cmd, cancel, &|_| {})?;
|
||||
cmd.arg(flags).arg(archive).arg("--no-same-owner").arg("--no-same-permissions").arg("-C").arg(dest);
|
||||
let result = crate::process::run_collect(cmd, cancel, &|_| {});
|
||||
// System tar implementations differ in which special permission bits they retain.
|
||||
// Sanitize partial extractions too, without following archive-created links.
|
||||
let sanitized = sanitize_tree(dest, dest);
|
||||
let (ok, output, _) = result?;
|
||||
sanitized?;
|
||||
if !ok {
|
||||
return Err(io_err("tar failed", output.trim()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_single_name(dest: &Path, name: &str) -> IdeResult<()> {
|
||||
let path = Path::new(name);
|
||||
if !is_safe_relative(path) {
|
||||
return Err(IdeError::invalid("archive filename escapes its destination"));
|
||||
}
|
||||
reject_symlink_components(dest, path)
|
||||
}
|
||||
|
||||
fn reject_symlink_components(dest: &Path, rel: &Path) -> IdeResult<()> {
|
||||
let mut path = dest.to_path_buf();
|
||||
for component in rel.components() {
|
||||
path.push(component);
|
||||
match fs::symlink_metadata(&path) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => {
|
||||
return Err(IdeError::invalid("archive entry traverses a symlink"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_link(root: &Path, path: &Path, target: &Path) -> IdeResult<()> {
|
||||
fn resolve(root: &Path, path: &Path, resolved: &mut PathBuf, links: &mut usize) -> IdeResult<()> {
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::Normal(name) => {
|
||||
resolved.push(name);
|
||||
match fs::symlink_metadata(root.join(&*resolved)) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => {
|
||||
*links += 1;
|
||||
if *links > 40 {
|
||||
return Err(IdeError::invalid("archive symlink cycle"));
|
||||
}
|
||||
let target = fs::read_link(root.join(&*resolved))?;
|
||||
resolved.pop();
|
||||
resolve(root, &target, resolved, links)?;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir if resolved.pop() => {}
|
||||
_ => return Err(IdeError::invalid("archive symlink escapes its destination")),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut resolved = PathBuf::new();
|
||||
let mut links = 0;
|
||||
resolve(root, path.parent().unwrap_or(Path::new("")), &mut resolved, &mut links)?;
|
||||
resolve(root, target, &mut resolved, &mut links)
|
||||
}
|
||||
|
||||
fn sanitize_tree(root: &Path, dir: &Path) -> IdeResult<()> {
|
||||
#[cfg(unix)]
|
||||
let mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(dir)?.permissions().mode() & 0o777;
|
||||
// Even a mode-000 directory may contain files whose special bits need clearing.
|
||||
fs::set_permissions(dir, fs::Permissions::from_mode(mode | 0o700))?;
|
||||
mode
|
||||
};
|
||||
let mut error = None;
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let result = (|| {
|
||||
let path = entry?.path();
|
||||
let meta = fs::symlink_metadata(&path)?;
|
||||
if meta.file_type().is_symlink() {
|
||||
let target = fs::read_link(&path)?;
|
||||
if let Err(e) = validate_link(root, path.strip_prefix(root).expect("entry below root"), &target) {
|
||||
fs::remove_file(&path)?;
|
||||
return Err(e);
|
||||
}
|
||||
} else {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(meta.permissions().mode() & 0o777))?;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
sanitize_tree(root, &path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(dir, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
error.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
fn is_safe_relative(p: &Path) -> bool {
|
||||
p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
|
||||
}
|
||||
@@ -149,7 +273,7 @@ pub fn make_executable(path: &Path) -> IdeResult<()> {
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mut perms = fs::metadata(path)?.permissions();
|
||||
perms.set_mode(perms.mode() | 0o755);
|
||||
perms.set_mode((perms.mode() & 0o777) | 0o755);
|
||||
fs::set_permissions(path, perms)?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
@@ -352,6 +476,208 @@ mod tests {
|
||||
assert!(dest.join("ok.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_symlinks_are_confined_to_the_destination() {
|
||||
for target in ["../outside", "/tmp/outside", "a/../../outside"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let archive = tmp.path().join("evil.zip");
|
||||
let mut z = zip::ZipWriter::new(File::create(&archive).unwrap());
|
||||
z.add_symlink("link", target, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.finish().unwrap();
|
||||
let dest = tmp.path().join("out");
|
||||
assert!(extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).is_err());
|
||||
assert!(fs::symlink_metadata(dest.join("link")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn zip_internal_symlink_is_created() {
|
||||
// A link inside the archive (e.g. a framework's Versions/Current) still extracts.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let archive = tmp.path().join("ok.zip");
|
||||
let mut z = zip::ZipWriter::new(File::create(&archive).unwrap());
|
||||
z.start_file("Versions/A/lib", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
io::Write::write_all(&mut z, b"x").unwrap();
|
||||
z.add_symlink("Versions/Current", "A", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
z.finish().unwrap();
|
||||
let dest = tmp.path().join("out");
|
||||
extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).unwrap();
|
||||
assert_eq!(fs::read_link(dest.join("Versions/Current")).unwrap(), Path::new("A"));
|
||||
assert_eq!(fs::read(dest.join("Versions/Current/lib")).unwrap(), b"x");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn zip_does_not_write_or_chmod_through_existing_symlinks() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
for name in ["link", "dir/file"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
fs::create_dir(&outside).unwrap();
|
||||
let file = outside.join("file");
|
||||
fs::write(&file, "original").unwrap();
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let dest = tmp.path().join("out");
|
||||
fs::create_dir(&dest).unwrap();
|
||||
symlink(&file, dest.join("link")).unwrap();
|
||||
symlink(&outside, dest.join("dir")).unwrap();
|
||||
let archive = tmp.path().join("evil.zip");
|
||||
zip_file(&archive, &[(name, b"replaced", 0o777)]);
|
||||
assert!(extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).is_err());
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "original");
|
||||
assert_eq!(fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn archives_strip_special_permission_bits() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for kind in [ArchiveKind::TarGz, ArchiveKind::Zip, ArchiveKind::TarXz, ArchiveKind::TarBz2] {
|
||||
let archive = tmp.path().join(format!("{kind:?}.archive"));
|
||||
match kind {
|
||||
ArchiveKind::TarGz => tar_gz(&archive, &[("tool", b"binary", 0o7777)]),
|
||||
ArchiveKind::Zip => {
|
||||
zip_file(&archive, &[("tool", b"binary", 0o777)]);
|
||||
// ZipWriter strips special bits, so set the central directory's Unix mode directly.
|
||||
let mut bytes = fs::read(&archive).unwrap();
|
||||
let central = bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap();
|
||||
bytes[central + 38..central + 42].copy_from_slice(&(0o107777_u32 << 16).to_le_bytes());
|
||||
fs::write(&archive, bytes).unwrap();
|
||||
}
|
||||
_ => {
|
||||
let source = tmp.path().join(format!("source-{kind:?}"));
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("tool"), "binary").unwrap();
|
||||
fs::set_permissions(source.join("tool"), fs::Permissions::from_mode(0o7777)).unwrap();
|
||||
let flag = if kind == ArchiveKind::TarXz { "-cJf" } else { "-cjf" };
|
||||
assert!(
|
||||
std::process::Command::new("tar")
|
||||
.arg(flag)
|
||||
.arg(&archive)
|
||||
.arg("-C")
|
||||
.arg(&source)
|
||||
.arg("tool")
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
}
|
||||
}
|
||||
let dest = tmp.path().join(format!("out-{kind:?}"));
|
||||
extract(&archive, kind, &dest, "x", &CancellationToken::new()).unwrap();
|
||||
let mode = fs::metadata(dest.join("tool")).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o7000, 0, "{kind:?}");
|
||||
assert_ne!(mode & 0o111, 0, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tar_entries_cannot_escape() {
|
||||
for (name, link) in [("../escape", None), ("link", Some("../escape"))] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let archive = tmp.path().join("evil.tar.gz");
|
||||
let gz = flate2::write::GzEncoder::new(File::create(&archive).unwrap(), flate2::Compression::fast());
|
||||
let mut builder = tar::Builder::new(gz);
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.as_mut_bytes()[..name.len()].copy_from_slice(name.as_bytes());
|
||||
header.set_mode(0o7777);
|
||||
header.set_size(0);
|
||||
if let Some(target) = link {
|
||||
header.set_entry_type(tar::EntryType::Symlink);
|
||||
header.set_link_name(target).unwrap();
|
||||
}
|
||||
header.set_cksum();
|
||||
builder.append(&header, io::empty()).unwrap();
|
||||
builder.into_inner().unwrap().finish().unwrap();
|
||||
let dest = tmp.path().join("out");
|
||||
let _ = extract(&archive, ArchiveKind::TarGz, &dest, "x", &CancellationToken::new());
|
||||
assert!(!tmp.path().join("escape").exists());
|
||||
assert!(fs::symlink_metadata(dest.join("link")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn compressed_tar_cannot_escape_or_retain_special_bits() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
// Both fixtures contain link -> ../outside, link/victim, ../escaped, and a mode-7777 file.
|
||||
for (kind, bytes) in [
|
||||
(ArchiveKind::TarXz, include_bytes!("../tests/fixtures/escape.tar.xz").as_slice()),
|
||||
(ArchiveKind::TarBz2, include_bytes!("../tests/fixtures/escape.tar.bz2").as_slice()),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
fs::create_dir(tmp.path().join("outside")).unwrap();
|
||||
let victim = tmp.path().join("outside/victim");
|
||||
fs::write(&victim, "original").unwrap();
|
||||
fs::set_permissions(&victim, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let archive = tmp.path().join("evil.archive");
|
||||
fs::write(&archive, bytes).unwrap();
|
||||
let dest = tmp.path().join("out");
|
||||
assert!(extract(&archive, kind, &dest, "x", &CancellationToken::new()).is_err());
|
||||
assert_eq!(fs::read_to_string(&victim).unwrap(), "original");
|
||||
assert_eq!(fs::metadata(&victim).unwrap().permissions().mode() & 0o7777, 0o600);
|
||||
assert!(!tmp.path().join("escaped").exists());
|
||||
assert!(fs::symlink_metadata(dest.join("link")).is_err());
|
||||
if let Ok(meta) = fs::metadata(dest.join("special")) {
|
||||
assert_eq!(meta.permissions().mode() & 0o7000, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn tar_link_resolution_handles_chains_and_dangling_targets() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
fs::create_dir(root.join("lib")).unwrap();
|
||||
symlink(".", root.join("alias")).unwrap();
|
||||
assert!(validate_link(root, Path::new("link"), Path::new("alias/../missing")).is_err());
|
||||
assert!(validate_link(root, Path::new("lib/link"), Path::new("../missing")).is_ok());
|
||||
symlink("cycle", root.join("cycle")).unwrap();
|
||||
assert!(validate_link(root, Path::new("link"), Path::new("cycle")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn sanitizing_clears_all_modes_even_after_bad_links() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for name in ["a", "b"] {
|
||||
let dir = root.join(name);
|
||||
fs::create_dir(&dir).unwrap();
|
||||
symlink("../../outside", dir.join("bad-link")).unwrap();
|
||||
fs::write(dir.join("tool"), "binary").unwrap();
|
||||
fs::set_permissions(dir.join("tool"), fs::Permissions::from_mode(0o7777)).unwrap();
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o7000)).unwrap();
|
||||
}
|
||||
fs::set_permissions(root, fs::Permissions::from_mode(0o7777)).unwrap();
|
||||
assert!(sanitize_tree(root, root).is_err());
|
||||
assert_eq!(fs::metadata(root).unwrap().permissions().mode() & 0o7000, 0);
|
||||
for name in ["a", "b"] {
|
||||
let dir = root.join(name);
|
||||
assert_eq!(fs::metadata(&dir).unwrap().permissions().mode() & 0o7777, 0);
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert!(fs::symlink_metadata(dir.join("bad-link")).is_err());
|
||||
assert_eq!(fs::metadata(dir.join("tool")).unwrap().permissions().mode() & 0o7000, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_payload_names_cannot_escape() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let archive = tmp.path().join("raw");
|
||||
fs::write(&archive, "payload").unwrap();
|
||||
for kind in [ArchiveKind::Raw, ArchiveKind::Gz] {
|
||||
assert!(extract(&archive, kind, &tmp.path().join("out"), "../escaped", &CancellationToken::new()).is_err());
|
||||
assert!(!tmp.path().join("escaped").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_gzip_and_raw_payloads() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -108,8 +108,28 @@ fn adoptium_arch(arch: Arch) -> &'static str {
|
||||
|
||||
/// The latest Temurin JDK build of Java `feature` for `platform`.
|
||||
pub fn adoptium_assets_url(feature: u32, platform: Platform) -> String {
|
||||
assets_url(feature, platform, ImageType::Jdk)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ImageType {
|
||||
Jdk,
|
||||
Jre,
|
||||
}
|
||||
|
||||
impl ImageType {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Jdk => "jdk",
|
||||
Self::Jre => "jre",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assets_url(feature: u32, platform: Platform, image: ImageType) -> String {
|
||||
let image = image.name();
|
||||
format!(
|
||||
"{ADOPTIUM_API}/assets/latest/{feature}/hotspot?architecture={}&image_type=jdk&os={}&vendor=eclipse",
|
||||
"{ADOPTIUM_API}/assets/latest/{feature}/hotspot?architecture={}&image_type={image}&os={}&vendor=eclipse",
|
||||
adoptium_arch(platform.arch),
|
||||
adoptium_os(platform.os),
|
||||
)
|
||||
@@ -170,12 +190,16 @@ impl AssetVersion {
|
||||
/// The JDK archive (`.tar.gz` on macOS / Linux, `.zip` on Windows) in an Adoptium
|
||||
/// `assets/latest` response; `None` when there is no build for the platform.
|
||||
pub fn adoptium_pick(json: &str, platform: Platform) -> IdeResult<Option<(Download, u32)>> {
|
||||
pick_image(json, platform, ImageType::Jdk)
|
||||
}
|
||||
|
||||
fn pick_image(json: &str, platform: Platform, image: ImageType) -> IdeResult<Option<(Download, u32)>> {
|
||||
let assets: Vec<Asset> =
|
||||
serde_json::from_str(json).map_err(|e| proto(format!("unexpected Adoptium response: {e}")))?;
|
||||
let ext = if platform.os == Os::Windows { ".zip" } else { ".tar.gz" };
|
||||
let os = adoptium_os(platform.os);
|
||||
let found = assets.into_iter().find(|a| {
|
||||
a.binary.image_type.as_deref().is_none_or(|t| t == "jdk")
|
||||
a.binary.image_type.as_deref().is_none_or(|t| t == image.name())
|
||||
&& a.binary.heap_size.as_deref().is_none_or(|h| h == "normal")
|
||||
&& a.binary.os.as_deref().is_none_or(|o| o == os)
|
||||
&& a.binary.package.name.ends_with(ext)
|
||||
@@ -255,14 +279,50 @@ impl Tools {
|
||||
location: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<DownloadedJdk> {
|
||||
self.download_java(vendor, feature, location, false, cancel, emit)
|
||||
}
|
||||
|
||||
/// Downloads a runtime for a language server, preferring a JRE. Only a
|
||||
/// platform without a JRE build falls back to a full JDK.
|
||||
pub fn download_java_runtime(
|
||||
&self,
|
||||
feature: u32,
|
||||
location: &Path,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<DownloadedJdk> {
|
||||
self.download_java(TEMURIN, feature, Some(location), true, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn download_java(
|
||||
&self,
|
||||
vendor: &str,
|
||||
feature: u32,
|
||||
location: Option<&Path>,
|
||||
runtime: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<DownloadedJdk> {
|
||||
vendor_or_err(vendor)?;
|
||||
let _guard = InstallGuard::acquire(&format!("jdk-{vendor}-{feature}"))?;
|
||||
let http = self.http()?;
|
||||
let location = location.map(Path::to_path_buf).unwrap_or_else(|| self.root.join("jdks"));
|
||||
emit(InstallEvent::Line { text: format!("Resolving the latest Eclipse Temurin {feature}…") });
|
||||
let mut picked =
|
||||
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
|
||||
let mut picked = if runtime {
|
||||
pick_image(
|
||||
&http.get_text_or_empty_on_404(&assets_url(feature, self.platform, ImageType::Jre), cancel)?,
|
||||
self.platform,
|
||||
ImageType::Jre,
|
||||
)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if picked.is_none() {
|
||||
picked =
|
||||
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
|
||||
}
|
||||
if picked.is_none() && self.platform.os == Os::Mac && self.platform.arch == Arch::Arm64 {
|
||||
// Java 8 has no Apple Silicon build: the Intel one runs under Rosetta.
|
||||
let intel = Platform { os: Os::Mac, arch: Arch::X64 };
|
||||
@@ -376,6 +436,22 @@ mod tests {
|
||||
assert!(adoptium_pick("{\"errorMessage\":\"x\"}", MAC_ARM).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_assets_use_jre_without_changing_jdk_downloads() {
|
||||
for platform in [MAC_ARM, LINUX_X64, WIN_X64] {
|
||||
assert!(assets_url(25, platform, ImageType::Jre).contains("image_type=jre"));
|
||||
assert!(adoptium_assets_url(25, platform).contains("image_type=jdk"));
|
||||
let ext = if platform.os == Os::Windows { "zip" } else { "tar.gz" };
|
||||
let jdk = asset(&format!("java.{ext}"), adoptium_os(platform.os), "normal", "");
|
||||
let jre = jdk.replace("\"image_type\":\"jdk\"", "\"image_type\":\"jre\"");
|
||||
assert!(pick_image(&format!("[{jre}]"), platform, ImageType::Jre).unwrap().is_some());
|
||||
assert!(adoptium_pick(&format!("[{jre}]"), platform).unwrap().is_none());
|
||||
assert!(pick_image(&format!("[{jdk}]"), platform, ImageType::Jre).unwrap().is_none());
|
||||
assert!(pick_image("[]", platform, ImageType::Jre).unwrap().is_none());
|
||||
assert!(pick_image("offline", platform, ImageType::Jre).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_8_versions_and_dir_names() {
|
||||
let v = AssetVersion { major: 8, minor: 0, security: 472, openjdk_version: Some("1.8.0_472-b08".into()) };
|
||||
@@ -448,7 +524,7 @@ mod tests {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(platform) = other {
|
||||
let tools = Tools::with_paths(crate::tools_dir(tmp.path()), crate::default_search_path(), platform);
|
||||
let tools = Tools::with_paths(crate::tools_dir(tmp.path()), ide_core::tool_path::search_path(), platform);
|
||||
let jdk = tools.download_jdk(TEMURIN, feature, None, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let home = jdk.home.into_path_buf();
|
||||
eprintln!("{}", home.display());
|
||||
|
||||
@@ -28,11 +28,13 @@ use process::{run_collect, run_quiet};
|
||||
pub use registry::{Method, ReleaseSource, TOOLS, ToolKind, ToolSpec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
@@ -77,6 +79,9 @@ pub struct ToolInfo {
|
||||
pub default_args: Vec<String>,
|
||||
/// A language server's `initializationOptions` from its language definition, as JSON text.
|
||||
pub default_initialization_options: Option<String>,
|
||||
/// The interchangeable servers this one belongs to, in preference order: a
|
||||
/// server and the `fallback` ones after it. Empty when it has none.
|
||||
pub alternatives: Vec<String>,
|
||||
}
|
||||
|
||||
/// Streamed install progress.
|
||||
@@ -97,7 +102,7 @@ struct Manifest {
|
||||
|
||||
const MANIFEST: &str = ".openidea-tool.json";
|
||||
|
||||
/// `typescript@<7` → `typescript`, `@vue/language-server` unchanged.
|
||||
/// `typescript@6` → `typescript`, `@vue/language-server` unchanged.
|
||||
fn npm_name(spec: &str) -> &str {
|
||||
match spec[1..].find('@') {
|
||||
Some(i) => &spec[..i + 1],
|
||||
@@ -171,35 +176,39 @@ pub fn path_with_tools(app_data: &Path, path: &std::ffi::OsStr) -> OsString {
|
||||
std::env::join_paths(dirs).unwrap_or_else(|_| path.to_owned())
|
||||
}
|
||||
|
||||
/// `PATH` plus the usual per-user tool locations (GUI apps on macOS start with a minimal `PATH`).
|
||||
pub fn default_search_path() -> OsString {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
ide_core::process::host_var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".bun/bin", ".volta/bin", ".npm-global/bin", "Library/pnpm"] {
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
dirs.retain(|d| !d.as_os_str().is_empty() && seen.insert(d.clone()));
|
||||
std::env::join_paths(dirs).unwrap_or_default()
|
||||
/// An in-flight install another request can join: extra callers subscribe to
|
||||
/// its event stream, share its cancellation (any caller cancels it) and wait
|
||||
/// for the same result instead of failing with "already being installed".
|
||||
/// A second Settings window (its own JS state) hits this when it re-installs
|
||||
/// while a first window's install is still running.
|
||||
struct InstallSlot {
|
||||
cancel: CancellationToken,
|
||||
listeners: Mutex<Vec<mpsc::SyncSender<InstallEvent>>>,
|
||||
result: std::sync::OnceLock<IdeResult<ToolInfo>>,
|
||||
}
|
||||
|
||||
static INSTALLING: Mutex<Option<HashSet<String>>> = Mutex::new(None);
|
||||
impl InstallSlot {
|
||||
fn broadcast(&self, e: InstallEvent) {
|
||||
self.listeners.lock().retain(|tx| tx.try_send(e.clone()).is_ok());
|
||||
}
|
||||
|
||||
struct InstallGuard(String);
|
||||
fn finish(&self, result: IdeResult<ToolInfo>) {
|
||||
let _ = self.result.set(result);
|
||||
self.listeners.lock().clear();
|
||||
}
|
||||
}
|
||||
|
||||
static INSTALLING: Mutex<Option<HashMap<String, Arc<InstallSlot>>>> = Mutex::new(None);
|
||||
|
||||
/// Mutual exclusion for work that cannot be joined (JDK downloads, uninstalls):
|
||||
/// a second caller while the name is busy fails fast.
|
||||
static EXCLUSIVE: Mutex<Option<HashSet<String>>> = Mutex::new(None);
|
||||
|
||||
pub(crate) struct InstallGuard(String);
|
||||
|
||||
impl InstallGuard {
|
||||
fn acquire(name: &str) -> IdeResult<Self> {
|
||||
let mut set = INSTALLING.lock();
|
||||
pub(crate) fn acquire(name: &str) -> IdeResult<Self> {
|
||||
let mut set = EXCLUSIVE.lock();
|
||||
if !set.get_or_insert_with(HashSet::new).insert(name.to_string()) {
|
||||
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{name} is already being installed")));
|
||||
}
|
||||
@@ -209,12 +218,82 @@ impl InstallGuard {
|
||||
|
||||
impl Drop for InstallGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(set) = INSTALLING.lock().as_mut() {
|
||||
if let Some(set) = EXCLUSIVE.lock().as_mut() {
|
||||
set.remove(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks `name` as installing (the slot is removed when the owner finishes) or
|
||||
/// returns the existing slot to join.
|
||||
fn install_slot(name: &str, cancel: &CancellationToken) -> Result<Arc<InstallSlot>, Arc<InstallSlot>> {
|
||||
let mut map = INSTALLING.lock();
|
||||
let map = map.get_or_insert_with(HashMap::new);
|
||||
match map.get(name) {
|
||||
Some(slot) => Err(slot.clone()),
|
||||
None => {
|
||||
let slot = Arc::new(InstallSlot {
|
||||
// The owner's token: its own Cancel and a joined caller's both stop the run.
|
||||
cancel: cancel.clone(),
|
||||
listeners: Mutex::new(Vec::new()),
|
||||
result: std::sync::OnceLock::new(),
|
||||
});
|
||||
map.insert(name.to_string(), slot.clone());
|
||||
Ok(slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn release_install_slot(name: &str, slot: &Arc<InstallSlot>) {
|
||||
let mut map = INSTALLING.lock();
|
||||
// Only the owner removes its slot (a replaced one is not ours).
|
||||
if let Some(map) = map.as_mut()
|
||||
&& map.get(name).is_some_and(|s| Arc::ptr_eq(s, slot))
|
||||
{
|
||||
map.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Follows a running install: forwards its events to `emit`, lets `cancel`
|
||||
/// cancel it, and waits for its result.
|
||||
fn join_install(slot: &Arc<InstallSlot>, cancel: &CancellationToken, emit: Emit) -> IdeResult<ToolInfo> {
|
||||
// Fast path: already done.
|
||||
if let Some(r) = slot.result.get() {
|
||||
return r.clone();
|
||||
}
|
||||
let (tx, rx) = mpsc::sync_channel::<InstallEvent>(256);
|
||||
slot.listeners.lock().push(tx);
|
||||
emit(InstallEvent::Line { text: "Joined the install already in progress…".into() });
|
||||
// Re-check: the install may have finished between the fast path and subscribing.
|
||||
if let Some(r) = slot.result.get() {
|
||||
// Drain whatever was queued so the listener vector drops our sender.
|
||||
while let Ok(e) = rx.try_recv() {
|
||||
emit(e);
|
||||
}
|
||||
return r.clone();
|
||||
}
|
||||
loop {
|
||||
// Events wake the loop; a timeout wakes it for cancellation/result checks.
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(e) => emit(e),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
// `finish` cleared the listeners: the channel closed, the result is up.
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
slot.cancel.cancel();
|
||||
}
|
||||
if let Some(r) = slot.result.get() {
|
||||
// Drain events emitted before the result landed so the log stays ordered.
|
||||
while let Ok(e) = rx.try_recv() {
|
||||
emit(e);
|
||||
}
|
||||
return r.clone();
|
||||
}
|
||||
}
|
||||
slot.result.get().cloned().unwrap_or_else(|| Err(IdeError::internal("install finished without a result")))
|
||||
}
|
||||
|
||||
/// Which languages use which tool, from the language definitions.
|
||||
#[derive(Default)]
|
||||
struct Usage {
|
||||
@@ -224,6 +303,7 @@ struct Usage {
|
||||
install_hint: Option<String>,
|
||||
args: Vec<String>,
|
||||
initialization_options: Option<String>,
|
||||
alternatives: Vec<String>,
|
||||
}
|
||||
|
||||
fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
@@ -266,6 +346,23 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
s.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).map(|v| v.to_string());
|
||||
}
|
||||
}
|
||||
for l in langs {
|
||||
let servers = &l.language_servers;
|
||||
for (i, head) in servers.iter().enumerate().filter(|(_, s)| !s.fallback) {
|
||||
let chain: Vec<String> = std::iter::once(head)
|
||||
.chain(servers[i + 1..].iter().take_while(|s| s.fallback))
|
||||
.map(|s| s.name.clone())
|
||||
.collect();
|
||||
if chain.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
for name in &chain {
|
||||
if let Some(u) = map.get_mut(name).filter(|u| u.alternatives.is_empty()) {
|
||||
u.alternatives = chain.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
@@ -310,12 +407,13 @@ pub struct Tools {
|
||||
custom: BTreeMap<String, PathBuf>,
|
||||
/// Executables found outside the search path (app bundles), by command.
|
||||
found: BTreeMap<String, PathBuf>,
|
||||
version_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
/// Tools under `<app_data>/tools` using [`default_search_path`].
|
||||
/// Tools under `<app_data>/tools` using [`ide_core::tool_path::search_path`].
|
||||
pub fn new(app_data: &Path) -> Self {
|
||||
Self::with_paths(tools_dir(app_data), default_search_path(), Platform::current())
|
||||
Self::with_paths(tools_dir(app_data), ide_core::tool_path::search_path(), Platform::current())
|
||||
}
|
||||
|
||||
pub fn with_paths(root: PathBuf, search_path: OsString, platform: Platform) -> Self {
|
||||
@@ -323,7 +421,15 @@ impl Tools {
|
||||
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
|
||||
let system_path = std::env::join_paths(&system).unwrap_or_default();
|
||||
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
|
||||
Self { root, system_path, child_path, platform, custom: BTreeMap::new(), found: BTreeMap::new() }
|
||||
Self {
|
||||
root,
|
||||
system_path,
|
||||
child_path,
|
||||
platform,
|
||||
custom: BTreeMap::new(),
|
||||
found: BTreeMap::new(),
|
||||
version_timeout: Duration::from_secs(4),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports the executables chosen in settings (command → path) as the tools' location.
|
||||
@@ -343,7 +449,7 @@ impl Tools {
|
||||
}
|
||||
|
||||
fn which(&self, cmd: &str) -> Option<PathBuf> {
|
||||
which::which_in(cmd, Some(&self.system_path), &self.root).ok()
|
||||
ide_core::tool_path::find_command(cmd, &self.system_path, &self.root)
|
||||
}
|
||||
|
||||
fn which_any(&self, cmds: &[&str]) -> Option<PathBuf> {
|
||||
@@ -407,7 +513,7 @@ impl Tools {
|
||||
let program = sibling.or_else(|| self.which(cmd))?;
|
||||
let mut c = self.command(program);
|
||||
c.args(args);
|
||||
let (ok, out) = run_quiet(c, Duration::from_secs(4))?;
|
||||
let (ok, out) = run_quiet(c, self.version_timeout)?;
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
@@ -480,6 +586,7 @@ impl Tools {
|
||||
custom_error: None,
|
||||
default_args: u.args.clone(),
|
||||
default_initialization_options: u.initialization_options.clone(),
|
||||
alternatives: u.alternatives.clone(),
|
||||
})
|
||||
.map(|info| self.apply_custom(info, None));
|
||||
};
|
||||
@@ -504,6 +611,7 @@ impl Tools {
|
||||
custom_error: None,
|
||||
default_args: usage.map(|u| u.args.clone()).unwrap_or_default(),
|
||||
default_initialization_options: usage.and_then(|u| u.initialization_options.clone()),
|
||||
alternatives: usage.map(|u| u.alternatives.clone()).unwrap_or_default(),
|
||||
})
|
||||
.map(|info| self.apply_custom(info, Some(spec)))
|
||||
}
|
||||
@@ -525,7 +633,7 @@ impl Tools {
|
||||
if cmd == spec.commands[0] { path.clone() } else { path.parent().and_then(|d| self.exe_in(d, cmd))? };
|
||||
let mut c = self.command(program);
|
||||
c.args(args);
|
||||
let (ok, out) = run_quiet(c, Duration::from_secs(4))?;
|
||||
let (ok, out) = run_quiet(c, self.version_timeout)?;
|
||||
if ok { parse_version(&out) } else { None }
|
||||
});
|
||||
info.status = ToolStatus::Custom;
|
||||
@@ -627,6 +735,9 @@ impl Tools {
|
||||
}
|
||||
|
||||
/// Installs (or reinstalls / updates) `name`, streaming output to `emit`.
|
||||
/// A second call for a name already installing joins that run: it gets the
|
||||
/// same live events and result instead of an "already installing" error,
|
||||
/// and cancelling either request cancels the shared run.
|
||||
pub fn install(
|
||||
&self,
|
||||
name: &str,
|
||||
@@ -644,37 +755,54 @@ impl Tools {
|
||||
if let Some(reason) = self.unavailable_reason(spec) {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let _guard = InstallGuard::acquire(name)?;
|
||||
std::fs::create_dir_all(&self.root)?;
|
||||
emit(InstallEvent::Line { text: format!("Installing {} via {}…", spec.display, spec.method.label()) });
|
||||
match spec.method {
|
||||
Method::Rustup { component } => {
|
||||
let mut c = self.command(self.which("rustup").expect("checked"));
|
||||
c.args(["component", "add", component]);
|
||||
run_streamed(c, cancel, emit)?;
|
||||
let slot = match install_slot(name, cancel) {
|
||||
Ok(slot) => slot,
|
||||
Err(slot) => return join_install(&slot, cancel, emit),
|
||||
};
|
||||
// The install uses the slot's token: every caller's cancel reaches it.
|
||||
let cancel = &slot.cancel;
|
||||
// Fan the events out to joined callers as well as this request's emit.
|
||||
let fan = |e: InstallEvent| {
|
||||
emit(e.clone());
|
||||
slot.broadcast(e);
|
||||
};
|
||||
let emit = &fan as Emit;
|
||||
let result = (|| {
|
||||
std::fs::create_dir_all(&self.root)?;
|
||||
emit(InstallEvent::Line { text: format!("Installing {} via {}…", spec.display, spec.method.label()) });
|
||||
match spec.method {
|
||||
Method::Rustup { component } => {
|
||||
let mut c = self.command(self.which("rustup").expect("checked"));
|
||||
c.args(["component", "add", component]);
|
||||
run_streamed(c, cancel, emit)?;
|
||||
}
|
||||
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
Method::Release { source, assets, locate } => {
|
||||
self.install_release(spec, source, assets, locate, cancel, emit)?
|
||||
}
|
||||
}
|
||||
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
Method::Release { source, assets, locate } => {
|
||||
self.install_release(spec, source, assets, locate, cancel, emit)?
|
||||
let info = self.info(name, langs)?;
|
||||
if info.status == ToolStatus::Missing {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Io,
|
||||
format!("installer finished but `{}` was not found afterwards", spec.commands[0]),
|
||||
));
|
||||
}
|
||||
}
|
||||
let info = self.info(name, langs)?;
|
||||
if info.status == ToolStatus::Missing {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Io,
|
||||
format!("installer finished but `{}` was not found afterwards", spec.commands[0]),
|
||||
));
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("{} {} installed", spec.display, info.version.as_deref().unwrap_or("")).replace(" ", " "),
|
||||
});
|
||||
Ok(info)
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("{} {} installed", spec.display, info.version.as_deref().unwrap_or(""))
|
||||
.replace(" ", " "),
|
||||
});
|
||||
Ok(info)
|
||||
})();
|
||||
release_install_slot(name, &slot);
|
||||
slot.finish(result.clone());
|
||||
result
|
||||
}
|
||||
|
||||
fn npm_manager(&self) -> IdeResult<(PathBuf, bool)> {
|
||||
@@ -1037,7 +1165,11 @@ impl Tools {
|
||||
/// Removes a tool the IDE installed.
|
||||
pub fn uninstall(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
|
||||
let spec = registry::find(name).ok_or_else(|| IdeError::not_found(format!("unknown tool `{name}`")))?;
|
||||
let _guard = InstallGuard::acquire(name)?;
|
||||
// Uninstalling mid-install would tear down the directory under the running installer.
|
||||
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(name)) {
|
||||
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{name} is already being installed")));
|
||||
}
|
||||
let _guard = InstallGuard::acquire(&format!("uninstall-{name}"))?;
|
||||
let cancel = CancellationToken::new();
|
||||
let quiet = |_: InstallEvent| {};
|
||||
match spec.method {
|
||||
|
||||
@@ -221,7 +221,25 @@ impl Http {
|
||||
|
||||
/// GETs `url` as text, failing when the response is larger than `max_bytes`.
|
||||
pub fn get_text_limited(&self, url: &str, max_bytes: Option<u64>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.get_text_response(url, max_bytes, false, cancel)
|
||||
}
|
||||
|
||||
/// Adoptium uses 404 as well as an empty array for absent platform builds.
|
||||
pub fn get_text_or_empty_on_404(&self, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.get_text_response(url, None, true, cancel)
|
||||
}
|
||||
|
||||
fn get_text_response(
|
||||
&self,
|
||||
url: &str,
|
||||
max_bytes: Option<u64>,
|
||||
empty_on_404: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let mut cmd = self.base(url);
|
||||
if empty_on_404 {
|
||||
cmd.args(["--write-out", "\n%{http_code}"]);
|
||||
}
|
||||
if let Some(max) = max_bytes {
|
||||
cmd.arg("--max-filesize").arg(max.to_string());
|
||||
}
|
||||
@@ -246,7 +264,14 @@ impl Http {
|
||||
None => std::thread::sleep(Duration::from_millis(30)),
|
||||
}
|
||||
};
|
||||
let body = out_t.join().unwrap_or_default();
|
||||
let mut body = out_t.join().unwrap_or_default();
|
||||
if empty_on_404 && let Some(split) = body.iter().rposition(|b| *b == b'\n') {
|
||||
let code = &body[split + 1..];
|
||||
if code == b"404" {
|
||||
return Ok("[]".into());
|
||||
}
|
||||
body.truncate(split);
|
||||
}
|
||||
if let Some(max) = max_bytes
|
||||
&& body.len() as u64 > max
|
||||
{
|
||||
@@ -362,6 +387,25 @@ mod tests {
|
||||
assert!(lines.contains(&"one".to_string()) && lines.contains(&"two".to_string()), "{lines:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn absent_build_is_empty_but_http_failures_are_not() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let curl = tmp.path().join("curl");
|
||||
let http = Http { curl: curl.clone(), https_only: false };
|
||||
for (code, exit, expected) in [(404, 22, Some("[]")), (200, 0, Some("payload")), (403, 22, None), (0, 7, None)]
|
||||
{
|
||||
std::fs::write(&curl, format!("#!/bin/sh\nprintf 'payload\\n{code:03}'\nexit {exit}\n")).unwrap();
|
||||
std::fs::set_permissions(&curl, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let result = http.get_text_or_empty_on_404("https://example.test/build", &CancellationToken::new());
|
||||
match expected {
|
||||
Some(body) => assert_eq!(result.unwrap(), body),
|
||||
None => assert!(result.is_err()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancellation_kills_the_child() {
|
||||
|
||||
@@ -114,7 +114,7 @@ const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str]
|
||||
|
||||
/// The TypeScript these npm servers load as a library (`tsserver.js`, `ts.server`):
|
||||
/// TypeScript 7 (the native port) ships neither, and `@latest` resolves to it.
|
||||
pub const TYPESCRIPT: &str = "typescript@<7";
|
||||
pub const TYPESCRIPT: &str = "typescript@6";
|
||||
|
||||
pub static TOOLS: &[ToolSpec] = &[
|
||||
ToolSpec {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! version publishes one per supported host platform (see `release.yml`).
|
||||
|
||||
use crate::process::Http;
|
||||
use crate::{InstallEvent, default_search_path, fetch_verified, sources};
|
||||
use crate::{InstallEvent, fetch_verified, sources};
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -46,7 +46,7 @@ pub fn fetch(
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let staging = tempfile_dir(dir)?;
|
||||
let result = (|| {
|
||||
let http = Http::new(&default_search_path())?;
|
||||
let http = Http::new(&ide_core::tool_path::search_path())?;
|
||||
// The binary runs on the remote host: never install it unverified.
|
||||
let checksum_url = format!("{url}.sha256");
|
||||
let sha256 = sources::parse_checksum(&http.get_text(&checksum_url, cancel)?, &name)
|
||||
|
||||
@@ -24,7 +24,10 @@ impl Env {
|
||||
fn tools(&self) -> Tools {
|
||||
let mut dirs = vec![self.sys.clone()];
|
||||
dirs.extend(bin_dirs_in(&self.root, Platform::current()));
|
||||
Tools::with_paths(self.root.clone(), std::env::join_paths(dirs).unwrap(), Platform::current())
|
||||
let mut tools = Tools::with_paths(self.root.clone(), std::env::join_paths(dirs).unwrap(), Platform::current());
|
||||
// These fixtures test detection and version parsing, not process startup latency.
|
||||
tools.version_timeout = Duration::from_secs(60);
|
||||
tools
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -88,6 +91,20 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert!(find(&list, "delve").kind == ToolKind::Debugger);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interchangeable_servers_list_their_alternatives() {
|
||||
let env = Env::new();
|
||||
let list = env.tools().list(&langs());
|
||||
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, "rust-analyzer").alternatives.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn detects_tools_on_path_with_versions() {
|
||||
@@ -180,6 +197,80 @@ fn concurrent_installs_of_one_tool_are_rejected() {
|
||||
assert!(InstallGuard::acquire("x-tool").is_ok());
|
||||
}
|
||||
|
||||
/// A second caller mid-install joins the run (the other Settings window's
|
||||
/// duplicate install) and shares the result instead of `AlreadyExists`.
|
||||
#[test]
|
||||
fn second_install_joins_the_running_one() {
|
||||
let slot = match install_slot("sqls", &CancellationToken::new()) {
|
||||
Ok(slot) => slot,
|
||||
Err(_) => panic!("no install is running"),
|
||||
};
|
||||
let owner = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..3 {
|
||||
slot.broadcast(InstallEvent::Line { text: format!("line {i}") });
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
release_install_slot("sqls", &slot);
|
||||
slot.finish(Err(IdeError::new(ErrorKind::Io, "compile failed")));
|
||||
})
|
||||
};
|
||||
let events = Mutex::new(Vec::new());
|
||||
let err = join_install(&slot, &CancellationToken::new(), &|e| events.lock().push(e)).unwrap_err();
|
||||
owner.join().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Io);
|
||||
assert_eq!(err.message, "compile failed");
|
||||
let texts: Vec<String> = events
|
||||
.into_inner()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
InstallEvent::Line { text } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(texts.contains(&"Joined the install already in progress…".to_string()), "{texts:?}");
|
||||
assert!(texts.iter().any(|l| l == "line 2"), "{texts:?}");
|
||||
// The slot is released: a fresh install can start.
|
||||
match install_slot("sqls", &CancellationToken::new()) {
|
||||
Ok(fresh) => release_install_slot("sqls", &fresh),
|
||||
Err(_) => panic!("the finished install still holds its slot"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A late caller gets the finished result without waiting.
|
||||
#[test]
|
||||
fn install_joined_after_it_finished_returns_the_result() {
|
||||
let slot = match install_slot("marksman", &CancellationToken::new()) {
|
||||
Ok(slot) => slot,
|
||||
Err(_) => panic!("no install is running"),
|
||||
};
|
||||
let ok = ToolInfo {
|
||||
name: "marksman".into(),
|
||||
display_name: "Marksman".into(),
|
||||
kind: ToolKind::LanguageServer,
|
||||
command: "marksman".into(),
|
||||
languages: vec![],
|
||||
status: ToolStatus::Installed,
|
||||
path: None,
|
||||
version: Some("1.0".into()),
|
||||
install_method: None,
|
||||
can_install: true,
|
||||
unavailable_reason: None,
|
||||
can_uninstall: true,
|
||||
install_hint: None,
|
||||
homepage: None,
|
||||
custom_error: None,
|
||||
default_args: vec![],
|
||||
default_initialization_options: None,
|
||||
alternatives: vec![],
|
||||
};
|
||||
release_install_slot("marksman", &slot);
|
||||
slot.finish(Ok(ok));
|
||||
let info = join_install(&slot, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.version.as_deref(), Some("1.0"));
|
||||
}
|
||||
|
||||
/// Full release install through a fake `curl` that serves a local release JSON and archive.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -318,7 +409,7 @@ done"#,
|
||||
}
|
||||
let installs = fs::read_to_string(&log).unwrap();
|
||||
for line in installs.lines() {
|
||||
assert!(line.contains("typescript@<7") && !line.contains("typescript@latest"), "{line}");
|
||||
assert!(line.contains("typescript@6") && !line.contains("typescript@latest"), "{line}");
|
||||
}
|
||||
assert!(installs.contains("@vue/language-server@latest"), "{installs}");
|
||||
|
||||
@@ -439,3 +530,25 @@ exit 0"#,
|
||||
let out = std::process::Command::new(&wrapper).output().unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "/opt/dotnet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
|
||||
let spec = registry::find("kotlin-debug-adapter").unwrap();
|
||||
assert!(matches!(
|
||||
spec.method,
|
||||
Method::Release { source: ReleaseSource::GitHub { repo: "fwcd/kotlin-debug-adapter" }, .. }
|
||||
));
|
||||
assert!(langs().iter().any(|l| l.debugger.as_ref().is_some_and(|d| d.adapter == spec.name)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_installing_request_can_still_cancel_its_shared_install() {
|
||||
let owner = CancellationToken::new();
|
||||
let slot = match install_slot("taplo", &owner) {
|
||||
Ok(slot) => slot,
|
||||
Err(_) => panic!("slot already taken"),
|
||||
};
|
||||
owner.cancel();
|
||||
assert!(slot.cancel.is_cancelled());
|
||||
release_install_slot("taplo", &slot);
|
||||
}
|
||||
Бінарний файл не відображається.
Бінарний файл не відображається.
@@ -0,0 +1,27 @@
|
||||
"""Regenerate the malicious tar fixtures used by archive.rs tests (Python stdlib only)."""
|
||||
|
||||
import bz2
|
||||
import io
|
||||
import lzma
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
|
||||
archive = io.BytesIO()
|
||||
with tarfile.open(fileobj=archive, mode="w", format=tarfile.GNU_FORMAT) as tar:
|
||||
for name, target, data in [
|
||||
("link", "../outside", b""),
|
||||
("link/victim", None, b"replaced"),
|
||||
("../escaped", None, b"escaped"),
|
||||
("special", None, b"special"),
|
||||
]:
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.mode = 0o7777
|
||||
if target:
|
||||
entry.type = tarfile.SYMTYPE
|
||||
entry.linkname = target
|
||||
else:
|
||||
entry.size = len(data)
|
||||
tar.addfile(entry, io.BytesIO(data))
|
||||
|
||||
for extension, compress in [("xz", lzma.compress), ("bz2", bz2.compress)]:
|
||||
Path(__file__).with_name(f"escape.tar.{extension}").write_bytes(compress(archive.getvalue()))
|
||||
@@ -13,7 +13,7 @@ ignore.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
gix = { workspace = true, features = ["sha1", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
|
||||
gix = { workspace = true, features = ["sha1", "sha256", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
|
||||
tracing.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
|
||||
@@ -27,6 +27,48 @@ pub fn set_askpass_env(env: Vec<(String, String)>) {
|
||||
*ASKPASS.write().unwrap_or_else(|e| e.into_inner()) = env;
|
||||
}
|
||||
|
||||
/// Called once per git child with its id, success flag, and stderr.
|
||||
pub type GitCommandObserver = std::sync::Arc<dyn Fn(u64, bool, &str) + Send + Sync>;
|
||||
|
||||
static COMMAND_OBSERVER: std::sync::RwLock<Option<(&'static str, GitCommandObserver)>> = std::sync::RwLock::new(None);
|
||||
|
||||
/// Installs the completion observer and the environment variable carrying each
|
||||
/// child's unique id to its credential helper.
|
||||
pub fn set_git_command_observer(env_name: &'static str, observer: GitCommandObserver) {
|
||||
*COMMAND_OBSERVER.write().unwrap_or_else(|e| e.into_inner()) = Some((env_name, observer));
|
||||
}
|
||||
|
||||
struct CommandSession {
|
||||
id: u64,
|
||||
observer: Option<GitCommandObserver>,
|
||||
}
|
||||
|
||||
impl CommandSession {
|
||||
fn start(cmd: &mut Command) -> Self {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let hook = COMMAND_OBSERVER.read().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let observer = hook.map(|(env_name, observer)| {
|
||||
cmd.env(env_name, id.to_string());
|
||||
observer
|
||||
});
|
||||
Self { id, observer }
|
||||
}
|
||||
|
||||
fn finish(&mut self, success: bool, stderr: &str) {
|
||||
if let Some(observer) = self.observer.take() {
|
||||
observer(self.id, success, stderr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CommandSession {
|
||||
fn drop(&mut self) {
|
||||
// Cancellation or an I/O error discards only this child's pending answers.
|
||||
self.finish(false, "");
|
||||
}
|
||||
}
|
||||
|
||||
/// Locates the auto-detected git executable once per process.
|
||||
///
|
||||
/// GUI apps on macOS start with a minimal `PATH`, so a few well-known install
|
||||
@@ -143,6 +185,7 @@ pub(crate) fn run_raw_env(
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
tracing::debug!(?args, "git");
|
||||
let mut session = CommandSession::start(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(spawn_error)?;
|
||||
let writer = match (stdin, child.stdin.take()) {
|
||||
(Some(data), Some(mut pipe)) => {
|
||||
@@ -158,6 +201,7 @@ pub(crate) fn run_raw_env(
|
||||
if let Some(w) = writer {
|
||||
let _ = w.join();
|
||||
}
|
||||
session.finish(out.status.success(), &String::from_utf8_lossy(&out.stderr));
|
||||
Ok(Output { stdout: out.stdout, stderr: out.stderr, code: out.status.code() })
|
||||
}
|
||||
|
||||
@@ -274,6 +318,7 @@ pub(crate) fn run_streaming_env(
|
||||
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)?;
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
@@ -332,11 +377,13 @@ pub(crate) fn run_streaming_env(
|
||||
let _ = r.join();
|
||||
}
|
||||
if status.success() {
|
||||
session.finish(true, &stderr_tail.join("\n"));
|
||||
return Ok(());
|
||||
}
|
||||
let relevant: Vec<&str> =
|
||||
conflicts.iter().chain(stderr_tail.iter()).map(String::as_str).filter(|l| !is_progress_line(l)).collect();
|
||||
let msg = relevant.join("\n");
|
||||
session.finish(false, &stderr_tail.join("\n"));
|
||||
Err(failure(args, msg.as_bytes(), b"", status.code()))
|
||||
}
|
||||
|
||||
@@ -420,3 +467,36 @@ fn kill(child: &mut Child) {
|
||||
}
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod command_session_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn command_ids_reach_children_and_completion_is_once_per_session() {
|
||||
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let seen = events.clone();
|
||||
set_git_command_observer(
|
||||
"OPENIDEA_TEST_COMMAND_ID",
|
||||
std::sync::Arc::new(move |id, success, stderr| {
|
||||
seen.lock().unwrap().push((id, success, stderr.to_owned()));
|
||||
}),
|
||||
);
|
||||
let mut first_cmd = Command::new("git");
|
||||
let mut second_cmd = Command::new("git");
|
||||
let mut first = CommandSession::start(&mut first_cmd);
|
||||
let second = CommandSession::start(&mut second_cmd);
|
||||
let (first_id, second_id) = (first.id, second.id);
|
||||
assert_ne!(first_id, second_id);
|
||||
for (cmd, id) in [(&first_cmd, first_id), (&second_cmd, second_id)] {
|
||||
let value = cmd.get_envs().find(|(key, _)| *key == "OPENIDEA_TEST_COMMAND_ID").unwrap().1.unwrap();
|
||||
assert_eq!(value, std::ffi::OsStr::new(&id.to_string()));
|
||||
}
|
||||
drop(second); // cancellation discards this command's state
|
||||
first.finish(true, "done");
|
||||
drop(first);
|
||||
let events = events.lock().unwrap();
|
||||
let ours: Vec<_> = events.iter().filter(|(id, _, _)| *id == first_id || *id == second_id).cloned().collect();
|
||||
assert_eq!(ours, vec![(second_id, false, String::new()), (first_id, true, "done".into())]);
|
||||
}
|
||||
}
|
||||
@@ -33,17 +33,20 @@ pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeRe
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(IdeError::invalid("Select an absolute path without '..'"));
|
||||
}
|
||||
no_symlinks(path)?;
|
||||
let meta = fs::symlink_metadata(path)?;
|
||||
if !meta.is_file() && !meta.is_dir() {
|
||||
// A symlink or junction is one entry to Git: ignore its name, not its target,
|
||||
// and never trail it with '/' (which matches directories only).
|
||||
let link = is_link(&meta);
|
||||
if !link && !meta.is_file() && !meta.is_dir() {
|
||||
return Err(IdeError::invalid("Only regular files and directories can be ignored"));
|
||||
}
|
||||
let directory = !link && meta.is_dir();
|
||||
// A selected nested repository directory is an entry of its enclosing repository.
|
||||
let start = path.parent().ok_or_else(|| IdeError::invalid("Cannot ignore a filesystem root"))?;
|
||||
let repo = Repo::discover(start)?.ok_or_else(|| IdeError::invalid("Selection is not in a Git repository"))?;
|
||||
let rel =
|
||||
path.strip_prefix(repo.root()).map_err(|_| IdeError::invalid("Selection is outside its repository"))?;
|
||||
let literal = pattern(rel, meta.is_dir())?;
|
||||
let literal = pattern(rel, directory)?;
|
||||
if rel.components().any(|c| c.as_os_str() == ".git") {
|
||||
return Err(IdeError::invalid("Git administration files cannot be ignored"));
|
||||
}
|
||||
@@ -60,10 +63,14 @@ pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeRe
|
||||
let literal_query = format!("./{rel_str}");
|
||||
let ignored = cli::run_raw(repo.root(), &["check-ignore", "-q", "--", &literal_query], None)?;
|
||||
match ignored.code {
|
||||
// Already ignored: unchanged, and nothing needs to be written or opened.
|
||||
Some(0) => continue,
|
||||
Some(1) => {}
|
||||
_ => return Err(IdeError::invalid(ignored.stdout_str() + &String::from_utf8_lossy(&ignored.stderr))),
|
||||
}
|
||||
// Only paths that are about to be written are held to the stricter rule: a
|
||||
// symlinked ancestor can put the rule or the ignore file in another repository.
|
||||
no_symlinked_ancestors(path)?;
|
||||
verify.push((repo.root().to_path_buf(), rel_str.to_owned()));
|
||||
let (file, rule, base) = match destination {
|
||||
IgnoreDestination::LocalExclude => {
|
||||
@@ -89,7 +96,7 @@ pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeRe
|
||||
.take_while(|p| p.starts_with(repo.root()))
|
||||
.find(|p| p.join(".gitignore").symlink_metadata().is_ok())
|
||||
.unwrap_or(repo.root());
|
||||
(base.join(".gitignore"), pattern(path.strip_prefix(base).unwrap(), meta.is_dir())?, base)
|
||||
(base.join(".gitignore"), pattern(path.strip_prefix(base).unwrap(), directory)?, base)
|
||||
}
|
||||
};
|
||||
no_symlinks(file.parent().unwrap())?;
|
||||
@@ -97,7 +104,7 @@ pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeRe
|
||||
edits.entry(file).or_default().push(IgnoreRule {
|
||||
pattern: rule,
|
||||
relative: path.strip_prefix(base).unwrap().to_path_buf(),
|
||||
directory: meta.is_dir(),
|
||||
directory,
|
||||
});
|
||||
}
|
||||
let mut changed = Vec::new();
|
||||
@@ -153,6 +160,40 @@ fn pattern(path: &Path, directory: bool) -> IdeResult<String> {
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
/// A symlink, or a Windows reparse point such as a junction, is a single entry for Git.
|
||||
fn is_link(meta: &fs::Metadata) -> bool {
|
||||
if meta.file_type().is_symlink() {
|
||||
return true;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
// Junctions and mount points are reparse points that `file_type` may report as directories.
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
|
||||
meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected entry itself may be a link (its name is all that gets ignored);
|
||||
/// an ancestor may not: the rule would describe a path Git does not see.
|
||||
fn no_symlinked_ancestors(path: &Path) -> IdeResult<()> {
|
||||
for part in path.ancestors().skip(1) {
|
||||
match fs::symlink_metadata(part) {
|
||||
Ok(m) if m.file_type().is_symlink() => {
|
||||
return Err(IdeError::invalid(format!("Refusing symlink path: {}", part.display())));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse symlinked ancestors too: writing through them could affect another repository.
|
||||
fn no_symlinks(path: &Path) -> IdeResult<()> {
|
||||
for part in path.ancestors() {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Identities of index files last written by status, shared with filesystem watchers.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct Identity {
|
||||
len: u64,
|
||||
modified: SystemTime,
|
||||
}
|
||||
|
||||
fn identity(path: &Path) -> Option<Identity> {
|
||||
let metadata = path.metadata().ok()?;
|
||||
Some(Identity { len: metadata.len(), modified: metadata.modified().ok()? })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IndexWrites(HashMap<PathBuf, Identity>);
|
||||
|
||||
pub(crate) fn lock() -> MutexGuard<'static, IndexWrites> {
|
||||
static WRITES: OnceLock<Mutex<IndexWrites>> = OnceLock::new();
|
||||
WRITES.get_or_init(Mutex::default).lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
impl IndexWrites {
|
||||
pub(crate) fn record(&mut self, path: &Path) {
|
||||
let Ok(path) = path.canonicalize() else { return };
|
||||
// Bound memory even when many repositories are opened over the process lifetime.
|
||||
if self.0.len() >= 256 && !self.0.contains_key(&path) {
|
||||
self.0.clear();
|
||||
}
|
||||
if let Some(identity) = identity(&path) {
|
||||
self.0.insert(path, identity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the current index still matches our last status write-back. Retain a
|
||||
/// match for duplicate watcher notifications; invalidate it on an external write.
|
||||
pub fn is_own_index_write(path: &Path) -> bool {
|
||||
let mut writes = lock();
|
||||
let Ok(path) = path.canonicalize() else { return false };
|
||||
if let Some(current) = identity(&path)
|
||||
&& writes.0.get(&path) == Some(¤t)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
writes.0.remove(&path);
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn identities_are_scoped_to_paths_and_invalidated_by_metadata_changes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let first = tmp.path().join("index");
|
||||
let second = tmp.path().join("other-index");
|
||||
std::fs::write(&first, "first").unwrap();
|
||||
std::fs::write(&second, "first").unwrap();
|
||||
lock().record(&first);
|
||||
assert!(is_own_index_write(&first));
|
||||
assert!(!is_own_index_write(&second));
|
||||
let file = std::fs::File::options().write(true).open(&first).unwrap();
|
||||
file.set_modified(SystemTime::UNIX_EPOCH).unwrap();
|
||||
assert!(!is_own_index_write(&first));
|
||||
lock().record(&first);
|
||||
file.set_len(10).unwrap();
|
||||
assert!(!is_own_index_write(&first));
|
||||
std::fs::remove_file(&first).unwrap();
|
||||
assert!(!is_own_index_write(&first));
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,19 @@ pub enum PushTags {
|
||||
CurrentBranch,
|
||||
}
|
||||
|
||||
/// Options of [`Repo::push_branch_to`]: which commits to push and where to.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PushBranchOptions<'a> {
|
||||
/// Push only up to this commit of the branch (`None`: the whole branch).
|
||||
pub revision: Option<&'a str>,
|
||||
/// Remote branch name (`None` keeps the upstream's / the local name).
|
||||
pub target: Option<&'a str>,
|
||||
/// Remote to push to (`None` keeps the upstream's / the default remote).
|
||||
pub remote: Option<&'a str>,
|
||||
/// `git push --force-with-lease`.
|
||||
pub force_with_lease: bool,
|
||||
}
|
||||
|
||||
/// What an interactive rebase does with one commit.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -443,6 +456,7 @@ mod cli;
|
||||
mod diff;
|
||||
mod history;
|
||||
mod ignore;
|
||||
mod index_writes;
|
||||
mod manage;
|
||||
mod ops;
|
||||
mod patch;
|
||||
@@ -452,10 +466,14 @@ mod repo;
|
||||
mod roots;
|
||||
pub mod shelf;
|
||||
mod status;
|
||||
pub use index_writes::is_own_index_write;
|
||||
mod text_encoding;
|
||||
mod write;
|
||||
|
||||
pub use cli::{detected_git_executable, git_version, set_askpass_env, set_git_executable};
|
||||
pub use cli::{
|
||||
GitCommandObserver, detected_git_executable, git_version, set_askpass_env, set_git_command_observer,
|
||||
set_git_executable,
|
||||
};
|
||||
pub use diff::build_partial_patch;
|
||||
pub use ignore::{IgnoreDestination, add_to_ignore};
|
||||
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
|
||||
@@ -573,13 +591,16 @@ impl Repo {
|
||||
}
|
||||
/// One entry per line of the current text (`current_text`, or the file on disk).
|
||||
/// Lines not yet committed carry an all-zero commit id and author "Not Committed Yet".
|
||||
/// `revision` is the history to blame against (default `HEAD`); the merge view
|
||||
/// blames each side pane on the branch it belongs to (e.g. `MERGE_HEAD`).
|
||||
pub fn blame(
|
||||
&self,
|
||||
path: &Path,
|
||||
current_text: Option<&str>,
|
||||
revision: Option<&str>,
|
||||
encoding: &'static Encoding,
|
||||
) -> IdeResult<Vec<BlameLine>> {
|
||||
write::blame(self, path, current_text, encoding)
|
||||
write::blame(self, path, current_text, revision, encoding)
|
||||
}
|
||||
/// Commits newest-first in topological order (children before parents).
|
||||
///
|
||||
@@ -776,20 +797,25 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
write::push_branch(self, branch, revision, None, force_with_lease, cancel, on_output)
|
||||
write::push_branch(
|
||||
self,
|
||||
branch,
|
||||
PushBranchOptions { revision, force_with_lease, ..Default::default() },
|
||||
cancel,
|
||||
on_output,
|
||||
)
|
||||
}
|
||||
/// [`Repo::push_branch`] to remote branch `target` instead of the upstream's name (the
|
||||
/// Push dialog's editable target).
|
||||
/// [`Repo::push_branch`] to remote branch `target` (None keeps the upstream's name)
|
||||
/// and/or remote `remote` (None keeps the upstream's remote). The Push dialog's
|
||||
/// editable target and remote picker.
|
||||
pub fn push_branch_to(
|
||||
&self,
|
||||
branch: &str,
|
||||
revision: Option<&str>,
|
||||
target: &str,
|
||||
force_with_lease: bool,
|
||||
options: PushBranchOptions<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
write::push_branch(self, branch, revision, Some(target), force_with_lease, cancel, on_output)
|
||||
write::push_branch(self, branch, options, cancel, on_output)
|
||||
}
|
||||
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
|
||||
/// Update). Fails when the branch has diverged.
|
||||
|
||||
@@ -20,6 +20,21 @@ pub struct Repos {
|
||||
}
|
||||
|
||||
impl Repos {
|
||||
/// Discovers repositories in independent project folders of a workspace.
|
||||
pub fn discover_roots(roots: &[PathBuf], skip: &dyn Fn(&Path) -> bool) -> IdeResult<Self> {
|
||||
let mut repos = Vec::new();
|
||||
for root in roots {
|
||||
for repo in Self::discover(root, skip)?.repos {
|
||||
if !repos.iter().any(|r: &Arc<Repo>| r.root() == repo.root()) {
|
||||
repos.push(repo);
|
||||
}
|
||||
}
|
||||
}
|
||||
repos.sort_by(|a, b| a.root().cmp(b.root()));
|
||||
let primary = (!repos.is_empty()).then_some(0);
|
||||
Ok(Self { repos, primary })
|
||||
}
|
||||
|
||||
/// The repository containing `project_root` and every repository whose worktree
|
||||
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
|
||||
/// folders `skip` rejects are not searched).
|
||||
|
||||
@@ -90,19 +90,25 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Persist refreshed stat info so the next status is cheaper (like `git status` does).
|
||||
// Only when something changed: `write_changes` writes even an empty change set, and
|
||||
// the rewritten `.git/index` comes back as a VCS change that triggers the next status.
|
||||
// Serialize write-back and identity capture with watcher queries.
|
||||
if let Some(mut outcome) = iter.into_outcome()
|
||||
&& outcome.has_changes()
|
||||
&& let Some(Err(e)) = outcome.write_changes()
|
||||
{
|
||||
tracing::debug!("could not write refreshed index: {e}");
|
||||
let mut writes = crate::index_writes::lock();
|
||||
match outcome.write_changes() {
|
||||
Some(Ok(_)) => writes.record(&repo.index_path()),
|
||||
Some(Err(e)) => tracing::debug!("could not write refreshed index: {e}"),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(map
|
||||
.into_iter()
|
||||
.filter(|(_, e)| e.staged.is_some() || e.unstaged.is_some())
|
||||
// Ignored names mean "the IDE treats these as nonexistent": hide their tracked
|
||||
// changes too, not just untracked hits above. Conflicts stay visible so merges
|
||||
// cannot stall on a file the user cannot see.
|
||||
.filter(|(rel, _)| conflicts.contains(rel) || !ignored.is_ignored_path(rel))
|
||||
.map(|(rel, mut e)| {
|
||||
if conflicts.contains(&rel) {
|
||||
e.staged = None;
|
||||
|
||||
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача