дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
46
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
31e9084cb5 | ||
|
|
ee6786d573 | ||
|
|
5804fcad16 | ||
|
|
7a0c9354fa | ||
|
|
7e7da950fc | ||
|
|
9298be8798 | ||
|
|
715ebf19e2 | ||
|
|
438ab158ad | ||
|
|
7965d171f0 | ||
|
|
c004e50751 | ||
|
|
daac8e80b0 | ||
|
|
39f6162c12 | ||
|
|
809bc1cc2f | ||
|
|
4beca55a54 | ||
|
|
fc5a7d8c91 | ||
|
|
61b12269a1 | ||
|
|
39dc5db079 | ||
|
|
2d34bc956d | ||
|
|
99fafffaac | ||
|
|
66ecf4c967 | ||
|
|
88ecaf9ccd | ||
|
|
d018771a8d | ||
|
|
0eca4366d0 | ||
|
|
c4b9912036 | ||
|
|
8259a81335 | ||
|
|
1b3f9ac6f7 | ||
|
|
6c813d501e | ||
|
|
c3e8f20f53 | ||
|
|
0f0458b966 | ||
|
|
34d830c247 | ||
|
|
ab9bb7c266 | ||
|
|
fa36733f80 | ||
|
|
aa3323ddc5 | ||
|
|
b5974ab3ac | ||
|
|
ebac061a1f | ||
|
|
d4db7bb290 | ||
|
|
b2253a8bc8 | ||
|
|
d0c3b9ba34 | ||
|
|
eae363908d | ||
|
|
410761e0f7 | ||
|
|
ebbda4bb1f | ||
|
|
64398dde3a | ||
|
|
d36cf83f78 | ||
|
|
b1171ecd23 | ||
|
|
7a6b1601d5 | ||
|
|
4dd51a1101 |
No files matched your search
@@ -166,6 +166,28 @@ jobs:
|
||||
xcrun stapler staple "$dmg"
|
||||
gh release upload "$TAG" "$dmg" --clobber
|
||||
done
|
||||
# Portable Windows builds (#1857): on Windows Tauri embeds the
|
||||
# frontend in the exe and WebView2 is a system component, so zipping
|
||||
# the raw exe gives an unpack-and-run alternative to the installers.
|
||||
- name: Portable zip
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
$target = "${{ matrix.target }}"
|
||||
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
|
||||
$version = $env:TAG -replace '^v', ''
|
||||
$asset = "OpenIDEA_${version}_windows_${arch}_portable.zip"
|
||||
$dir = "target/$target/release"
|
||||
$files = @("$dir/openidea.exe")
|
||||
if (Test-Path "$dir/WebView2Loader.dll") {
|
||||
$files += "$dir/WebView2Loader.dll"
|
||||
}
|
||||
Compress-Archive -Path $files -DestinationPath $asset -Force
|
||||
$hash = (Get-FileHash $asset -Algorithm SHA256).Hash.ToLower()
|
||||
"$hash $asset" | Out-File -Encoding ascii "$asset.sha256"
|
||||
gh release upload $env:TAG $asset "$asset.sha256" --clobber
|
||||
|
||||
# The remote development server, per host platform it can run on. The desktop
|
||||
# app downloads the one for the host (ide-tools `server`) and installs it over SSH.
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
name: Website
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "website/**"
|
||||
- ".github/workflows/website.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "website/**"
|
||||
- ".github/workflows/website.yml"
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
# Releases published by GITHUB_TOKEN do not trigger another release workflow.
|
||||
workflow_run:
|
||||
workflows: [Release]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: website-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pages: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: website
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
package_json_file: website/package.json
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: website/pnpm-lock.yaml
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm test
|
||||
- name: Refresh official release downloads
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: pnpm release:refresh
|
||||
# A PR must be testable before Pages has been enabled in repository settings.
|
||||
- id: pages
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: actions/configure-pages@v5
|
||||
- name: Build static homepage
|
||||
env:
|
||||
BASE_PATH: ${{ github.event_name == 'pull_request' && format('/{0}', github.event.repository.name) || steps.pages.outputs.base_path }}
|
||||
VITE_SITE_URL: ${{ steps.pages.outputs.base_url }}
|
||||
run: pnpm build && pnpm typecheck && pnpm check:static
|
||||
# Also verify a custom-domain / user-site root with no repository prefix.
|
||||
- name: Check root deployment
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BASE_PATH: /
|
||||
run: pnpm build && pnpm check:static
|
||||
- uses: actions/upload-pages-artifact@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
path: website/dist/client
|
||||
|
||||
deploy:
|
||||
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pages: write
|
||||
id-token: write
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
Створено
@@ -4216,6 +4216,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"portable-pty",
|
||||
|
||||
+4
-1
@@ -25,7 +25,9 @@ OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool window
|
||||
its search-everything habits — to a native app with a Rust core.
|
||||
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
for 60+ languages. Builds for macOS, Windows and Linux. On Windows, if you'd
|
||||
rather skip the installer, each release also ships a portable zip — unpack it
|
||||
and run `openidea.exe`.
|
||||
|
||||
## Benchmark
|
||||
|
||||
@@ -76,5 +78,6 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
Database tool window notes, including Oracle Instant Client setup, are in
|
||||
[`docs/databases.md`](docs/databases.md).
|
||||
Java language server choices and their capabilities are in [`docs/java.md`](docs/java.md).
|
||||
|
||||
<sub>Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</sub>
|
||||
@@ -54,6 +54,9 @@ const SESSION_STATE: [&str; 5] =
|
||||
pub(crate) const RETRY_UPDATE: &str = "openidea_retry";
|
||||
/// A native agent's own update: the usage limits of its account (see [`AgentLimit`]).
|
||||
pub(crate) const LIMITS_UPDATE: &str = "openidea_limits";
|
||||
/// A native agent's own update: the background tasks its session runs
|
||||
/// (see [`TaskState::background_tasks`]).
|
||||
pub(crate) const BACKGROUND_TASKS_UPDATE: &str = "openidea_background_tasks";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -209,6 +212,10 @@ struct TaskState {
|
||||
pending_rollback: u32,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
/// Background tasks the agent reported as running (`run_in_background` commands and
|
||||
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
|
||||
/// waits for the last one. A (re)started process runs nothing yet.
|
||||
background_tasks: Vec<Value>,
|
||||
}
|
||||
|
||||
/// A running agent and its session.
|
||||
@@ -244,6 +251,9 @@ struct Task {
|
||||
turn_started: AtomicBool,
|
||||
/// Turns sent so far: an idle release scheduled before the latest one is void.
|
||||
turns: AtomicU64,
|
||||
/// Bumped when the agent's last background task finishes: an idle release scheduled
|
||||
/// before that is void, the usual delay starts over from the report.
|
||||
idle_epoch: AtomicU64,
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
@@ -302,6 +312,7 @@ impl AgentManager {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
}
|
||||
f.task.retry = None;
|
||||
f.task.background.clear();
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
@@ -470,6 +481,7 @@ impl AgentManager {
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
@@ -664,6 +676,7 @@ impl AgentManager {
|
||||
queue: Vec::new(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
..s.task.clone()
|
||||
};
|
||||
TaskFile {
|
||||
@@ -802,6 +815,21 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops background task `background` of task `id`.
|
||||
pub async fn stop_background(&self, id: &str, background: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let live = task.live.lock().clone().ok_or_else(|| IdeError::invalid("the agent is not running"))?;
|
||||
if !live.capabilities.background_tasks {
|
||||
return Err(IdeError::invalid("this agent can't stop a background task"));
|
||||
}
|
||||
let _: Value = live
|
||||
.peer
|
||||
.request("_openidea/stop_task", json!({ "sessionId": live.session, "taskId": background }), None)
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(task.describe(error)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Answers permission request `permission` with option `option` (`None` cancels it).
|
||||
pub fn respond(&self, id: &str, permission: u32, option: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -914,6 +942,7 @@ impl Task {
|
||||
before: Arc::new(file.before),
|
||||
pending_rollback: file.pending_rollback,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
connecting: tokio::sync::Mutex::new(()),
|
||||
@@ -924,6 +953,7 @@ impl Task {
|
||||
cancel_pending: AtomicBool::new(false),
|
||||
turn_started: AtomicBool::new(false),
|
||||
turns: AtomicU64::new(0),
|
||||
idle_epoch: AtomicU64::new(0),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
flush_scheduled: AtomicBool::new(false),
|
||||
@@ -960,6 +990,39 @@ impl Task {
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
/// Keeps the agent's background tasks that outlive its turn. Returns whether the last
|
||||
/// one just finished, so the idle release starts over from this report.
|
||||
fn set_background_tasks(&self, tasks: Vec<Value>) -> bool {
|
||||
let (emptied, shown) = {
|
||||
let mut state = self.state.lock();
|
||||
if state.background_tasks == tasks {
|
||||
return false;
|
||||
}
|
||||
let emptied = !state.background_tasks.is_empty() && tasks.is_empty();
|
||||
let background = shown_background(&tasks, &state.task.background);
|
||||
let shown = background != *state.task.background;
|
||||
*state.task.background = background;
|
||||
state.background_tasks = tasks;
|
||||
if emptied {
|
||||
// Void a release scheduled while the tasks still ran: it would stop the
|
||||
// agent sooner than the usual delay after this one.
|
||||
self.idle_epoch.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
(emptied, shown)
|
||||
};
|
||||
if shown {
|
||||
self.emit_task();
|
||||
}
|
||||
emptied
|
||||
}
|
||||
|
||||
fn clear_shown_background(&self) {
|
||||
let cleared = !std::mem::take(&mut self.state.lock().task.background).is_empty();
|
||||
if cleared {
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
@@ -1078,19 +1141,32 @@ impl Task {
|
||||
/// Stops the agent's process once the task has stayed idle for [`IDLE_RELEASE`], so
|
||||
/// finished tasks don't keep an agent (and what it started) running. Only an agent that
|
||||
/// reloads its session: the next message starts it again with the conversation intact.
|
||||
/// A turn's background tasks outlive it: the release waits for the last one, and the
|
||||
/// delay runs again once the agent reports it done.
|
||||
fn release_when_idle(self: &Arc<Self>) {
|
||||
let turn = self.turns.load(Ordering::Acquire);
|
||||
let epoch = self.idle_epoch.load(Ordering::Acquire);
|
||||
let delay = Duration::from_millis(self.shared.idle_release_ms.load(Ordering::Relaxed));
|
||||
let task = Arc::downgrade(self);
|
||||
self.shared.runtime.spawn(async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
let Some(task) = task.upgrade() else { return };
|
||||
if task.turns.load(Ordering::Acquire) != turn
|
||||
|| task.idle_epoch.load(Ordering::Acquire) != epoch
|
||||
|| task.state.lock().busy
|
||||
|| !task.permissions.lock().is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Stopping now would orphan what the agent still runs in the background: its
|
||||
// result would never reach the conversation. Wait for the last task; when it
|
||||
// is done, its report voids this schedule and starts the delay over.
|
||||
let waiting = !task.state.lock().background_tasks.is_empty();
|
||||
if waiting && task.live.lock().as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) {
|
||||
tracing::debug!("agent task {}: idle, waiting for its background tasks", task.id);
|
||||
task.release_when_idle();
|
||||
return;
|
||||
}
|
||||
let live = {
|
||||
let mut live = task.live.lock();
|
||||
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
|
||||
@@ -1098,6 +1174,7 @@ impl Task {
|
||||
if let Some(live) = live {
|
||||
tracing::debug!("agent task {}: idle, stopping the agent until the next message", task.id);
|
||||
live.peer.kill();
|
||||
task.clear_shown_background();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1116,6 +1193,7 @@ impl Task {
|
||||
if !gone && let Some(live) = self.live.lock().take() {
|
||||
live.peer.kill();
|
||||
}
|
||||
self.clear_shown_background();
|
||||
match failure.limit {
|
||||
Some(resets) => {
|
||||
self.state.lock().task.resets_ms = resets;
|
||||
@@ -1356,6 +1434,9 @@ impl Task {
|
||||
s.task.config = options;
|
||||
s.task.capabilities = capabilities;
|
||||
s.session_id = Some(session_id.clone());
|
||||
// The (re)started process runs nothing yet: whatever it reports next is all of it.
|
||||
s.background_tasks = Vec::new();
|
||||
s.task.background.clear();
|
||||
}
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
@@ -1448,6 +1529,16 @@ impl Task {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == BACKGROUND_TASKS_UPDATE {
|
||||
if !self.replaying.load(Ordering::Acquire) {
|
||||
let tasks = update.get("tasks").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
// The last one finished while the agent is up: the usual delay starts over.
|
||||
if self.set_background_tasks(tasks) {
|
||||
self.release_when_idle();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
@@ -1556,17 +1647,38 @@ impl Task {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let questions: Vec<AgentQuestion> = params
|
||||
.pointer("/toolCall/_meta/questions")
|
||||
.and_then(|questions| serde_json::from_value(questions.clone()).ok())
|
||||
.unwrap_or_default();
|
||||
let asked: Vec<String> = questions.iter().map(|question| question.question.clone()).collect();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let entry = self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), chosen: None });
|
||||
let entry =
|
||||
self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), questions, chosen: None });
|
||||
self.permissions.lock().insert(id, tx);
|
||||
self.set_status(AgentStatus::NeedsInput, None);
|
||||
self.approve_pending();
|
||||
|
||||
let answer = rx.recv().ok().flatten();
|
||||
let name = answer
|
||||
.as_ref()
|
||||
.and_then(|a| options.iter().find(|o| &o.id == a))
|
||||
.map_or_else(|| "Cancelled".to_owned(), |o| o.name.clone());
|
||||
let answers = answer
|
||||
.as_deref()
|
||||
.filter(|_| !asked.is_empty())
|
||||
.and_then(|reply| serde_json::from_str::<serde_json::Map<String, Value>>(reply).ok());
|
||||
let name = match answers {
|
||||
Some(answers) => asked
|
||||
.iter()
|
||||
.filter_map(|question| answers.get(question))
|
||||
.map(|items| match items {
|
||||
Value::Array(items) => items.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", "),
|
||||
item => item.as_str().unwrap_or_default().to_owned(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("; "),
|
||||
None => answer
|
||||
.as_ref()
|
||||
.and_then(|reply| options.iter().find(|option| &option.id == reply))
|
||||
.map_or_else(|| "Cancelled".to_owned(), |option| option.name.clone()),
|
||||
};
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
|
||||
@@ -1622,6 +1734,7 @@ impl Task {
|
||||
self.cancel_permissions();
|
||||
let live = self.live.lock().take()?;
|
||||
live.peer.kill();
|
||||
self.clear_shown_background();
|
||||
Some(live.peer)
|
||||
}
|
||||
}
|
||||
@@ -1735,6 +1848,19 @@ fn client_info() -> Value {
|
||||
}
|
||||
|
||||
/// What the agent said it can do, and whether it takes embedded files.
|
||||
fn shown_background(tasks: &[Value], known: &[AgentBackgroundTask]) -> Vec<AgentBackgroundTask> {
|
||||
let now = now_ms();
|
||||
tasks
|
||||
.iter()
|
||||
.filter_map(|task| {
|
||||
let id = task.get("task_id")?.as_str()?.to_owned();
|
||||
let started_ms = known.iter().find(|seen| seen.id == id).map_or(now, |seen| seen.started_ms);
|
||||
let text = |key: &str| task.get(key).and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
Some(AgentBackgroundTask { id, kind: text("task_type"), description: text("description"), started_ms })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
let meta = |p: &str| init.meta(p).and_then(Value::as_bool) == Some(true);
|
||||
let capabilities = AgentCapabilities {
|
||||
@@ -1742,6 +1868,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
fork: init.session("fork"),
|
||||
rollback: meta("/openidea/rollback"),
|
||||
steer: meta("/openidea/steer"),
|
||||
background_tasks: meta("/openidea/backgroundTasks"),
|
||||
};
|
||||
(capabilities, init.prompt("embeddedContext"))
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ pub struct AgentCapabilities {
|
||||
pub rollback: bool,
|
||||
/// A message can join the running turn instead of waiting for it.
|
||||
pub steer: bool,
|
||||
/// It reports its background tasks and stops them one by one.
|
||||
pub background_tasks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -89,6 +91,22 @@ pub struct AgentTask {
|
||||
/// by its next output or any status change.
|
||||
#[serde(default)]
|
||||
pub retry: Option<AgentRetry>,
|
||||
/// What the agent runs in the background (shells, subagents, monitors), oldest first.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub background: Box<Vec<AgentBackgroundTask>>,
|
||||
}
|
||||
|
||||
/// A task the agent runs in the background while the conversation goes on.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentBackgroundTask {
|
||||
pub id: String,
|
||||
/// What it is, as the agent names it (`local_bash`, `local_agent`, `monitor`…).
|
||||
pub kind: String,
|
||||
pub description: String,
|
||||
/// When the client first saw it (ms since the epoch).
|
||||
pub started_ms: f64,
|
||||
}
|
||||
|
||||
/// An API request the agent is about to retry.
|
||||
@@ -260,6 +278,28 @@ pub struct AgentPermissionOption {
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// A question the agent asks with `AskUserQuestion`, answered by picking options or typing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQuestion {
|
||||
#[serde(default)]
|
||||
pub header: String,
|
||||
pub question: String,
|
||||
#[serde(default)]
|
||||
pub multi_select: bool,
|
||||
pub options: Vec<AgentQuestionOption>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQuestionOption {
|
||||
pub label: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub preview: Option<String>,
|
||||
}
|
||||
|
||||
/// One item of a task's conversation.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
@@ -332,6 +372,10 @@ pub enum AgentEntry {
|
||||
id: u32,
|
||||
title: String,
|
||||
options: Vec<AgentPermissionOption>,
|
||||
/// Set when the request asks `AskUserQuestion`'s questions; answered with a JSON object
|
||||
/// of question to answer instead of an option.
|
||||
#[serde(default)]
|
||||
questions: Vec<AgentQuestion>,
|
||||
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
|
||||
chosen: Option<String>,
|
||||
},
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Shim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "embeddedContext": true },
|
||||
"sessionCapabilities": { "fork": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
|
||||
"authMethods": [],
|
||||
@@ -396,6 +396,13 @@ impl Shim {
|
||||
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "stop_task", "task_id": task }))).map_err(internal)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/rollback" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let turns = params.get("turns").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
@@ -611,7 +618,8 @@ impl Session {
|
||||
session.on_exit(&reader_proc);
|
||||
}
|
||||
});
|
||||
let init = proc.control(json!({ "subtype": "initialize" })).await?;
|
||||
// Stop ends the turn only: the client stops background tasks one by one.
|
||||
let init = proc.control(json!({ "subtype": "initialize", "perTaskStopAffordance": true })).await?;
|
||||
let applied = proc.control(json!({ "subtype": "get_settings" })).await.unwrap_or_default();
|
||||
let chosen = {
|
||||
let mut st = self.st.lock();
|
||||
@@ -1109,38 +1117,46 @@ fn permission_result(
|
||||
}
|
||||
}
|
||||
|
||||
/// `AskUserQuestion`: each question as a permission request whose options are its
|
||||
/// answers; `None` when one is not answered.
|
||||
/// `AskUserQuestion`: one permission request carrying all its questions, answered with a
|
||||
/// JSON object of question to the chosen labels and typed text; `None` when skipped.
|
||||
async fn ask_questions<F, Fut>(input: &Value, call: &Value, ask: F) -> Option<Value>
|
||||
where
|
||||
F: Fn(Value, Value) -> Fut,
|
||||
Fut: std::future::Future<Output = Option<String>>,
|
||||
{
|
||||
let mut answers = serde_json::Map::new();
|
||||
for q in input.get("questions").and_then(Value::as_array).into_iter().flatten() {
|
||||
let question = q.get("question").and_then(Value::as_str).unwrap_or_default();
|
||||
let labels: Vec<&str> = q
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|o| o.get("label")?.as_str())
|
||||
.collect();
|
||||
let mut options: Vec<Value> = labels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| json!({ "optionId": format!("answer-{i}"), "name": l, "kind": "allow_once" }))
|
||||
.collect();
|
||||
options.push(json!({ "optionId": "reject", "name": "Skip", "kind": "reject_once" }));
|
||||
let mut call = call.clone();
|
||||
call["title"] = json!(question);
|
||||
let chosen = ask(call, Value::Array(options)).await?;
|
||||
let i: usize = chosen.strip_prefix("answer-")?.parse().ok()?;
|
||||
answers.insert(question.to_owned(), json!(labels.get(i)?));
|
||||
}
|
||||
let questions = input.get("questions")?;
|
||||
let mut call = call.clone();
|
||||
call["title"] = questions.pointer("/0/question").cloned().unwrap_or_else(|| json!("Claude has a question"));
|
||||
call["_meta"] = json!({ "questions": questions });
|
||||
let options = json!([{ "optionId": "reject", "name": "Skip", "kind": "reject_once" }]);
|
||||
let chosen = ask(call, options).await?;
|
||||
let chosen: serde_json::Map<String, Value> = serde_json::from_str(&chosen).ok()?;
|
||||
let answers = questions
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let question = entry.get("question")?.as_str()?;
|
||||
let items: Vec<&str> = chosen.get(question)?.as_array()?.iter().filter_map(Value::as_str).collect();
|
||||
let multi = entry.get("multiSelect").and_then(Value::as_bool) == Some(true);
|
||||
let answer = if multi { join_answers(&items) } else { items.first()?.to_string() };
|
||||
Some((question.to_owned(), json!(answer)))
|
||||
})
|
||||
.collect();
|
||||
Some(Value::Object(answers))
|
||||
}
|
||||
|
||||
/// A multi-select answer as Claude Code's own question UI writes it: comma-joined, with an
|
||||
/// item that holds the separator or a quote JSON-quoted so it reads back as one item.
|
||||
fn join_answers(items: &[&str]) -> String {
|
||||
items
|
||||
.iter()
|
||||
.map(
|
||||
|item| if item.contains(", ") || item.contains('"') { json!(item).to_string() } else { (*item).to_owned() },
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// Whether `result` ends `turn`: it answers the turn's last message, or (stopped) any of
|
||||
/// its messages, or names none (the CLI's own error before the turn began).
|
||||
fn belongs(turn: &Turn, result: &Value) -> bool {
|
||||
|
||||
@@ -976,6 +976,19 @@ fn api_retries_are_announced() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_tasks_are_announced_wholesale() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let tasks = json!([{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"}]);
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "background_tasks_changed", "tasks": tasks}));
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].session, "s");
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks}));
|
||||
// The list is replaced with every report: an empty one says every task is done.
|
||||
let out = t.on_message(&json!({"type": "system", "subtype": "background_tasks_changed", "tasks": []}));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_not_sent_twice() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
@@ -1093,3 +1106,67 @@ fn tool_calls_plans_and_subagents() {
|
||||
assert_eq!(finished[1].update["content"][0]["text"], "It is x");
|
||||
assert_eq!(finished[1].update["senderSessionId"], "ag");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn questions_go_out_as_one_request() {
|
||||
let questions = json!([
|
||||
{"header": "Files", "question": "Where should they live?", "multiSelect": false,
|
||||
"options": [{"label": "Local", "description": "Kept out of git"}, {"label": "Committed", "description": "In the repo"}]},
|
||||
{"header": "Checks", "question": "Which checks?", "multiSelect": true,
|
||||
"options": [{"label": "Lint", "description": ""}, {"label": "Tests", "description": ""}]},
|
||||
]);
|
||||
let input = json!({ "questions": questions });
|
||||
let asked = std::sync::Mutex::new(Vec::new());
|
||||
let reply = json!({"Where should they live?": ["Local"], "Which checks?": ["Lint", "Tests"]}).to_string();
|
||||
let answers = json!({"Where should they live?": "Local", "Which checks?": "Lint, Tests"});
|
||||
let result = ask_questions(&input, &json!({"toolCallId": "t"}), |call, options| {
|
||||
asked.lock().unwrap().push((call, options));
|
||||
let reply = reply.clone();
|
||||
async move { Some(reply) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result, Some(answers));
|
||||
let asked = asked.into_inner().unwrap();
|
||||
assert_eq!(asked.len(), 1);
|
||||
let (call, options) = &asked[0];
|
||||
assert_eq!(call["title"], "Where should they live?");
|
||||
assert_eq!(call["_meta"]["questions"], questions);
|
||||
assert_eq!(options[0]["optionId"], "reject");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answers_keep_claude_codes_format_with_other_text() {
|
||||
let input = json!({"questions": [
|
||||
{"question": "Which cache?", "multiSelect": false, "options": [{"label": "Redis"}, {"label": "None"}]},
|
||||
{"question": "Which checks?", "multiSelect": true, "options": [{"label": "Lint"}, {"label": "Tests"}]},
|
||||
{"question": "Which stores?", "multiSelect": true, "options": [{"label": "Disk"}, {"label": "S3"}]},
|
||||
]});
|
||||
let reply = json!({
|
||||
"Which cache?": ["Memcached, for now"],
|
||||
"Which checks?": ["Lint", "Tests"],
|
||||
"Which stores?": ["Disk", "Redis, not Memcached", "a \"cold\" tier"],
|
||||
})
|
||||
.to_string();
|
||||
let result = ask_questions(&input, &json!({}), |_, _| {
|
||||
let reply = reply.clone();
|
||||
async move { Some(reply) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
result,
|
||||
Some(json!({
|
||||
"Which cache?": "Memcached, for now",
|
||||
"Which checks?": "Lint, Tests",
|
||||
"Which stores?": "Disk, \"Redis, not Memcached\", \"a \\\"cold\\\" tier\"",
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skipped_questions_have_no_answers() {
|
||||
let input = json!({"questions": [{"question": "Which?", "options": [{"label": "A"}]}]});
|
||||
let skipped = ask_questions(&input, &json!({}), |_, _| async { Some("reject".to_owned()) }).await;
|
||||
assert_eq!(skipped, None);
|
||||
let cancelled = ask_questions(&input, &json!({}), |_, _| async { None }).await;
|
||||
assert_eq!(cancelled, None);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Agent tool use that launched them: their messages carry it as `parent_tool_use_id`.
|
||||
|
||||
use super::tools;
|
||||
use crate::{LIMITS_UPDATE, RETRY_UPDATE};
|
||||
use crate::{BACKGROUND_TASKS_UPDATE, LIMITS_UPDATE, RETRY_UPDATE};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
@@ -458,6 +458,15 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
let Some(tasks) = msg.get("tasks").and_then(Value::as_array).cloned() else { return Vec::new() };
|
||||
vec![Update {
|
||||
session: self.root.clone(),
|
||||
update: json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": tasks }),
|
||||
}]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ impl Handler for FakeAgent {
|
||||
self.calls.lock().push("subagents".into());
|
||||
}
|
||||
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": !self.no_load,
|
||||
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true}}}}))
|
||||
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true, "backgroundTasks": true}}}}))
|
||||
}
|
||||
"session/new" => {
|
||||
let mut options = vec![json!({"id": "model", "category": "model", "type": "select",
|
||||
@@ -106,6 +106,10 @@ impl Handler for FakeAgent {
|
||||
"configOptions": options}))
|
||||
}
|
||||
"session/fork" => Ok(json!({"sessionId": "s2"})),
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/rollback" | "_openidea/steer" => {
|
||||
let detail = params.get("turns").cloned().unwrap_or_else(|| params["prompt"][0]["text"].clone());
|
||||
self.calls.lock().push(format!("{method} {detail}"));
|
||||
@@ -125,6 +129,16 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "second turn");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "background" {
|
||||
// A command that outlives the turn, as the agent reports it.
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE,
|
||||
"tasks": [{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"}]}),
|
||||
);
|
||||
self.say(&session, "running it in the background");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -142,6 +156,24 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "ok");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "ask" {
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session,
|
||||
"toolCall": {"toolCallId": "q1", "title": "AskUserQuestion", "_meta": {"questions": [
|
||||
{"question": "Which layout?", "options": [{"label": "List"}, {"label": "Grid"}]},
|
||||
{"question": "Which checks?", "multiSelect": true,
|
||||
"options": [{"label": "Disk"}, {"label": "GPU temps"}]}]}},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
let chosen = answer.pointer("/outcome/optionId").and_then(Value::as_str).unwrap_or("none");
|
||||
self.say(&session, &format!("answered {chosen}"));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
@@ -595,6 +627,44 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn answered_questions_close_the_question_with_every_picked_label() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("ask"),
|
||||
provider: "codex".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let question = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let reply = json!({"Which layout?": ["List"], "Which checks?": ["Disk", "GPU temps"]}).to_string();
|
||||
mgr.respond(&task.id, question, Some(reply)).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "List; Disk, GPU temps")),
|
||||
"{entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1146,6 +1216,114 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// A turn's background tasks outlive it: an idle agent stops only once its last one is
|
||||
/// done, and the usual delay runs from that report.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_idle_agent_waits_for_its_background_tasks_before_it_stops() {
|
||||
let live =
|
||||
|mgr: &AgentManager, id: &str| mgr.task(id).unwrap().live.lock().as_ref().is_some_and(|l| !l.peer.is_closed());
|
||||
let new = || NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("background"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
};
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.set_idle_release(Duration::from_millis(200));
|
||||
let task = mgr.create(new()).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
// The task runs long past the idle delay: the agent stays up for it.
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(live(&mgr, &task.id));
|
||||
// It is done: the delay starts over from this report, then the agent stops.
|
||||
agent.update("s1", json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(live(&mgr, &task.id), "the delay runs from when the last task is done");
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(!live(&mgr, &task.id));
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready, "not an error");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_task_shows_what_runs_in_the_background() {
|
||||
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("background"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let shown = || mgr.task(&task.id).unwrap().state.lock().task.background.clone();
|
||||
let first = shown();
|
||||
assert_eq!(first.len(), 1);
|
||||
assert_eq!(
|
||||
(first[0].id.as_str(), first[0].kind.as_str(), first[0].description.as_str()),
|
||||
("bsh1", "local_bash", "sleep 900")
|
||||
);
|
||||
|
||||
agent.update(
|
||||
"s1",
|
||||
json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": [
|
||||
{"task_id": "bsh1", "task_type": "local_bash", "description": "sleep 900"},
|
||||
{"task_id": "mon1", "task_type": "monitor", "description": "Watch the deploy"},
|
||||
]}),
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while shown().len() < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(shown()[0].started_ms, first[0].started_ms, "a task keeps when it was first seen");
|
||||
|
||||
agent.update("s1", json!({"sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": []}));
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !shown().is_empty() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_task_is_stopped_on_its_own() {
|
||||
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::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.stop_background(&task.id, "b1").await.unwrap();
|
||||
assert!(agent.calls.lock().contains(&"_openidea/stop_task \"b1\"".to_owned()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Deleting a task whose agent still runs in the worktree removes both and leaves no
|
||||
/// process behind, whether it is waiting for permission or idle without session/load.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -434,7 +434,13 @@ mod tests {
|
||||
t.push(AgentEntry::Agent { text: "between".into() });
|
||||
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
|
||||
t.push(AgentEntry::Permission { id: 1, title: "Run?".into(), options: vec![], chosen: None });
|
||||
t.push(AgentEntry::Permission {
|
||||
id: 1,
|
||||
title: "Run?".into(),
|
||||
options: vec![],
|
||||
questions: vec![],
|
||||
chosen: None,
|
||||
});
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! later replaces plugins and dependencies with the effective build.
|
||||
|
||||
use crate::xml::{self, Element};
|
||||
use ide_core::{Pos, Range};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
@@ -467,7 +468,7 @@ struct Resolver {
|
||||
}
|
||||
|
||||
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
|
||||
pub(crate) fn default_local_repo() -> Option<PathBuf> {
|
||||
pub fn default_local_repo() -> Option<PathBuf> {
|
||||
let m2 = dirs::home_dir()?.join(".m2");
|
||||
local_repository_of(&m2.join("settings.xml")).or(Some(m2.join("repository")))
|
||||
}
|
||||
@@ -1492,10 +1493,296 @@ pub fn parse_dependency_tree(output: &str) -> Vec<(String, Vec<MavenDependency>)
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- goto declaration
|
||||
|
||||
/// What a go-to-declaration in a POM found, and where.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PomGoto {
|
||||
/// Absolute path of the file with the declaration: the POM itself, or a parent
|
||||
/// POM of the local repository when the definition is inherited from one.
|
||||
pub path: PathBuf,
|
||||
pub range: Range,
|
||||
/// What was found.
|
||||
pub kind: PomGotoKind,
|
||||
/// The declaration as named for the user (`example.version`, `com.example:example-lib`).
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The kind of declaration a POM go-to-declaration found.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PomGotoKind {
|
||||
/// A `<properties>` entry of the POM or one of its parents.
|
||||
Property,
|
||||
/// A `<dependencyManagement>` entry providing the dependency's version.
|
||||
ManagedDependency,
|
||||
/// A `<pluginManagement>` entry providing the plugin's version.
|
||||
ManagedPlugin,
|
||||
}
|
||||
|
||||
/// Byte offset of `pos` (0-based line / UTF-16 column), clamped to `text`.
|
||||
fn offset_at(text: &str, pos: Pos) -> usize {
|
||||
let (mut line_seen, mut at) = (0usize, 0usize);
|
||||
if pos.line > 0 {
|
||||
for (i, b) in text.bytes().enumerate() {
|
||||
if b == b'\n' {
|
||||
line_seen += 1;
|
||||
if line_seen == pos.line as usize {
|
||||
at = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if line_seen < pos.line as usize {
|
||||
return text.len();
|
||||
}
|
||||
}
|
||||
let line_end = text[at..].find('\n').map_or(text.len(), |i| at + i);
|
||||
let (mut col, mut byte) = (0u32, at);
|
||||
for c in text[at..line_end].chars() {
|
||||
let width = c.len_utf16() as u32;
|
||||
if col + width > pos.col {
|
||||
break;
|
||||
}
|
||||
col += width;
|
||||
byte += c.len_utf8();
|
||||
}
|
||||
byte
|
||||
}
|
||||
|
||||
/// 0-based line / UTF-16 column of byte offset `at`.
|
||||
fn pos_at(text: &str, at: usize) -> Pos {
|
||||
let before = &text[..at];
|
||||
let line_start = before.rfind('\n').map_or(0, |i| i + 1);
|
||||
Pos::new(before.matches('\n').count() as u32, before[line_start..].encode_utf16().count() as u32)
|
||||
}
|
||||
|
||||
/// The `${property}` reference covering byte offset `at`: its name and the span of
|
||||
/// the whole reference. `None` when `at` is outside one (a closing `${…}` before it
|
||||
/// ends the search: references do not nest).
|
||||
fn property_ref_at(text: &str, at: usize) -> Option<(&str, usize, usize)> {
|
||||
// `at` may sit on the `$` itself.
|
||||
let open = text[..at].rfind("${").or_else(|| text[at..].starts_with("${").then_some(at))?;
|
||||
let close = open + 2 + text[open + 2..].find('}')?;
|
||||
(close >= at).then(|| (text[open + 2..close].trim(), open, close + 1))
|
||||
}
|
||||
|
||||
/// The elements containing `at`, from the root down to the innermost one.
|
||||
fn element_path(root: &Element, at: usize) -> Vec<&Element> {
|
||||
let mut path = vec![root];
|
||||
loop {
|
||||
let Some(next) = path.last().unwrap().children.iter().find(|c| c.start <= at && at < c.end) else {
|
||||
return path;
|
||||
};
|
||||
path.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `<groupId>` / `<artifactId>` of a dependency or plugin element, with the
|
||||
/// plugin default (`org.apache.maven.plugins`) applied.
|
||||
fn coordinates(e: &Element, props: &HashMap<String, String>) -> Option<(String, String)> {
|
||||
let group = if e.name == "plugin" && e.text_of("groupId").is_none() {
|
||||
"org.apache.maven.plugins".to_owned()
|
||||
} else {
|
||||
interpolate(&e.text_of("groupId")?, props)
|
||||
};
|
||||
Some((group, interpolate(&e.text_of("artifactId")?, props)))
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` (0-based line / UTF-16 column) of the POM
|
||||
/// `text` stored at `path` (the current buffer text when the file is open): a
|
||||
/// `${property}` reference to the `<properties>` entry that defines it along the
|
||||
/// parent chain, or a dependency / plugin to the `<dependencyManagement>` /
|
||||
/// `<pluginManagement>` entry that provides its version (a parent POM, followed into
|
||||
/// the local repository when it is not in the project). `None` when there is no
|
||||
/// resolvable declaration here.
|
||||
pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let root = xml::parse(text).filter(|e| e.name == "project")?;
|
||||
let at = offset_at(text, pos);
|
||||
if let Some((name, _, _)) = property_ref_at(text, at)
|
||||
&& !name.is_empty()
|
||||
{
|
||||
return property_target(text, path, name, local_repo);
|
||||
}
|
||||
// A `<dependency>` / `<plugin>` in a declaration position: its version may come
|
||||
// from a management entry of this POM or an ancestor's.
|
||||
let elements = element_path(&root, at);
|
||||
let e = elements.iter().rev().find(|e| e.name == "dependency" || e.name == "plugin")?;
|
||||
if elements.iter().any(|a| a.name == "dependencyManagement" || a.name == "pluginManagement") {
|
||||
return None; // Management entries are declarations; there is nothing to go to.
|
||||
}
|
||||
let kind = match e.name.as_str() {
|
||||
"dependency" => PomGotoKind::ManagedDependency,
|
||||
_ => PomGotoKind::ManagedPlugin,
|
||||
};
|
||||
managed_target(text, path, e, kind, local_repo)
|
||||
}
|
||||
|
||||
/// The parent POMs of the POM in `text` at `path`, child-first (its `<parent>` refs,
|
||||
/// via `relativePath` in the project or the local repository), with their texts.
|
||||
fn parent_chain(path: &Path, text: &str, local_repo: Option<PathBuf>) -> Vec<(PathBuf, String)> {
|
||||
let mut resolver = Resolver::new(local_repo, &[]);
|
||||
let path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let mut chain = vec![(path.clone(), text.to_owned())];
|
||||
let mut dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let mut pom = parse_pom(text);
|
||||
for _ in 0..MAX_PARENT_DEPTH {
|
||||
let Some(parent) = pom.and_then(|p| p.parent) else { return chain };
|
||||
let Some(pp) = resolver.parent_path(&dir, &parent) else { return chain };
|
||||
let pp = dunce::canonicalize(&pp).unwrap_or(pp);
|
||||
let Ok(next) = std::fs::read_to_string(&pp) else { return chain };
|
||||
pom = resolver.pom(&pp);
|
||||
dir = pp.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
chain.push((pp, next));
|
||||
}
|
||||
chain
|
||||
}
|
||||
|
||||
/// The properties visible in the POM at `chain[i]`: inherited (its parents' and
|
||||
/// ancestors' own entries) plus its own, and the `project.*` built-ins.
|
||||
fn properties_at(resolver: &mut Resolver, chain: &[(PathBuf, String)], i: usize) -> HashMap<String, String> {
|
||||
let (p, text) = &chain[i];
|
||||
let Some(pom) = parse_pom(text) else { return HashMap::new() };
|
||||
let dir = p.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let ctx = resolver.context(p, 0);
|
||||
resolver.properties_for(&pom, &ctx, &dir)
|
||||
}
|
||||
|
||||
/// Where the property `name` is declared: the `project.*` built-ins go to their
|
||||
/// coordinate elements, the rest to the first `<properties>` entry along the parent
|
||||
/// chain declaring it (a child's definition wins over a parent's; an active
|
||||
/// profile's counts as the POM's own). The winner's path, element range and name.
|
||||
fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let name = name.strip_prefix("pom.").map(|n| format!("project.{n}")).unwrap_or_else(|| name.to_owned());
|
||||
let resolver = Resolver::new(local_repo.clone(), &[]);
|
||||
let chain = parent_chain(path, text, local_repo);
|
||||
// `project.parent.*` (and the legacy `parent.*` spellings) are declared by the
|
||||
// clicked POM's own `<parent>` section.
|
||||
let parent_key = match name.as_str() {
|
||||
"project.parent.groupId"
|
||||
| "project.parent.artifactId"
|
||||
| "project.parent.version"
|
||||
| "parent.groupId"
|
||||
| "parent.version" => {
|
||||
let key = name.rsplit('.').next().unwrap();
|
||||
Some(&name[name.len() - key.len()..])
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(key) = parent_key {
|
||||
if !matches!(key, "groupId" | "artifactId" | "version") {
|
||||
return None; // No other `project.parent.*` property has a declaration.
|
||||
}
|
||||
let root = xml::parse(&chain[0].1).filter(|e| e.name == "project")?;
|
||||
let e = root.child("parent")?.child(key)?;
|
||||
return Some(PomGoto {
|
||||
path: chain[0].0.clone(),
|
||||
range: range_of(&chain[0].1, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
|
||||
if let Some(key) = name.strip_prefix("project.") {
|
||||
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
|
||||
return None; // `project.basedir`, `project.build.directory`… have no element.
|
||||
}
|
||||
for (p, text) in &chain {
|
||||
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
|
||||
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
return None;
|
||||
}
|
||||
// A property of `<properties>`: the first POM of the chain (child-first) that
|
||||
// declares it, at project level or in an active profile.
|
||||
for (p, text) in &chain {
|
||||
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
|
||||
let active: Vec<String> = parse_pom(text)
|
||||
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
|
||||
.unwrap_or_default();
|
||||
// Project level first, then the first active profile declaring the property.
|
||||
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
|
||||
root.list("profiles", "profile")
|
||||
.into_iter()
|
||||
.find(|profile| {
|
||||
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
|
||||
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
|
||||
})?
|
||||
.child("properties")?
|
||||
.child(&name)
|
||||
});
|
||||
if let Some(e) = e {
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, e),
|
||||
kind: PomGotoKind::Property,
|
||||
label: name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `<dependencyManagement>` / `<pluginManagement>` entry providing the version
|
||||
/// of the dependency / plugin element `e`: this POM's own management first, then the
|
||||
/// parent chain, child-first (the nearest declaration wins). Coordinates are matched
|
||||
/// after interpolation with each POM's effective properties.
|
||||
fn managed_target(
|
||||
text: &str,
|
||||
path: &Path,
|
||||
e: &Element,
|
||||
kind: PomGotoKind,
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<PomGoto> {
|
||||
let mut resolver = Resolver::new(local_repo.clone(), &[]);
|
||||
let chain = parent_chain(path, text, local_repo);
|
||||
let key = coordinates(e, &properties_at(&mut resolver, &chain, 0))?;
|
||||
let (section, item) = match kind {
|
||||
PomGotoKind::ManagedDependency => ("dependencyManagement/dependencies", "dependency"),
|
||||
_ => ("build/pluginManagement/plugins", "plugin"),
|
||||
};
|
||||
for (i, (p, text)) in chain.iter().enumerate() {
|
||||
let root = xml::parse(text).filter(|e| e.name == "project")?;
|
||||
let props = properties_at(&mut resolver, &chain, i);
|
||||
let Some(hit) = root.list(section, item).into_iter().find(|m| coordinates(m, &props).as_ref() == Some(&key))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let target = hit.child("artifactId").unwrap_or(hit);
|
||||
return Some(PomGoto {
|
||||
path: p.clone(),
|
||||
range: range_of(text, target),
|
||||
kind,
|
||||
label: format!("{}:{}", key.0, key.1),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The range of element `e` in `text`.
|
||||
fn range_of(text: &str, e: &Element) -> Range {
|
||||
Range::new(pos_at(text, e.start), pos_at(text, e.end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `parent_chain` returns paths normalized by `dunce::canonicalize`, so the
|
||||
/// expected values compared against them must go through the same call: the
|
||||
/// temp dirs sit behind symlinks on macOS (`/var` → `/private/var`) and under
|
||||
/// an 8.3 short name on Windows, and raw paths would not match on those runners.
|
||||
fn canon(path: &Path) -> PathBuf {
|
||||
dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// A plugin jar in `repo` whose descriptor declares `goals`.
|
||||
fn write_plugin_jar(repo: &Path, group: &str, artifact: &str, version: &str, goals: &[&str]) {
|
||||
let dir = repo.join(group.replace('.', "/")).join(artifact).join(version);
|
||||
@@ -2175,6 +2462,325 @@ mod tests {
|
||||
assert_eq!((d.group_id.as_str(), d.version.as_deref()), ("g", Some("1")), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------- goto declaration
|
||||
|
||||
/// The position of the first character of `needle` (a click on it).
|
||||
fn at(text: &str, needle: &str) -> Pos {
|
||||
pos_at(text, text.find(needle).unwrap())
|
||||
}
|
||||
|
||||
/// A parent POM and a child of it in `tmp`: the parent at `tmp/pom.xml`, the
|
||||
/// child at `tmp/app/pom.xml` (found through the default `../pom.xml`).
|
||||
fn write_parent_child(tmp: &Path, parent: &str, child: &str) {
|
||||
std::fs::create_dir_all(tmp.join("app")).unwrap();
|
||||
std::fs::write(tmp.join("pom.xml"), parent).unwrap();
|
||||
std::fs::write(tmp.join("app/pom.xml"), child).unwrap();
|
||||
}
|
||||
|
||||
const CHILD_HEADER: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<parent>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
"#;
|
||||
|
||||
const PARENT_HEADER: &str = r#"<project xmlns="http://maven.apache.org/POM/4.0.0">
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0</version>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn a_property_reference_finds_its_definition_in_the_same_pom() {
|
||||
let text = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = Path::new("/tmp/pom.xml");
|
||||
let goto = goto_declaration(&text, path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.label, "example.version");
|
||||
assert_eq!(goto.path, path);
|
||||
let from = text.find("<example.version>").unwrap();
|
||||
let to = text.find("</example.version>").unwrap() + "</example.version>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
let from = parent.find("<example.version>").unwrap();
|
||||
assert_eq!(goto.range.start, pos_at(&parent, from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_property_wins_over_the_parent_s_definition() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.0.0</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<example.version>2.0.0</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.path, canon(&path), "the child's own definition");
|
||||
let from = text.find("<example.version>").unwrap();
|
||||
let to = text.find("</example.version>").unwrap() + "</example.version>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
|
||||
assert!(text[from..to].contains("2.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_managed_dependency_reference_finds_the_managing_declaration_in_the_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>example-lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>example-lib</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "<artifactId>example-lib"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::ManagedDependency);
|
||||
assert_eq!(goto.label, "com.example:example-lib");
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
let from = parent.find("<artifactId>example-lib</artifactId>").unwrap();
|
||||
let to = from + "<artifactId>example-lib</artifactId>".len();
|
||||
assert_eq!(goto.range, Range::new(pos_at(&parent, from), pos_at(&parent, to)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_managed_plugin_reference_finds_the_managing_declaration_in_the_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "<artifactId>maven-compiler-plugin"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::ManagedPlugin);
|
||||
assert_eq!(goto.label, "org.apache.maven.plugins:maven-compiler-plugin");
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_property_is_found_in_a_parent_pom_of_the_local_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repository");
|
||||
let parent_dir = repo.join("com/example/parent/1.0");
|
||||
std::fs::create_dir_all(&parent_dir).unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<properties>
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
</project>"#
|
||||
);
|
||||
std::fs::write(parent_dir.join("parent-1.0.pom"), &parent).unwrap();
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
std::fs::create_dir_all(tmp.path().join("app")).unwrap();
|
||||
std::fs::write(&path, &child).unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${example.version}"), Some(repo)).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, canon(&parent_dir.join("parent-1.0.pom")));
|
||||
assert_eq!(goto.range.start, pos_at(&parent, parent.find("<example.version>").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_version_resolves_to_the_first_pom_declaring_its_own_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(r#"{PARENT_HEADER}<packaging>pom</packaging></project>"#);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>${{project.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let goto = goto_declaration(&text, &path, at(&text, "${project.version}"), None).unwrap();
|
||||
assert_eq!(goto.path, canon(&tmp.path().join("pom.xml")), "the child has no own <version>");
|
||||
assert_eq!(goto.range.start, pos_at(&parent, parent.find("<version>").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_without_a_resolvable_declaration_find_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = format!(
|
||||
r#"{PARENT_HEADER}<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>managed-lib</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>"#
|
||||
);
|
||||
let child = format!(
|
||||
r#"{CHILD_HEADER}<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>direct-lib</artifactId>
|
||||
<version>${{missing.key}}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>other-lib</artifactId>
|
||||
<version>2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
write_parent_child(tmp.path(), &parent, &child);
|
||||
let path = tmp.path().join("app/pom.xml");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
// The property is declared nowhere along the chain.
|
||||
assert_eq!(goto_declaration(&text, &path, at(&text, "${missing.key}"), None), None);
|
||||
// The dependency names its own version: it is the declaration.
|
||||
assert_eq!(goto_declaration(&text, &path, at(&text, "<artifactId>other-lib"), None), None);
|
||||
// A management entry is a declaration itself, not a reference.
|
||||
let parent_path = tmp.path().join("pom.xml");
|
||||
let parent_text = std::fs::read_to_string(&parent_path).unwrap();
|
||||
assert_eq!(
|
||||
goto_declaration(&parent_text, &parent_path, at(&parent_text, "<artifactId>managed-lib"), None),
|
||||
None
|
||||
);
|
||||
// Offsets beyond the document, and non-POM documents, find nothing.
|
||||
assert_eq!(goto_declaration(&text, &path, Pos::new(999, 0), None), None);
|
||||
assert_eq!(goto_declaration("<project></project>", &path, Pos::new(0, 3), None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_property_reference_after_non_ascii_text_is_still_found() {
|
||||
let text = format!(
|
||||
r#"{CHILD_HEADER}<properties>
|
||||
<!-- Версия сборки: сборка 2026 -->
|
||||
<example.version>1.2.3</example.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<!-- Проверка: ссылка на свойство -->
|
||||
<version>${{example.version}}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>"#
|
||||
);
|
||||
let path = Path::new("/tmp/pom.xml");
|
||||
let goto = goto_declaration(&text, path, at(&text, "${example.version}"), None).unwrap();
|
||||
assert_eq!(goto.kind, PomGotoKind::Property);
|
||||
assert_eq!(goto.path, path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,6 +95,24 @@ fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
/// `--threads`) is left out, because the sync pins its own `-T1` — its console
|
||||
/// output is parsed as one stream, which a parallel build interleaves.
|
||||
fn sync_maven_options(options: &[String]) -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(options.len());
|
||||
let mut args = options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "-T" || arg == "--threads" {
|
||||
args.next(); // the count itself
|
||||
} else if (arg.starts_with("-T") && arg.len() > 2) || arg.starts_with("--threads=") {
|
||||
// `--threads=4` / `-T4`: the count is part of the argument.
|
||||
} else {
|
||||
out.push(arg.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
const GRADLE_CACHE: &str = "gradle.json";
|
||||
const MAVEN_PROFILES: &str = "maven-profiles.json";
|
||||
|
||||
@@ -324,7 +342,7 @@ pub fn sync_maven(
|
||||
// `dependency:tree` output of concurrent modules, which the sync parses
|
||||
// as one stream. mvn is serial anyway, so this only pins the daemon.
|
||||
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into(), "-T1".into()];
|
||||
args.extend(options.maven_options.iter().cloned());
|
||||
args.extend(sync_maven_options(&options.maven_options));
|
||||
if options.offline {
|
||||
args.push("-o".into());
|
||||
}
|
||||
@@ -831,6 +849,19 @@ mod tests {
|
||||
assert_eq!(error_summary("one\nlast line\n\n"), "last line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sync_leaves_out_the_settings_thread_count() {
|
||||
// The sync pins its own `-T1`; the user's `-T` (Settings › Maven) would win
|
||||
// over it on the mvnd command line and interleave the parsed output.
|
||||
let options = ["-s".to_owned(), "settings.xml".to_owned(), "-T".to_owned(), "4".to_owned()];
|
||||
assert_eq!(sync_maven_options(&options), ["-s", "settings.xml"]);
|
||||
let options = ["--threads".to_owned(), "2C".to_owned(), "-Dmaven.repo.local=/m2".to_owned()];
|
||||
assert_eq!(sync_maven_options(&options), ["-Dmaven.repo.local=/m2"]);
|
||||
assert_eq!(sync_maven_options(&["-T4".to_owned()]), Vec::<String>::new());
|
||||
assert_eq!(sync_maven_options(&["--threads=4".to_owned()]), Vec::<String>::new());
|
||||
assert!(sync_maven_options(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The file list on the OS clipboard: what Explorer copies when the user
|
||||
//! copies files, so the project view can paste them, and what the project view
|
||||
//! writes so Explorer can paste the files it copied (IDEA does both). The
|
||||
//! written list comes with the paths as text, so a paste into an editor
|
||||
//! inserts them instead of doing nothing.
|
||||
//! written list comes with the file names as text, so a paste into an editor
|
||||
//! inserts them instead of doing nothing (#1878).
|
||||
//!
|
||||
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
|
||||
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
|
||||
@@ -44,6 +44,21 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
imp::set_files(paths)
|
||||
}
|
||||
|
||||
/// The text flavor written beside the file list: the files' names, one per
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.to_string_lossy().into_owned())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -108,7 +123,7 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, encode};
|
||||
use super::{HEADER, decode, encode, names_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -220,9 +235,9 @@ mod imp {
|
||||
if bytes.len() <= HEADER {
|
||||
return false;
|
||||
}
|
||||
// The paths as text, newline-separated, so pasting into an editor
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
let text = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\r\n");
|
||||
// The file names as text: the file list keeps the absolute paths for
|
||||
// Explorer, while an editor paste inserts the names (#1878).
|
||||
let text = names_text(paths, "\r\n");
|
||||
// SAFETY: the blocks are allocated, filled, handed to the clipboard and
|
||||
// freed only on the paths where the clipboard did not take ownership.
|
||||
unsafe {
|
||||
@@ -242,7 +257,7 @@ mod imp {
|
||||
return false;
|
||||
}
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it.
|
||||
// the file names are set back with it.
|
||||
if EmptyClipboard() == 0 {
|
||||
CloseClipboard();
|
||||
GlobalFree(memory);
|
||||
@@ -278,6 +293,8 @@ mod imp {
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
|
||||
/// `NSURL` as the one class to read, limited to file URLs: a web link the
|
||||
/// user copied is not a file to paste.
|
||||
fn read_file_urls<R>(
|
||||
@@ -338,13 +355,11 @@ mod imp {
|
||||
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
// Replacing the list also drops the text the user copied before;
|
||||
// the paths' own text is set back with it, so an editor paste
|
||||
// inserts them (IDEA writes the list and the text together).
|
||||
// the file names are set back as text, so an editor paste inserts
|
||||
// names, not paths (#1878).
|
||||
board.clearContents();
|
||||
let written = board.writeObjects(&NSArray::from_slice(&writers));
|
||||
let text = NSString::from_str(
|
||||
&paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"),
|
||||
);
|
||||
let text = NSString::from_str(&names_text(paths, "\n"));
|
||||
board.setString_forType(&text, unsafe { NSPasteboardTypeString });
|
||||
written
|
||||
})
|
||||
@@ -415,6 +430,15 @@ mod tests {
|
||||
assert_eq!(decode(&far), Vec::<PathBuf>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_flavor_is_the_file_names() {
|
||||
assert_eq!(names_text(&paths(&["C:/work/project/a.txt", "C:/work/project/sub"]), "\r\n"), "a.txt\r\nsub");
|
||||
// A path with no file name (the filesystem root) keeps its whole path.
|
||||
let root = PathBuf::from("/");
|
||||
assert!(root.file_name().is_none());
|
||||
assert_eq!(names_text(std::slice::from_ref(&root), "\n"), root.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ansi_list_is_still_read_before_the_terminator() {
|
||||
let mut bytes = vec![0u8; HEADER];
|
||||
|
||||
@@ -367,6 +367,8 @@ pub struct AppearanceSettings {
|
||||
pub red_green_vision: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
pub small_tree_indents: bool,
|
||||
pub full_path_in_title: bool,
|
||||
pub project_colors_in_toolbar: bool,
|
||||
pub dnd_with_alt_only: bool,
|
||||
@@ -437,6 +439,7 @@ impl Default for AppearanceSettings {
|
||||
red_green_vision: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
full_path_in_title: false,
|
||||
project_colors_in_toolbar: true,
|
||||
dnd_with_alt_only: false,
|
||||
@@ -916,6 +919,24 @@ pub struct MavenSettings {
|
||||
/// Maven Daemon home (or its `mvnd` executable); empty = `$MVND_HOME`, else
|
||||
/// `mvnd` on `PATH` / common install dirs. Only used when `daemon` is on.
|
||||
pub mvnd_home: String,
|
||||
/// Thread count of Maven builds (`-T`): a number of threads (`4`) or a core
|
||||
/// multiplier (`2C`, `2.5C`); empty = Maven's default (one thread per module).
|
||||
pub threads: String,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
/// The `-T` value when it is one Maven accepts: a thread count (`4`) or a
|
||||
/// core multiplier with an optional decimal fraction (`1C`, `2.5C`).
|
||||
/// Anything else is dropped: a bad `-T` would make every Maven run fail.
|
||||
pub fn thread_count(&self) -> Option<&str> {
|
||||
let value = self.threads.trim();
|
||||
let number = value.strip_suffix('C').unwrap_or(value);
|
||||
let mut decimal = number.split('.');
|
||||
let well_formed = number.parse::<f64>().is_ok_and(|n| n > 0.0)
|
||||
&& decimal.clone().count() <= 2
|
||||
&& decimal.all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()));
|
||||
well_formed.then_some(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -1158,6 +1179,41 @@ mod maven_linkage_tests {
|
||||
assert!(encoded.contains("\"daemon\":true") && encoded.contains("mvndHome"));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_takes_counts_and_core_multipliers_only() {
|
||||
let threads = |t: &str| {
|
||||
let m = MavenSettings { threads: t.into(), ..Default::default() };
|
||||
m.thread_count().map(str::to_owned)
|
||||
};
|
||||
// Empty = Maven's default (one thread per module).
|
||||
assert_eq!(threads("").as_deref(), None);
|
||||
assert_eq!(threads(" ").as_deref(), None);
|
||||
// A thread count, and a core multiplier whose fraction may be decimal.
|
||||
assert_eq!(threads("4").as_deref(), Some("4"));
|
||||
assert_eq!(threads(" 2 ").as_deref(), Some("2"));
|
||||
assert_eq!(threads("1C").as_deref(), Some("1C"));
|
||||
assert_eq!(threads("2.0C").as_deref(), Some("2.0C"));
|
||||
assert_eq!(threads("0.5C").as_deref(), Some("0.5C"));
|
||||
// Everything else a `-T` would make every Maven run reject is dropped.
|
||||
assert_eq!(threads("abc").as_deref(), None);
|
||||
assert_eq!(threads("4x").as_deref(), None);
|
||||
assert_eq!(threads("0").as_deref(), None);
|
||||
assert_eq!(threads("-4").as_deref(), None);
|
||||
assert_eq!(threads("1e3").as_deref(), None);
|
||||
assert_eq!(threads("2..5C").as_deref(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_round_trips_and_defaults_to_empty() {
|
||||
// Old settings files predate the thread count; `serde(default)` keeps them loadable.
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.threads.is_empty() && old.thread_count().is_none());
|
||||
let settings = MavenSettings { threads: "2C".into(), ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
assert!(encoded.contains("\"threads\":\"2C\""));
|
||||
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -20,6 +20,9 @@ memchr = "2"
|
||||
portable-pty.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tracing-subscriber.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros"] }
|
||||
@@ -301,6 +301,8 @@ pub struct DebugManager {
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
}
|
||||
|
||||
/// Whether the debugged project depends on the Flutter SDK, so it must go
|
||||
@@ -587,6 +589,7 @@ impl DebugManager {
|
||||
exception_choices: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -994,15 +997,62 @@ impl DebugManager {
|
||||
|
||||
/// Ends a session: `terminate` (when asked and supported) → `disconnect` → kill.
|
||||
pub(crate) async fn shutdown(&self, s: &Arc<Session>, terminate: bool) {
|
||||
// java-debug runs the program itself and pipes its stdout over DAP. A `disconnect`
|
||||
// ends that DAP session, so every line the program writes while shutting down is lost.
|
||||
// Ask the program to exit ourselves and keep the adapter attached until it has drained
|
||||
// the console (`terminated`), as IDEA does with the process it owns.
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
let own_terminate = terminate && s.request == "launch" && pid > 0;
|
||||
let graceful = terminate && s.request == "launch" && s.supports("supportsTerminateRequest");
|
||||
if !s.conn.is_closed() {
|
||||
if terminate && s.request == "launch" && s.supports("supportsTerminateRequest") {
|
||||
if graceful {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && !own_terminate {
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
if own_terminate && !graceful {
|
||||
// Signal before anything else: waiting on a request the adapter may not answer
|
||||
// would delay the shutdown the console is supposed to show.
|
||||
crate::session::signal_debuggee(s, false);
|
||||
}
|
||||
if graceful {
|
||||
// java-debug sends `terminated` only after it has drained the program's console
|
||||
// (it waits up to 5 s for the output pump). Close on the process id alone and the
|
||||
// last shutdown lines are dropped, so wait for that event here.
|
||||
let deadline = std::time::Instant::now() + crate::session::DEBUGGEE_EXIT_WAIT;
|
||||
while !s.terminated.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
// An adapter answers `disconnect` before the program it launched has exited, and that
|
||||
// program keeps its port until it is gone. Reporting the session as terminated then
|
||||
// lets Run start again into an occupied port, so wait for the program first — with the
|
||||
// connection still open, so a second Stop can find the session and kill it.
|
||||
crate::session::wait_for_debuggee(s, terminate).await;
|
||||
if terminate && s.request == "launch" {
|
||||
// The adapter reports `terminated` only after it has drained the program's console
|
||||
// (java-debug waits up to 5 s for the pump): closing before that drops the last
|
||||
// shutdown lines from the console.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(6);
|
||||
while !s.terminated.load(Ordering::Acquire) && !s.conn.is_closed() && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
if graceful && !s.conn.is_closed() {
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": false }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
@@ -1577,10 +1627,40 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a session and its child sessions.
|
||||
/// Stops every debug session started from `root` or below — closing a project stops the
|
||||
/// programs it launched even when the session's owner key does not name the window doing
|
||||
/// the closing (window groups, auxiliary windows).
|
||||
pub async fn stop_under(&self, root: &Path) {
|
||||
let ids: Vec<DebugSessionId> =
|
||||
self.live_sessions().into_iter().filter(|s| s.spec.cwd.starts_with(root)).map(|s| s.id).collect();
|
||||
tracing::info!(root = %root.display(), sessions = ids.len(), "closing project: stopping debug sessions");
|
||||
for id in ids {
|
||||
if let Err(e) = self.stop(id).await {
|
||||
tracing::debug!("debug session {id:?} did not stop: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a session and its child sessions. A second Stop while the first one waits kills
|
||||
/// the program instead of waiting for it — even after the adapter dropped the session.
|
||||
pub async fn stop(&self, s: DebugSessionId) -> IdeResult<()> {
|
||||
{
|
||||
let in_flight = self.stopping.lock();
|
||||
if let Some(session) = in_flight.get(&s) {
|
||||
session.stop_force.store(true, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let session = self.session(s)?;
|
||||
let children: Vec<Arc<Session>> = self.live_sessions().into_iter().filter(|c| c.parent == Some(s)).collect();
|
||||
self.stopping.lock().insert(s, session.clone());
|
||||
let result = self.stop_tree(session).await;
|
||||
self.stopping.lock().remove(&s);
|
||||
result
|
||||
}
|
||||
|
||||
async fn stop_tree(&self, session: Arc<Session>) -> IdeResult<()> {
|
||||
let children: Vec<Arc<Session>> =
|
||||
self.live_sessions().into_iter().filter(|c| c.parent == Some(session.id)).collect();
|
||||
for child in children {
|
||||
self.shutdown(&child, true).await;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use tokio::process::Child;
|
||||
@@ -49,6 +49,14 @@ pub(crate) struct Session {
|
||||
pub configured: AtomicBool,
|
||||
pub initialized: watch::Sender<bool>,
|
||||
pub terminated: AtomicBool,
|
||||
/// Set by a second Stop: the one waiting for the program kills it instead.
|
||||
pub stop_force: AtomicBool,
|
||||
/// `systemProcessId` from the adapter's `process` event: the program being debugged.
|
||||
pub debuggee_pid: AtomicI64,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
pub stop_pids: parking_lot::Mutex<Vec<i32>>,
|
||||
/// Breakpoints replaced for run to cursor / force stepping, restored on the next stop.
|
||||
pub pending_restore: Mutex<PendingRestore>,
|
||||
/// Adapter breakpoint id → (file, index in the stored list).
|
||||
@@ -96,6 +104,9 @@ impl Session {
|
||||
configured: AtomicBool::new(false),
|
||||
initialized: watch::channel(false).0,
|
||||
terminated: AtomicBool::new(false),
|
||||
stop_force: AtomicBool::new(false),
|
||||
debuggee_pid: AtomicI64::new(0),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
pending_restore: Mutex::default(),
|
||||
breakpoint_ids: Mutex::new(HashMap::new()),
|
||||
resolved_paths: Mutex::new(HashMap::new()),
|
||||
@@ -275,6 +286,108 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long Stop waits for a launched program to exit before reporting the session ended.
|
||||
pub(crate) const DEBUGGEE_EXIT_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The program and everything it started: an adapter may report the launcher shell, whose
|
||||
/// child is the debugged program, so stopping only the reported pid leaves the program alive.
|
||||
#[cfg(unix)]
|
||||
fn process_tree(pid: i32) -> Vec<i32> {
|
||||
use std::collections::HashMap;
|
||||
let Ok(out) = std::process::Command::new("ps").args(["-A", "-o", "pid=,ppid="]).output() else {
|
||||
return vec![pid];
|
||||
};
|
||||
let mut children: HashMap<i32, Vec<i32>> = HashMap::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let mut it = line.split_whitespace();
|
||||
let (Some(p), Some(parent)) = (it.next(), it.next()) else { continue };
|
||||
let (Ok(p), Ok(parent)) = (p.parse::<i32>(), parent.parse::<i32>()) else { continue };
|
||||
children.entry(parent).or_default().push(p);
|
||||
}
|
||||
let mut tree = vec![pid];
|
||||
let mut at = 0;
|
||||
while at < tree.len() {
|
||||
if let Some(kids) = children.get(&tree[at]) {
|
||||
tree.extend(kids.iter().copied());
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// Asks the program itself to exit (`force` = SIGKILL) without ending the adapter session:
|
||||
/// its output keeps flowing over DAP while it shuts down. The first call remembers the pid
|
||||
/// tree, because the reported pid may die before its program does.
|
||||
pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
if pid <= 0 {
|
||||
return;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut known = s.stop_pids.lock();
|
||||
if known.is_empty() {
|
||||
*known = process_tree(pid as i32);
|
||||
}
|
||||
let signal = if force { libc::SIGKILL } else { libc::SIGTERM };
|
||||
// Children first: the shell that started the program would otherwise reparent it.
|
||||
for p in known.iter().rev() {
|
||||
// SAFETY: plain syscall on the processes this session started.
|
||||
unsafe {
|
||||
libc::kill(*p, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut cmd = std::process::Command::new("taskkill");
|
||||
cmd.args(["/PID", &pid.to_string(), "/T"]);
|
||||
if force {
|
||||
cmd.arg("/F");
|
||||
}
|
||||
let _ = cmd.status();
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let _ = (pid, force);
|
||||
}
|
||||
|
||||
/// Waits until the program a `launch` session started is gone; a second Stop kills it.
|
||||
pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {
|
||||
if !terminate || s.request != "launch" {
|
||||
return;
|
||||
}
|
||||
let pid = s.debuggee_pid.load(Ordering::Acquire);
|
||||
if pid <= 0 {
|
||||
return;
|
||||
}
|
||||
tracing::info!(session = s.id.0, pid, "stop: waiting for the debugged program to exit");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::time::Instant;
|
||||
let targets = {
|
||||
let known = s.stop_pids.lock();
|
||||
if known.is_empty() { process_tree(pid as i32) } else { known.clone() }
|
||||
};
|
||||
let alive = || targets.iter().any(|p| unsafe { libc::kill(*p, 0) } == 0);
|
||||
let deadline = Instant::now() + DEBUGGEE_EXIT_WAIT;
|
||||
while alive() {
|
||||
if s.stop_force.swap(false, Ordering::AcqRel) {
|
||||
signal_debuggee(s, true);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
// The program ignored the terminate: do not leave it running.
|
||||
signal_debuggee(s, true);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = pid;
|
||||
}
|
||||
}
|
||||
|
||||
// java-debug and Windows netcoredbg need native separators for source lookup.
|
||||
// Keep DAP path mode, but normalize Windows drive and UNC paths.
|
||||
fn is_windows_source_path(path: &str) -> bool {
|
||||
@@ -370,8 +483,18 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
return;
|
||||
}
|
||||
let output = str_("output").unwrap_or_default();
|
||||
if tracing::enabled!(tracing::Level::DEBUG) && mgr.stopping.lock().contains_key(&s.id) {
|
||||
tracing::debug!(session = ?s.id, bytes = output.len(), "output during stop");
|
||||
}
|
||||
s.emit(DebugEvent::Output { category, output });
|
||||
}
|
||||
// The program the adapter started: Stop must wait for it, not for the adapter's reply.
|
||||
// `process` is the DAP event; java-debug announces the same thing as `processid`.
|
||||
"process" | "processid" => {
|
||||
if let Some(pid) = int("systemProcessId").or_else(|| int("processId")).filter(|p| *p > 0) {
|
||||
s.debuggee_pid.store(pid, Ordering::Release);
|
||||
}
|
||||
}
|
||||
"thread" => s.emit(DebugEvent::Thread {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
started: body.get("reason").and_then(Value::as_str) != Some("exited"),
|
||||
@@ -390,12 +513,18 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
}
|
||||
"exited" => {}
|
||||
"terminated" => {
|
||||
if !s.terminated.swap(true, Ordering::AcqRel) {
|
||||
s.emit(DebugEvent::Terminated);
|
||||
}
|
||||
let first = !s.terminated.swap(true, Ordering::AcqRel);
|
||||
let mgr = mgr.clone();
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move { mgr.shutdown(&s, false).await });
|
||||
// Waiting here would stop reading the adapter: it keeps sending the program's last
|
||||
// output while the program exits. Wait off the reader task, then report the end.
|
||||
tokio::spawn(async move {
|
||||
if first {
|
||||
wait_for_debuggee(&s, true).await;
|
||||
s.emit(DebugEvent::Terminated);
|
||||
}
|
||||
mgr.shutdown(&s, false).await;
|
||||
});
|
||||
}
|
||||
"capabilities" => {
|
||||
if let Some(new) = body.get("capabilities").and_then(Value::as_object) {
|
||||
|
||||
@@ -5,11 +5,16 @@ use crate::adapter::{AdapterIo, LaunchFuture};
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_jsonrpc::framing;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
#[cfg(unix)]
|
||||
use std::time::Instant;
|
||||
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
|
||||
type Log = Arc<Mutex<Vec<Value>>>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Clone)]
|
||||
struct Script {
|
||||
/// Send a `runInTerminal` reverse request when `launch` arrives.
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
@@ -17,10 +22,35 @@ struct Script {
|
||||
start_debugging: bool,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
java_process_id: bool,
|
||||
/// Send one more output event right after the `terminated` event (a program still logging
|
||||
/// while it shuts down).
|
||||
output_after_terminate: bool,
|
||||
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
|
||||
supports_terminate: bool,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
}
|
||||
|
||||
impl Default for Script {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
start_debugging: false,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
supports_terminate: true,
|
||||
hold_set_breakpoints: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeLauncher {
|
||||
log: Log,
|
||||
script: Script,
|
||||
@@ -77,7 +107,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
json!({
|
||||
"supportsConfigurationDoneRequest": true,
|
||||
"supportsCompletionsRequest": true,
|
||||
"supportsTerminateRequest": true,
|
||||
"supportsTerminateRequest": script.supports_terminate,
|
||||
"supportsSetVariable": true,
|
||||
"supportsFunctionBreakpoints": true,
|
||||
"supportsDataBreakpoints": true,
|
||||
@@ -155,6 +185,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
if let Some(l) = pending_launch.take() {
|
||||
send!(json!({"type": "response", "request_seq": l, "command": "launch", "success": true}));
|
||||
}
|
||||
if let Some(pid) = script.debuggee_pid {
|
||||
let event = if script.java_process_id {
|
||||
json!({"type": "event", "event": "processid", "body": {"processId": pid, "shellProcessId": pid}})
|
||||
} else {
|
||||
json!({"type": "event", "event": "process", "body": {"name": "prog", "systemProcessId": pid}})
|
||||
};
|
||||
send!(event);
|
||||
}
|
||||
send!(json!({"type": "event", "event": "output", "body": {"category": "stdout", "output": "hello\n"}}));
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
@@ -208,6 +246,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"terminate" => {
|
||||
ok!(msg, Value::Null);
|
||||
send!(json!({"type": "event", "event": "terminated"}));
|
||||
if script.output_after_terminate {
|
||||
send!(
|
||||
json!({"type": "event", "event": "output", "body": {"category": "stdout", "output": "late\n"}})
|
||||
);
|
||||
}
|
||||
}
|
||||
"disconnect" => {
|
||||
ok!(msg, Value::Null);
|
||||
@@ -1348,6 +1391,201 @@ fn flutter_projects_are_found_from_the_program_or_the_working_directory() {
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_waits_for_the_launched_program_to_exit() {
|
||||
// The adapter answers `disconnect` at once; the program it started is still alive and
|
||||
// holds its port for a while. Stop must not report the session as over before it exits.
|
||||
// Reaped by a waiting thread: a zombie still "exists" for `kill(pid, 0)`, unlike the
|
||||
// program an adapter starts and reaps.
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await; // let the program install its trap
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed >= Duration::from_millis(800), "stop returned after {elapsed:?}, before the program exited");
|
||||
assert!(elapsed < Duration::from_secs(5), "stop waited {elapsed:?} for a program that ended after a second");
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_second_stop_kills_the_program_instead_of_waiting() {
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let exited = exited.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
exited.store(true, Ordering::Release);
|
||||
});
|
||||
}
|
||||
let h = harness(Script { debuggee_pid: Some(pid), ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(400)).await;
|
||||
let first = tokio::spawn({
|
||||
let manager = h.manager.clone();
|
||||
async move { manager.stop(id).await }
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert!(!exited.load(Ordering::Acquire), "the program is still alive while the first Stop waits");
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let first_result = tokio::time::timeout(Duration::from_secs(5), first).await.expect("the first Stop returns");
|
||||
first_result.unwrap().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(2), "a second Stop does not wait out the program");
|
||||
for _ in 0..100 {
|
||||
if exited.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(exited.load(Ordering::Acquire), "the second Stop killed the program");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_waits_for_the_program_when_the_adapter_uses_javas_processid_event() {
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), java_process_id: true, ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert!(
|
||||
started.elapsed() >= Duration::from_millis(800),
|
||||
"stop returned after {:?}, before the program exited",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn output_keeps_arriving_while_a_stopped_program_is_exiting() {
|
||||
// Ignores SIGTERM: Stop must wait for the program, not assume the signal ended it.
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(1)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
let h = harness(Script { debuggee_pid: Some(pid), output_after_terminate: true, ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let stop = tokio::spawn({
|
||||
let manager = h.manager.clone();
|
||||
async move { manager.stop(id).await }
|
||||
});
|
||||
// The last line must reach the console while Stop still waits for the program.
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output == "late\n")).await;
|
||||
assert!(started.elapsed() < Duration::from_millis(800), "output arrived only after the program was gone");
|
||||
stop.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_project_stops_the_debug_sessions_it_started() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
// The session's cwd is /p, whatever key it was started under.
|
||||
h.manager.stop_under(Path::new("/p")).await;
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
assert!(h.manager.sessions(None).is_empty(), "session {id:?} is gone");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_kills_the_program_started_by_the_reported_launcher() {
|
||||
use std::io::BufRead;
|
||||
// java-debug reports the launcher shell; the JVM is its child. Stopping only the reported
|
||||
// pid orphans the program, which keeps running (and keeps its ports).
|
||||
let mut launcher = std::process::Command::new("sh")
|
||||
.args(["-c", "python3 -c 'import time; time.sleep(30)' & echo $!; wait"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let launcher_pid = launcher.id();
|
||||
let mut line = String::new();
|
||||
std::io::BufReader::new(launcher.stdout.take().unwrap()).read_line(&mut line).unwrap();
|
||||
let program: i32 = line.trim().parse().expect("child pid");
|
||||
// Reap the launcher: a zombie still "exists" for `kill(pid, 0)`, unlike the shell jdtls reaps.
|
||||
std::thread::spawn(move || {
|
||||
let _ = launcher.wait();
|
||||
});
|
||||
|
||||
let h = harness(Script {
|
||||
debuggee_pid: Some(launcher_pid),
|
||||
supports_terminate: false, // java-debug does not advertise it
|
||||
..Default::default()
|
||||
});
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Initialized)).await;
|
||||
for _ in 0..100 {
|
||||
if h.manager.session(id).map(|s| s.debuggee_pid.load(Ordering::Acquire)).ok() == Some(i64::from(launcher_pid)) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while unsafe { libc::kill(program, 0) } == 0 {
|
||||
assert!(Instant::now() < deadline, "the program the launcher started survived stop");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delve_leftovers_are_removed_without_touching_other_files() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-delve-bin-{}", std::process::id()));
|
||||
|
||||
@@ -32,7 +32,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.2.0";
|
||||
pub const ENGINE_VERSION: &str = "1.3.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -248,7 +248,7 @@ impl Host {
|
||||
vec![project.notebooks.clone()],
|
||||
project.kotlin_bridge.iter().cloned().collect(),
|
||||
Some(project.lsp.clone()),
|
||||
Some((self.debugger.clone(), window.to_owned())),
|
||||
Some((self.debugger.clone(), window.to_owned(), project.root.clone())),
|
||||
Some(project),
|
||||
))
|
||||
}
|
||||
@@ -261,7 +261,7 @@ impl Host {
|
||||
notebooks: Vec<Arc<notebook::NotebookService>>,
|
||||
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
|
||||
lsp: Option<Arc<ide_lsp::LspManager>>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String)>,
|
||||
debug: Option<(Arc<ide_dap::DebugManager>, String, std::path::PathBuf)>,
|
||||
retired: Option<Arc<Project>>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
for bridge in &bridges {
|
||||
@@ -286,8 +286,9 @@ impl Host {
|
||||
if let Some(lsp) = lsp {
|
||||
lsp.shutdown_all().await;
|
||||
}
|
||||
if let Some((debug, key)) = debug {
|
||||
if let Some((debug, key, root)) = debug {
|
||||
debug.stop_key(&key).await;
|
||||
debug.stop_under(&root).await;
|
||||
}
|
||||
});
|
||||
if let Some(retired) = retired {
|
||||
|
||||
@@ -238,6 +238,11 @@ pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>)
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
}
|
||||
|
||||
/// Stops one of the task's background tasks.
|
||||
pub async fn stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.stop_background(&task, &background).await
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: None` cancels it.
|
||||
pub fn respond(host: &Host, window: &str, task: String, permission: u32, option: Option<String>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -297,6 +302,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_rollback", |c| async move { rollback(&c.host, &c.window, c.arg("task")?, c.arg("turns")?).await });
|
||||
d.add("agent_probe", |c| async move { probe(&c.host, &c.window, c.arg("provider")?, c.arg("refresh")?).await });
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_stop_background", |call| async move {
|
||||
stop_background(&call.host, &call.window, call.arg("task")?, call.arg("background")?).await
|
||||
});
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
|
||||
@@ -5,10 +5,11 @@ use crate::rpc::Dispatcher;
|
||||
use crate::{Host, Project, apply_workspace_edit};
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::maven::PomGoto;
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{FileEdit, IdeError, IdeEvent, IdeResult, Location, Range, RequestId, WorkspaceEdit};
|
||||
use ide_core::{FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -440,6 +441,27 @@ pub async fn maven_dependency_declaration(
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` of the Maven POM `pom` (project-relative, or
|
||||
/// absolute for a parent POM opened from the local repository): the definition of the
|
||||
/// `${property}` at the caret, or the `<dependencyManagement>` / `<pluginManagement>`
|
||||
/// entry providing the dependency's / plugin's version, along the parent chain (into
|
||||
/// the local repository when a parent is not in the project). `None` when nothing
|
||||
/// resolvable is under the caret.
|
||||
pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos: Pos) -> IdeResult<Option<PomGoto>> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let given = Path::new(&pom);
|
||||
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
|
||||
let text = project.text_of(&path)?;
|
||||
let settings = project.settings.effective();
|
||||
let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings)
|
||||
.or_else(ide_build::maven::default_local_repo);
|
||||
Ok(ide_build::maven::goto_declaration(&text, &path, pos, repo))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Adds an `<exclusion>` of `exclusion` to the declaration of the direct dependency
|
||||
/// `dependency` of the Maven module `pom`, through the open document when there is one
|
||||
/// (saved). Returns the declaration; nothing changes when it already excludes it.
|
||||
@@ -582,6 +604,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("maven_dependency_declaration", |c| async move {
|
||||
maven_dependency_declaration(&c.host, &c.window, c.arg("pom")?, c.arg("dependency")?).await
|
||||
});
|
||||
d.add("maven_goto_declaration", |c| async move {
|
||||
maven_goto_declaration(&c.host, &c.window, c.arg("pom")?, c.arg("pos")?).await
|
||||
});
|
||||
d.add("maven_exclude_dependency", |c| async move {
|
||||
maven_exclude_dependency(&c.host, &c.window, c.arg("pom")?, c.arg("dependency")?, c.arg("exclusion")?).await
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::Host;
|
||||
use crate::apply_workspace_edit as apply_edit;
|
||||
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{DocId, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
|
||||
use ide_lsp::types::*;
|
||||
use ide_plugin::ProviderDocument;
|
||||
@@ -46,7 +47,7 @@ pub async fn lsp_completion(
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result };
|
||||
let items = plugin_call(move || plugins.provide_completion(&d, pos, trigger.as_deref())).await.unwrap_or_default();
|
||||
if items.is_empty() {
|
||||
return result;
|
||||
return Ok(result.unwrap_or(CompletionList { is_incomplete: true, items: Vec::new() }));
|
||||
}
|
||||
let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() });
|
||||
list.items.extend(items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
@@ -221,14 +222,65 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
|
||||
}
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
|
||||
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
|
||||
if found.is_empty() {
|
||||
return result;
|
||||
let found: Vec<Location> =
|
||||
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
|
||||
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, found, in_string)
|
||||
}
|
||||
|
||||
async fn in_string_literal(host: &Host, window: &str, doc: DocId, pos: Pos) -> bool {
|
||||
let Ok(project) = host.project(window) else { return false };
|
||||
blocking(move || {
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
if snap.large {
|
||||
return Ok(false);
|
||||
}
|
||||
let s = ide_syntax::Snapshot::doc(doc, snap.version, &snap.language, &snap.text);
|
||||
Ok(string_at(&project.structure, &s, pos))
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn string_at(structure: &ide_syntax::StructureService, snap: &ide_syntax::Snapshot, pos: Pos) -> bool {
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
let Ok(Some(at)) = structure.node_at(snap, Range::new(pos, pos), &cancel) else { return false };
|
||||
let stringy = |kind: &str| kind.contains("string") || kind.contains("heredoc") || kind.contains("nowdoc");
|
||||
let part = |kind: &str| kind.contains("content") || kind.contains("fragment") || kind.contains("escape");
|
||||
stringy(&at.node.kind) || (part(&at.node.kind) && at.ancestors.first().is_some_and(|parent| stringy(&parent.kind)))
|
||||
}
|
||||
|
||||
fn definition_targets(
|
||||
server: IdeResult<Vec<Location>>,
|
||||
plugin: Vec<Location>,
|
||||
in_string: bool,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
if plugin.is_empty() {
|
||||
return server.map(without_generated_helpers);
|
||||
}
|
||||
let mut out = result.unwrap_or_default();
|
||||
out.extend(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }));
|
||||
if in_string {
|
||||
return Ok(plugin);
|
||||
}
|
||||
let same_place = |l: &Location| plugin.iter().any(|p| p.path == l.path && p.range.start.line == l.range.start.line);
|
||||
let server: Vec<Location> =
|
||||
without_generated_helpers(server.unwrap_or_default()).into_iter().filter(|l| !same_place(l)).collect();
|
||||
let mut out = plugin;
|
||||
out.extend(server);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn without_generated_helpers(locations: Vec<Location>) -> Vec<Location> {
|
||||
let generated = |l: &Location| {
|
||||
let path = l.path.to_string_lossy().replace('\\', "/");
|
||||
let file = path.rsplit('/').next().unwrap_or(&path);
|
||||
file.starts_with("_ide_helper") || file == ".phpstorm.meta.php" || path.contains("/vendor/_laravel_ide")
|
||||
};
|
||||
if locations.iter().all(generated) {
|
||||
return locations;
|
||||
}
|
||||
locations.into_iter().filter(|l| !generated(l)).collect()
|
||||
}
|
||||
|
||||
/// Gutter markers from plugins (`line-markers` providers) for `doc`.
|
||||
pub async fn plugin_line_markers(
|
||||
host: &Host,
|
||||
@@ -614,7 +666,22 @@ pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range
|
||||
}
|
||||
|
||||
pub async fn lsp_semantic_tokens(host: &Host, window: &str, doc: DocId) -> IdeResult<Option<SemanticTokens>> {
|
||||
host.project(window)?.lsp.semantic_tokens(doc).await
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::SemanticTokens) else {
|
||||
return lsp.semantic_tokens(doc).await;
|
||||
};
|
||||
let (result, tokens) =
|
||||
tokio::join!(lsp.semantic_tokens(doc), plugin_call(move || plugins.provide_semantic_tokens(&d)));
|
||||
let tokens = tokens.unwrap_or_default();
|
||||
if tokens.is_empty() {
|
||||
return result;
|
||||
}
|
||||
let server = match result {
|
||||
Ok(server) => server,
|
||||
Err(e) if matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable) => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
Ok(Some(crate::plugins::merge_semantic_tokens(server, tokens)))
|
||||
}
|
||||
|
||||
pub async fn lsp_code_lens(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CodeLens>> {
|
||||
@@ -940,6 +1007,79 @@ mod tests {
|
||||
assert!(eager.edit.is_some() && eager.data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_definitions_own_strings_and_join_the_server_elsewhere() {
|
||||
let at = |path: &str, line: u32| Location {
|
||||
path: path.into(),
|
||||
range: Range::new(Pos::new(line, 0), Pos::new(line, 4)),
|
||||
uri: None,
|
||||
};
|
||||
let paths = |found: IdeResult<Vec<Location>>| {
|
||||
found.unwrap().into_iter().map(|l| l.path.to_string_lossy().into_owned()).collect::<Vec<_>>()
|
||||
};
|
||||
let xml = at("/p/src/main/resources/UserMapper.xml", 3);
|
||||
let java = at("/p/src/main/java/UserMapper.java", 7);
|
||||
let helper = at("/p/_ide_helper.php", 1);
|
||||
let route = at("/p/routes/web.php", 2);
|
||||
let guess = at("/p/app/helpers.php", 9);
|
||||
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![java.clone(), helper.clone()]), vec![xml.clone()], false)),
|
||||
["/p/src/main/resources/UserMapper.xml", "/p/src/main/java/UserMapper.java"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![xml.clone(), java.clone()]), vec![xml.clone()], false)),
|
||||
["/p/src/main/resources/UserMapper.xml", "/p/src/main/java/UserMapper.java"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Ok(vec![guess.clone(), helper.clone()]), vec![route.clone()], true)),
|
||||
["/p/routes/web.php"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(definition_targets(Err(ide_core::IdeError::unavailable("no server")), vec![route.clone()], false)),
|
||||
["/p/routes/web.php"]
|
||||
);
|
||||
assert_eq!(paths(definition_targets(Ok(vec![helper, guess]), Vec::new(), false)), ["/p/app/helpers.php"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_inside_string_literals_are_told_apart() {
|
||||
let syntax = std::sync::Arc::new(ide_language::Syntax::new());
|
||||
let structure = ide_syntax::StructureService::new(std::sync::Arc::new(ide_language::SyntaxCache::new(syntax)));
|
||||
let php = ide_core::LanguageId::new("php");
|
||||
let text = "<?php\nreturn to_route('users.show', $user);\necho \"Hi {$name}\";\n";
|
||||
let snap = ide_syntax::Snapshot::text(&php, text);
|
||||
assert!(string_at(&structure, &snap, Pos::new(1, 20)), "inside 'users.show'");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 9)), "on to_route");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 35)), "on $user");
|
||||
assert!(!string_at(&structure, &snap, Pos::new(2, 12)), "on an interpolated variable");
|
||||
let java = ide_core::LanguageId::new("java");
|
||||
let text = "class A {\n User find(long id) { return mapper.selectById(\"users\"); }\n}\n";
|
||||
let snap = ide_syntax::Snapshot::text(&java, text);
|
||||
assert!(!string_at(&structure, &snap, Pos::new(1, 9)), "on a method name");
|
||||
assert!(string_at(&structure, &snap, Pos::new(1, 53)), "inside \"users\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_ide_helpers_give_way_to_real_declarations() {
|
||||
let at = |path: &str| Location { path: path.into(), range: Range::default(), uri: None };
|
||||
let paths =
|
||||
|found: Vec<Location>| found.into_iter().map(|l| l.path.to_string_lossy().into_owned()).collect::<Vec<_>>();
|
||||
let real = at("/app/app/Models/User.php");
|
||||
let helper = at("/app/_ide_helper_models.php");
|
||||
let meta = at("/app/.phpstorm.meta.php");
|
||||
let vendor = at("/app/vendor/_laravel_idea/_ide_helper.php");
|
||||
assert_eq!(
|
||||
paths(without_generated_helpers(vec![helper.clone(), real.clone(), meta.clone(), vendor])),
|
||||
["/app/app/Models/User.php"]
|
||||
);
|
||||
assert_eq!(
|
||||
paths(without_generated_helpers(vec![helper.clone(), meta.clone()])),
|
||||
["/app/_ide_helper_models.php", "/app/.phpstorm.meta.php"]
|
||||
);
|
||||
assert!(without_generated_helpers(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_completion_kind_the_plugin_api_documents_is_understood() {
|
||||
let wit = include_str!("../../../../wit/providers.wit");
|
||||
|
||||
@@ -71,6 +71,19 @@ pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core
|
||||
Ok(ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter).map(Into::into))
|
||||
}
|
||||
|
||||
/// The version of the PHP interpreter `php` and of the Xdebug it loads, run in `cwd` (default: the
|
||||
/// project root).
|
||||
pub async fn sdk_php_xdebug(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
php: PathBuf,
|
||||
cwd: Option<PathBuf>,
|
||||
) -> IdeResult<ide_sdk::php::PhpXdebug> {
|
||||
host.require_trust(window)?;
|
||||
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
|
||||
tokio::task::spawn_blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
|
||||
/// the language server configuration picks it).
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -173,10 +186,11 @@ pub async fn sdk_locate_tools(
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// `base -m venv location`; output lines stream through `on_output`.
|
||||
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
|
||||
pub async fn sdk_python_create_venv(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
tool: ide_sdk::python::VenvTool,
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
request: RequestId,
|
||||
@@ -185,7 +199,7 @@ pub async fn sdk_python_create_venv(
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::python::create_venv(&base, &location, &cancel, &|line| {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
@@ -245,6 +259,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
|
||||
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window, c.arg("near")?) });
|
||||
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
|
||||
d.add("sdk_php_xdebug", |c| async move { sdk_php_xdebug(&c.host, &c.window, c.arg("php")?, c.arg("cwd")?).await });
|
||||
d.add(
|
||||
"sdk_php_language_level",
|
||||
|c| async move { sdk_php_language_level(&c.host, &c.window, c.arg("path")?).await },
|
||||
@@ -261,6 +276,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
sdk_python_create_venv(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("tool")?,
|
||||
c.arg("base")?,
|
||||
c.arg("location")?,
|
||||
c.arg("request")?,
|
||||
|
||||
@@ -583,12 +583,15 @@ pub async fn vcs_create_branch(
|
||||
name: String,
|
||||
start: Option<String>,
|
||||
checkout: bool,
|
||||
overwrite: Option<bool>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let recorded = checkout.then_some("Git checkout");
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| r.create_branch(&name, start.as_deref(), checkout))
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| {
|
||||
r.create_branch_with_overwrite(&name, start.as_deref(), checkout, overwrite.unwrap_or(false))
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1335,7 +1338,16 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
vcs_checkout(&c.host, &c.window, c.arg("repo")?, c.arg("branch")?, c.arg("create")?, c.arg("options")?).await
|
||||
});
|
||||
d.add("vcs_create_branch", |c| async move {
|
||||
vcs_create_branch(&c.host, &c.window, c.arg("repo")?, c.arg("name")?, c.arg("start")?, c.arg("checkout")?).await
|
||||
vcs_create_branch(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("repo")?,
|
||||
c.arg("name")?,
|
||||
c.arg("start")?,
|
||||
c.arg("checkout")?,
|
||||
c.arg("overwrite")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"vcs_undo_commit",
|
||||
|
||||
@@ -417,6 +417,129 @@ impl PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
/// Runs an approved program until it exits or `cancel` fires, passing
|
||||
/// each output line to `on_line`; returns its exit code.
|
||||
pub(super) fn stream_process(
|
||||
&self,
|
||||
program: &str,
|
||||
args: Vec<String>,
|
||||
cwd: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(super::PluginOutputLine),
|
||||
) -> Result<Option<i32>, HostError> {
|
||||
let binary = self.approved_program(program)?;
|
||||
let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id()));
|
||||
let _ = std::fs::create_dir_all(&cwd);
|
||||
let mut cmd = std::process::Command::new(&binary);
|
||||
ide_core::process::prepare(ide_core::process::own_group(&mut cmd));
|
||||
let mut child = cmd
|
||||
.args(&args)
|
||||
.current_dir(&cwd)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| HostError::Failed(format!("{}: {e}", binary.display())))?;
|
||||
// Bounded: a program printing faster than the lines are sent waits on its pipe.
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1024);
|
||||
let read = |pipe: Box<dyn std::io::Read + Send>, stderr: bool| {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
read_lines(pipe, MAX_OUTPUT_LINE, &mut |text| {
|
||||
tx.send(super::PluginOutputLine { stderr, text }).is_ok()
|
||||
});
|
||||
});
|
||||
};
|
||||
if let Some(out) = child.stdout.take() {
|
||||
read(Box::new(out), false);
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
read(Box::new(err), true);
|
||||
}
|
||||
drop(tx);
|
||||
// Revoking the grant removes the pin: stop then.
|
||||
let cap = format!("process:{program}");
|
||||
let pin = (self.id().to_owned(), cap.clone());
|
||||
let stop = |child: &mut std::process::Child| -> Option<HostError> {
|
||||
if cancel.is_cancelled() {
|
||||
kill_group(child);
|
||||
return Some(HostError::Cancelled);
|
||||
}
|
||||
if !self.shared.pins.read().contains_key(&pin) {
|
||||
kill_group(child);
|
||||
return Some(HostError::Denied(cap.clone()));
|
||||
}
|
||||
None
|
||||
};
|
||||
loop {
|
||||
if let Some(e) = stop(&mut child) {
|
||||
return Err(e);
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(line) => on_line(line),
|
||||
// Both pipes closed: the program is done (or detached them).
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
}
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().map_err(failed)? {
|
||||
return Ok(status.code());
|
||||
}
|
||||
if let Some(e) = stop(&mut child) {
|
||||
return Err(e);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest output line a followed program sends; the rest of the line is dropped.
|
||||
const MAX_OUTPUT_LINE: usize = 16 << 10;
|
||||
|
||||
/// Passes `pipe`'s lines (without `\r\n`, at most `max` bytes each) to `line`
|
||||
/// until it returns false or the pipe closes, holding at most one line.
|
||||
fn read_lines(pipe: Box<dyn std::io::Read + Send>, max: usize, line: &mut dyn FnMut(String) -> bool) {
|
||||
use std::io::{BufRead, Read};
|
||||
let mut reader = std::io::BufReader::new(pipe);
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
buf.clear();
|
||||
match (&mut reader).take(max as u64).read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => return,
|
||||
Ok(_) => {}
|
||||
}
|
||||
if buf.last() != Some(&b'\n') && buf.len() == max {
|
||||
// Too long: skip to the end of the line.
|
||||
let mut rest = Vec::new();
|
||||
loop {
|
||||
rest.clear();
|
||||
match (&mut reader).take(max as u64).read_until(b'\n', &mut rest) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) if rest.last() == Some(&b'\n') => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let end = buf.strip_suffix(b"\n").unwrap_or(&buf);
|
||||
let end = end.strip_suffix(b"\r").unwrap_or(end);
|
||||
if !line(String::from_utf8_lossy(end).into_owned()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills a program spawned in its own group and what it started. A kill that
|
||||
/// lands while the program forks can miss the new process, so the group is
|
||||
/// signalled again before the program is reaped (until then its group id
|
||||
/// can't be reused).
|
||||
fn kill_group(child: &mut std::process::Child) {
|
||||
ide_core::process::kill_tree_of(child.id());
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
ide_core::process::kill_tree(child);
|
||||
}
|
||||
|
||||
fn failed(e: impl std::fmt::Display) -> HostError {
|
||||
HostError::Failed(e.to_string())
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ mod providers;
|
||||
pub mod remote;
|
||||
pub mod remote_host;
|
||||
mod run_detectors;
|
||||
mod semantic_tokens;
|
||||
mod theme;
|
||||
mod types;
|
||||
pub mod ui_points;
|
||||
@@ -47,6 +48,7 @@ pub use market::{
|
||||
pub use points::{COMMANDS, CommandDecl, register_builtin_points};
|
||||
pub use providers::{ProviderKind, set_editor_providers};
|
||||
pub(crate) use providers::{editor_plugin_host, editor_providers as editor_providers_for};
|
||||
pub(crate) use semantic_tokens::merge as merge_semantic_tokens;
|
||||
pub use theme::{ThemeDef, ThemeKind};
|
||||
pub use types::*;
|
||||
|
||||
@@ -59,7 +61,8 @@ use ide_extension::{
|
||||
use ide_language::plugin_point::PluginLanguages;
|
||||
use ide_language::{LanguageConfig, ProgramPin};
|
||||
use ide_plugin::{
|
||||
Actor, ActorError, CANCELLED, CallError, HostApi, Invocation, Limits, PluginEngine, Runtime, RuntimeSetup,
|
||||
Actor, ActorError, CANCELLED, CallError, HostApi, HostError, Invocation, Limits, PluginEngine, Runtime,
|
||||
RuntimeSetup,
|
||||
};
|
||||
use parking_lot::{Condvar, Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -1074,6 +1077,66 @@ impl PluginHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// The Services pane of node `key` of the plugin's `location = "services"`
|
||||
/// view `view`.
|
||||
pub fn service_detail(
|
||||
&self,
|
||||
id: &str,
|
||||
view: &str,
|
||||
key: &str,
|
||||
invocation: Invocation,
|
||||
) -> IdeResult<Vec<ide_plugin::ServiceTab>> {
|
||||
self.services_view(id, view)?;
|
||||
let (view, key) = (view.to_owned(), key.to_owned());
|
||||
self.code_call(id, invocation, "rendering the service's pane", move |rt, inv| {
|
||||
rt.service_detail(&view, &key, inv)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the program of the log tab `tab` of node `key`'s pane, with the
|
||||
/// arguments of the toggles in `on`, streaming its output until it exits
|
||||
/// or `cancel` fires; returns its exit code. The pane is asked of the
|
||||
/// plugin again, so the UI never names what runs. Needs the plugin's
|
||||
/// `process:<program>` grant.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn stream_service_log(
|
||||
&self,
|
||||
id: &str,
|
||||
view: &str,
|
||||
key: &str,
|
||||
tab: &str,
|
||||
on: &[String],
|
||||
invocation: Invocation,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
on_line: &dyn Fn(PluginOutputLine),
|
||||
) -> IdeResult<Option<i32>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let cwd = invocation.workspace_root.clone();
|
||||
let tabs = self.service_detail(id, view, key, invocation)?;
|
||||
let Some(ide_plugin::ServicePane::Log(log)) = tabs.into_iter().find(|t| t.id == tab).map(|t| t.body) else {
|
||||
return Err(IdeError::not_found(format!("the pane of {key:?} has no log tab {tab:?}")));
|
||||
};
|
||||
let toggled = log.toggles.into_iter().filter(|t| on.contains(&t.id)).flat_map(|t| t.args);
|
||||
let args: Vec<String> = log.args.into_iter().chain(toggled).collect();
|
||||
let plugin =
|
||||
self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("plugin {id:?}")))?;
|
||||
let cap = Capability::Process(log.program.clone());
|
||||
if !plugin.meta.lock().granted.iter().any(|g| g.covers(&cap)) {
|
||||
let denied = HostError::Denied(cap.to_string()).to_string();
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, denied));
|
||||
}
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
api.stream_process(&log.program, args, cwd.as_deref(), cancel, on_line).map_err(|e| match e {
|
||||
HostError::Cancelled => IdeError::cancelled(),
|
||||
e @ HostError::Denied(_) => IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e.to_string()),
|
||||
HostError::NotFound(m) => IdeError::not_found(m),
|
||||
HostError::Invalid(m) => IdeError::invalid(m),
|
||||
e => IdeError::unavailable(e.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
fn declared_view(&self, id: &str, view: &str) -> IdeResult<()> {
|
||||
let declared = [ui_points::VIEWS, ui_points::CUSTOM_EDITORS]
|
||||
.iter()
|
||||
@@ -1081,6 +1144,19 @@ impl PluginHost {
|
||||
if declared { Ok(()) } else { Err(IdeError::not_found(format!("plugin {id:?} declares no view {view:?}"))) }
|
||||
}
|
||||
|
||||
fn services_view(&self, id: &str, view: &str) -> IdeResult<()> {
|
||||
let services = self
|
||||
.ui
|
||||
.items(ui_points::VIEWS, Some(id))
|
||||
.iter()
|
||||
.any(|i| i.key == view && i.decl["location"].as_str() == Some(ui_points::SERVICES_LOCATION));
|
||||
if services {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::not_found(format!("plugin {id:?} declares no services view {view:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// One call into a plugin's code for the UI: checks it may run (asking
|
||||
/// for missing consent), activates it, retries once when the instance was
|
||||
/// reclaimed meanwhile, and reports crashes.
|
||||
|
||||
@@ -37,6 +37,7 @@ pub enum ProviderKind {
|
||||
CodeActions,
|
||||
Definition,
|
||||
LineMarkers,
|
||||
SemanticTokens,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
@@ -112,6 +113,9 @@ impl ExtensionPoint for ProvidersPoint {
|
||||
if d.kinds.is_empty() || d.languages.is_empty() || d.languages.len() > 64 {
|
||||
return Err("contributes.providers: give `kinds` and 1–64 `languages`".into());
|
||||
}
|
||||
if d.kinds.contains(&ProviderKind::SemanticTokens) {
|
||||
pkg.manifest.needs_api("contributes.providers: semantic-tokens", 3)?;
|
||||
}
|
||||
for l in &d.languages {
|
||||
if l != "*"
|
||||
&& (l.is_empty()
|
||||
@@ -161,7 +165,7 @@ use super::{LoadedPlugin, PluginHost, PluginStatus};
|
||||
use ide_core::CancellationToken;
|
||||
use ide_plugin::{
|
||||
ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending,
|
||||
ProviderDocument, Runtime,
|
||||
ProviderDocument, Runtime, SemanticToken,
|
||||
};
|
||||
use std::sync::Weak;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -331,6 +335,16 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn provide_semantic_tokens(&self, doc: &ProviderDocument) -> Vec<SemanticToken> {
|
||||
let d = Arc::new(doc.clone());
|
||||
self.edit_calls(ProviderKind::SemanticTokens, &doc.language, move |rt, timeout| {
|
||||
rt.provide_semantic_tokens(&d, timeout)
|
||||
})
|
||||
.into_iter()
|
||||
.flat_map(|(_, tokens)| tokens)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ghost text from the first plugin that has some. Not bound by the
|
||||
/// edit-path soft deadline (it may need the network) but by `cancel`:
|
||||
/// the editor cancels a request as soon as the user types on.
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
//! The commands a window needs at run time (`plugin_run_command`,
|
||||
//! `plugin_post_events`, `plugin_event_kinds`, `plugin_status_items`,
|
||||
//! `plugin_context_keys`, `plugin_cancel_task`, `plugin_answer_prompt`, `plugin_set_active_file`,
|
||||
//! `plugin_line_markers`, `plugin_view_render`, `plugin_view_event`)
|
||||
//! `plugin_line_markers`, `plugin_view_render`, `plugin_view_event`, `plugin_service_detail`,
|
||||
//! `plugin_service_log`)
|
||||
//! carry the desktop commands' names and arguments, so a remote window's UI
|
||||
//! routes them here unchanged. Plugin results come back as `plugin`
|
||||
//! notifications ([`PluginEventMessage`]); secrets stay in the desktop's
|
||||
@@ -465,6 +466,40 @@ impl RemotePlugins {
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_service_detail", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
super::views::service_detail(
|
||||
&c.host,
|
||||
alive(&h)?,
|
||||
&c.window,
|
||||
c.arg("pluginId")?,
|
||||
c.arg("view")?,
|
||||
c.arg("key")?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_service_log", move |c| {
|
||||
let h = h.clone();
|
||||
async move {
|
||||
super::views::service_log(
|
||||
&c.host,
|
||||
alive(&h)?,
|
||||
&c.window,
|
||||
c.arg("pluginId")?,
|
||||
c.arg("view")?,
|
||||
c.arg("key")?,
|
||||
c.arg("tab")?,
|
||||
c.arg("on")?,
|
||||
c.arg("request")?,
|
||||
c.sender("onLine")?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let h = host.clone();
|
||||
d.add("plugin_navigation_files", move |c| {
|
||||
let h = h.clone();
|
||||
async move { super::index_ops::plugin_navigation_files(&c.host, alive(&h)?, &c.window).await }
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
use ide_lsp::types::SemanticTokens;
|
||||
use ide_plugin::SemanticToken;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(crate) fn merge(server: Option<SemanticTokens>, plugin: Vec<SemanticToken>) -> SemanticTokens {
|
||||
let mut out = server.unwrap_or_else(|| SemanticTokens {
|
||||
data: Vec::new(),
|
||||
token_types: Vec::new(),
|
||||
token_modifiers: Vec::new(),
|
||||
});
|
||||
let mut added: Vec<[u32; 5]> = Vec::with_capacity(plugin.len());
|
||||
let mut lines: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();
|
||||
for token in plugin {
|
||||
let (start, end) = (token.range.start, token.range.end);
|
||||
if start.line != end.line || end.col <= start.col {
|
||||
continue;
|
||||
}
|
||||
let kind = camel_case(&token.kind);
|
||||
let kind = match out.token_types.iter().position(|t| *t == kind) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
out.token_types.push(kind);
|
||||
out.token_types.len() - 1
|
||||
}
|
||||
};
|
||||
let mut bits = 0u32;
|
||||
for modifier in &token.modifiers {
|
||||
let modifier = camel_case(modifier);
|
||||
let i = match out.token_modifiers.iter().position(|m| *m == modifier) {
|
||||
Some(i) => i,
|
||||
None if out.token_modifiers.len() < 32 => {
|
||||
out.token_modifiers.push(modifier);
|
||||
out.token_modifiers.len() - 1
|
||||
}
|
||||
None => continue,
|
||||
};
|
||||
bits |= 1 << i;
|
||||
}
|
||||
lines.entry(start.line).or_default().push((start.col, end.col));
|
||||
added.push([start.line, start.col, end.col - start.col, kind as u32, bits]);
|
||||
}
|
||||
let covered = |t: &[u32; 5]| {
|
||||
lines.get(&t[0]).is_some_and(|ranges| ranges.iter().any(|&(from, to)| t[1] < to && from < t[1] + t[2]))
|
||||
};
|
||||
let mut data: Vec<[u32; 5]> = out.data.as_chunks::<5>().0.iter().filter(|t| !covered(t)).copied().collect();
|
||||
data.extend(added);
|
||||
data.sort_by_key(|t| (t[0], t[1]));
|
||||
out.data = data.into_iter().flatten().collect();
|
||||
out
|
||||
}
|
||||
|
||||
fn camel_case(name: &str) -> String {
|
||||
let mut out = String::with_capacity(name.len());
|
||||
let mut upper = false;
|
||||
for c in name.chars() {
|
||||
if c == '-' {
|
||||
upper = true;
|
||||
} else if upper {
|
||||
out.extend(c.to_uppercase());
|
||||
upper = false;
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Pos, Range};
|
||||
|
||||
fn token(line: u32, from: u32, to: u32, kind: &str, modifiers: &[&str]) -> SemanticToken {
|
||||
SemanticToken {
|
||||
range: Range::new(Pos::new(line, from), Pos::new(line, to)),
|
||||
kind: kind.into(),
|
||||
modifiers: modifiers.iter().map(|m| (*m).into()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn server() -> SemanticTokens {
|
||||
SemanticTokens {
|
||||
data: vec![0, 0, 6, 0, 0, 1, 4, 5, 1, 1, 1, 12, 3, 1, 0],
|
||||
token_types: vec!["variable".into(), "property".into()],
|
||||
token_modifiers: vec!["readonly".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_tokens_replace_the_server_tokens_they_overlap() {
|
||||
let merged = merge(Some(server()), vec![token(1, 6, 10, "method", &[])]);
|
||||
assert_eq!(merged.token_types, ["variable", "property", "method"]);
|
||||
assert_eq!(merged.data, [0, 0, 6, 0, 0, 1, 6, 4, 2, 0, 1, 12, 3, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_and_modifiers_use_the_lsp_names() {
|
||||
let merged = merge(None, vec![token(2, 0, 3, "type-parameter", &["default-library", "readonly"])]);
|
||||
assert_eq!(merged.token_types, ["typeParameter"]);
|
||||
assert_eq!(merged.token_modifiers, ["defaultLibrary", "readonly"]);
|
||||
assert_eq!(merged.data, [2, 0, 3, 0, 0b11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_names_reuse_the_server_legend() {
|
||||
let merged = merge(Some(server()), vec![token(3, 1, 2, "property", &["readonly"])]);
|
||||
assert_eq!(merged.token_types.len(), 2);
|
||||
assert_eq!(merged.token_modifiers.len(), 1);
|
||||
assert_eq!(merged.data[15..], [3, 1, 1, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_spanning_lines_or_empty_are_ignored() {
|
||||
let multi = SemanticToken {
|
||||
range: Range::new(Pos::new(0, 4), Pos::new(1, 2)),
|
||||
kind: "method".into(),
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
let merged = merge(Some(server()), vec![multi, token(0, 3, 3, "method", &[])]);
|
||||
assert_eq!(merged.data, server().data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_past_thirty_two_are_dropped() {
|
||||
let names: Vec<String> = (0..40).map(|i| format!("m{i}")).collect();
|
||||
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let merged = merge(None, vec![token(0, 0, 1, "type", &refs)]);
|
||||
assert_eq!(merged.token_modifiers.len(), 32);
|
||||
assert_eq!(merged.data[4], u32::MAX);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,14 @@ pub use ide_plugin::{
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// A line a view's `process` body printed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginOutputLine {
|
||||
pub stderr: bool,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PluginSource {
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
//! id = "jobs"
|
||||
//! title = "Jobs"
|
||||
//! icon = "server"
|
||||
//! location = "right" # left, right, bottom
|
||||
//! location = "right" # left, right, bottom, services (nodes of the Services tool window)
|
||||
//!
|
||||
//! [[contributes.customEditors]]
|
||||
//! id = "table"
|
||||
@@ -55,6 +55,9 @@ use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A view whose tree shows in the Services tool window; the plugin's
|
||||
/// `service-provider` renders the selected node's pane.
|
||||
pub const SERVICES_LOCATION: &str = "services";
|
||||
pub const MENUS: &str = "menus";
|
||||
pub const KEYMAPS: &str = "keymaps";
|
||||
pub const STATUS_BAR: &str = "statusBar";
|
||||
@@ -395,8 +398,14 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
validate_item_id(&d.id, "view id")?;
|
||||
title(VIEWS, &d.title)?;
|
||||
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
|
||||
if !["left", "right", "bottom"].contains(&d.location.as_str()) {
|
||||
return Err(format!("view {:?}: `location` is left, right or bottom", d.id));
|
||||
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
|
||||
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
|
||||
}
|
||||
if d.location == SERVICES_LOCATION {
|
||||
pkg.manifest.needs_api(&format!("view {:?}: `location = \"services\"`", d.id), 3)?;
|
||||
if d.web.is_some() {
|
||||
return Err(format!("view {:?}: a services view is rendered by the plugin's code (no `web`)", d.id));
|
||||
}
|
||||
}
|
||||
if d.icon.as_ref().is_some_and(|i| i.len() > 64) {
|
||||
return Err(format!("view {:?}: icon names are up to 64 bytes", d.id));
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Declarative views and custom editors as the
|
||||
//! window commands `plugin_view_render` / `plugin_view_event` serve them —
|
||||
//! window commands `plugin_view_render` / `plugin_view_event` (and, for services views,
|
||||
//! `plugin_service_detail` / `plugin_service_log`) serve them —
|
||||
//! the desktop for local projects, `openidea-server` for remote ones.
|
||||
|
||||
use super::{PluginEditor, PluginHost};
|
||||
use super::{PluginEditor, PluginHost, PluginOutputLine};
|
||||
use ide_core::{DocId, IdeError, IdeResult};
|
||||
use ide_plugin::{EditorContext, Invocation, View, ViewEvent, Viewport};
|
||||
use ide_plugin::{EditorContext, Invocation, ServiceTab, View, ViewEvent, Viewport};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The window's project, plus the editor the call is about: the document a
|
||||
@@ -67,6 +68,47 @@ pub async fn event(
|
||||
blocking(move || plugins.view_event(&plugin_id, &view, event, invocation)).await
|
||||
}
|
||||
|
||||
/// The Services pane of node `key` of a plugin's services view.
|
||||
pub async fn service_detail(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
view: String,
|
||||
key: String,
|
||||
) -> IdeResult<Vec<ServiceTab>> {
|
||||
let invocation = view_invocation(host, window, None, None)?;
|
||||
blocking(move || plugins.service_detail(&plugin_id, &view, &key, invocation)).await
|
||||
}
|
||||
|
||||
/// Runs the program of the log tab `tab` of node `key`'s pane in the window's
|
||||
/// project root, streaming its lines until it exits or request `request` is
|
||||
/// cancelled; returns its exit code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn service_log(
|
||||
host: &crate::Host,
|
||||
plugins: Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
view: String,
|
||||
key: String,
|
||||
tab: String,
|
||||
on: Vec<String>,
|
||||
request: ide_core::RequestId,
|
||||
on_line: crate::ops::Channel<PluginOutputLine>,
|
||||
) -> IdeResult<Option<i32>> {
|
||||
let invocation = view_invocation(host, window, None, None)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
plugins.stream_service_log(&plugin_id, &view, &key, &tab, &on, invocation, &cancel, &|line| {
|
||||
let _ = on_line.send(line);
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -284,6 +284,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "agent_commands"
|
||||
| "agent_unqueue"
|
||||
| "agent_cancel"
|
||||
| "agent_stop_background"
|
||||
| "agent_archive"
|
||||
| "agent_unarchive"
|
||||
| "agent_registry_list"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use ide_host::plugins::{Consent, PluginHost};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/semantic-tokens")
|
||||
}
|
||||
|
||||
fn host(dir: &Path) -> PluginHost {
|
||||
let limits = Limits { edit_soft: Duration::from_secs(5), edit_hard: Duration::from_secs(10), ..Limits::default() };
|
||||
PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()
|
||||
}
|
||||
|
||||
fn doc(dir: &Path, language: &str, text: &str) -> ProviderDocument {
|
||||
ProviderDocument { path: dir.join("Order.php"), language: language.into(), version: 1, text: text.into() }
|
||||
}
|
||||
|
||||
const ORDER: &str =
|
||||
"<?php\nclass Order\n{\n public function user() {}\n}\n$order->user;\n$order->total;\n$order->user();\n";
|
||||
|
||||
#[test]
|
||||
fn relation_accesses_and_columns_get_their_own_kinds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
let tokens = host.provide_semantic_tokens(&doc(tmp.path(), "php", ORDER));
|
||||
let found: Vec<_> = tokens
|
||||
.iter()
|
||||
.map(|t| (t.range.start.line, t.range.start.col, t.range.end.line, t.range.end.col, t.kind.as_str()))
|
||||
.collect();
|
||||
assert_eq!(found, [(5, 8, 5, 12, "method"), (6, 8, 6, 13, "property")]);
|
||||
assert!(tokens.iter().all(|t| t.modifiers.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_declared_languages_are_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap();
|
||||
assert!(host.provide_semantic_tokens(&doc(tmp.path(), "javascript", "a->b")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_needs_plugin_api_1_3() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = host(tmp.path());
|
||||
let pkg = tmp.path().join("old");
|
||||
std::fs::create_dir_all(pkg.join("dist")).unwrap();
|
||||
std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap();
|
||||
let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap();
|
||||
std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.3\"", "\"^1.0\"")).unwrap();
|
||||
let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.3"), "{}", err.message);
|
||||
}
|
||||
@@ -2811,6 +2811,188 @@ fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
|
||||
assert_eq!((d[0].unnecessary, d[0].deprecated, d[0].source.as_deref()), (true, false, Some("lint")));
|
||||
}
|
||||
|
||||
/// `hello` as a services view, which needs API 1.3.
|
||||
fn services_variant(text: &str) -> String {
|
||||
text.replace("location = \"right\"", "location = \"services\"")
|
||||
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.3\"")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn services_views_need_api_1_3_and_code() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let info = f.install(&hello_variant(tmp.path(), services_variant));
|
||||
assert!(info.error.is_none(), "{:?}", info.error);
|
||||
assert_eq!(f.host.ui_items("views").remove(0).decl["location"].as_str(), Some("services"));
|
||||
|
||||
for (edit, message) in [
|
||||
(
|
||||
Box::new(|t: &str| t.replace("location = \"right\"", "location = \"services\""))
|
||||
as Box<dyn Fn(&str) -> String>,
|
||||
"new in plugin API 1.3",
|
||||
),
|
||||
(
|
||||
Box::new(|t: &str| t.replace("location = \"right\"", "location = \"middle\"")),
|
||||
"left, right, bottom or services",
|
||||
),
|
||||
(
|
||||
Box::new(|t: &str| {
|
||||
services_variant(t)
|
||||
.replace("location = \"services\"", "location = \"services\"\nweb = \"web/index.html\"")
|
||||
}),
|
||||
"a services view is rendered by the plugin's code (no `web`)",
|
||||
),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = hello_variant(tmp.path(), edit);
|
||||
std::fs::create_dir_all(pkg.join("web")).unwrap();
|
||||
std::fs::write(pkg.join("web/index.html"), "<p>x</p>").unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains(message), "{message}: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn services_views_have_a_detail_pane() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
f.install(&hello_variant(tmp.path(), services_variant));
|
||||
let tabs = f.host.service_detail("hello", "greetings", "pod:default/nginx", f.inv()).unwrap();
|
||||
assert_eq!(tabs.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(), ["log", "info"]);
|
||||
assert_eq!(tabs[1].body, ide_plugin::ServicePane::Text("greetings: pod:default/nginx".into()));
|
||||
let ide_plugin::ServicePane::Log(log) = &tabs[0].body else { panic!("a log: {:?}", tabs[0].body) };
|
||||
assert_eq!(
|
||||
(log.program.as_str(), log.args.as_slice()),
|
||||
("sh", ["-c".to_owned(), "pod:default/nginx".to_owned()].as_slice())
|
||||
);
|
||||
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("hello"));
|
||||
let err = f.host.service_detail("hello", "greetings", "x", f.inv()).unwrap_err();
|
||||
assert!(err.message.contains("declares no services view"), "a right view has no pane: {err:?}");
|
||||
}
|
||||
|
||||
/// `hello` as a services view that may run `sh`, granted or not.
|
||||
#[cfg(unix)]
|
||||
fn services_with_sh(f: &Fixture, dir: &Path, grant: bool) {
|
||||
let sh = PathBuf::from("/bin");
|
||||
f.host.set_program_path(Arc::new(move || Some(sh.clone().into_os_string())));
|
||||
let pkg = hello_variant(dir, |t| {
|
||||
services_variant(t).replace(
|
||||
"required = [\"editor.read\", \"editor.write\"]",
|
||||
"required = [\"editor.read\", \"editor.write\"]\noptional = [\"process:sh\"]",
|
||||
)
|
||||
});
|
||||
f.install(&pkg);
|
||||
f.host.set_capability("hello", "process:sh", grant).unwrap();
|
||||
}
|
||||
|
||||
/// Follows the Log tab of the node whose key is `script`.
|
||||
#[cfg(unix)]
|
||||
fn stream(
|
||||
f: &Fixture,
|
||||
script: &str,
|
||||
on: &[&str],
|
||||
cancel: &ide_core::CancellationToken,
|
||||
lines: impl Fn(PluginOutputLine),
|
||||
) -> ide_core::IdeResult<Option<i32>> {
|
||||
let on: Vec<String> = on.iter().map(|s| (*s).to_owned()).collect();
|
||||
f.host.stream_service_log("hello", "greetings", script, "log", &on, f.inv(), cancel, &lines)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn service_logs_stream_lines_with_the_toggles_args() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
services_with_sh(&f, tmp.path(), true);
|
||||
let lines = Mutex::new(Vec::new());
|
||||
let script = "printf 'a\\nb\\n'; printf 'e\\n' >&2; exit 3";
|
||||
let status = stream(&f, script, &[], &Default::default(), |l| lines.lock().push(l));
|
||||
assert_eq!(status.unwrap(), Some(3));
|
||||
let mut lines = lines.into_inner();
|
||||
lines.sort_by_key(|l| l.stderr);
|
||||
let line = |stderr: bool, text: &str| PluginOutputLine { stderr, text: text.into() };
|
||||
assert_eq!(lines, [line(false, "a"), line(false, "b"), line(true, "e")]);
|
||||
|
||||
// `sh -c script arg` names the script `arg` ($0): the toggle's args are appended.
|
||||
let named = Mutex::new(Vec::new());
|
||||
stream(&f, "echo $0", &["named"], &Default::default(), |l| named.lock().push(l.text)).unwrap();
|
||||
assert_eq!(named.into_inner(), ["named"]);
|
||||
|
||||
let long = Mutex::new(Vec::new());
|
||||
stream(&f, "head -c 40000 /dev/zero | tr '\\0' x; echo; echo next", &[], &Default::default(), |l| {
|
||||
long.lock().push(l.text.len())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(long.into_inner(), [16 << 10, 4], "a long line is cut, the next one is whole");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn service_logs_need_the_grant_and_a_log_tab() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
services_with_sh(&f, tmp.path(), false);
|
||||
let marker = tmp.path().join("ran");
|
||||
let script = format!("touch {}", marker.display());
|
||||
let err = stream(&f, &script, &[], &Default::default(), |_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::PermissionDenied);
|
||||
assert!(err.message.contains("permission denied: process:sh is not granted"), "{err:?}");
|
||||
assert!(!marker.exists(), "nothing was started");
|
||||
|
||||
f.host.set_capability("hello", "process:sh", true).unwrap();
|
||||
let info =
|
||||
f.host.stream_service_log("hello", "greetings", &script, "info", &[], f.inv(), &Default::default(), &|_| {});
|
||||
assert_eq!(info.unwrap_err().kind, ErrorKind::NotFound, "a text tab runs nothing");
|
||||
let cancelled = ide_core::CancellationToken::default();
|
||||
cancelled.cancel();
|
||||
assert_eq!(stream(&f, &script, &[], &cancelled, |_| {}).unwrap_err().kind, ErrorKind::Cancelled);
|
||||
assert!(!marker.exists(), "a cancelled request starts nothing");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn service_log_cancel_kills_the_child() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
services_with_sh(&f, tmp.path(), true);
|
||||
let cancel = ide_core::CancellationToken::default();
|
||||
let started = Instant::now();
|
||||
let result = stream(&f, "echo up; sleep 30.4321", &[], &cancel, |l| {
|
||||
if l.text == "up" {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert!(started.elapsed() < Duration::from_secs(2), "{:?}", started.elapsed());
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let orphan = || std::process::Command::new("pgrep").args(["-f", "sleep 30.4321"]).status().unwrap().success();
|
||||
assert!(eventually(|| !orphan()), "what the program started is killed too");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn service_log_stops_when_the_grant_is_revoked() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
services_with_sh(&f, tmp.path(), true);
|
||||
let started = Instant::now();
|
||||
let watchdog = ide_core::CancellationToken::default();
|
||||
let timer = watchdog.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
timer.cancel();
|
||||
});
|
||||
let result = stream(&f, "while :; do echo tick; sleep 0.05; done", &[], &watchdog, |l| {
|
||||
if l.text == "tick" && started.elapsed() < Duration::from_secs(1) {
|
||||
f.host.set_capability("hello", "process:sh", false).unwrap();
|
||||
}
|
||||
});
|
||||
assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
|
||||
let err = result.unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_set_their_own_context_keys() {
|
||||
let f = fixture(Limits::default());
|
||||
|
||||
@@ -151,7 +151,7 @@ async fn change_commit_branch_stash_and_merge_a_conflict() {
|
||||
assert!(ops::vcs::vcs_line_hunks(&f.host, WINDOW, lib_path.clone()).await.unwrap().is_empty());
|
||||
|
||||
// A branch changes the line its way.
|
||||
ops::vcs::vcs_create_branch(&f.host, WINDOW, None, "feature".into(), None, true).await.unwrap();
|
||||
ops::vcs::vcs_create_branch(&f.host, WINDOW, None, "feature".into(), None, true, None).await.unwrap();
|
||||
let theirs = "pub fn format_price(cents: u64) -> String { // feature";
|
||||
f.edit_line(lib, theirs).await;
|
||||
f.save(lib).await;
|
||||
|
||||
@@ -93,6 +93,16 @@ pub struct IndentConfig {
|
||||
pub insert_spaces: bool,
|
||||
}
|
||||
|
||||
/// Additions to the tsserver project of a tree without `tsconfig.json` / `jsconfig.json`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct TsserverProjectExtras {
|
||||
/// File extensions a tsserver plugin handles, registered with the sources (`vue`).
|
||||
pub extensions: Vec<String>,
|
||||
/// `compilerOptions.paths` with absolute targets: the bundler's module aliases
|
||||
/// (`@/*` → `<root>/src/*` in a Vue CLI project).
|
||||
pub paths: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct LanguageServerConfig {
|
||||
@@ -155,6 +165,9 @@ pub struct LanguageServerConfig {
|
||||
/// Register source files with tsserver when no project configuration exists.
|
||||
#[serde(default)]
|
||||
pub tsserver_project: bool,
|
||||
/// Set by the settings hook: what that registered project adds to its defaults.
|
||||
#[serde(skip)]
|
||||
pub tsserver_project_extras: TsserverProjectExtras,
|
||||
/// Re-sends the open documents (unchanged) once `workspace/configuration` is answered:
|
||||
/// the server (Intelephense) applies some settings, such as the PHP version, only when
|
||||
/// it parses a document.
|
||||
|
||||
@@ -639,6 +639,7 @@ mod tests {
|
||||
for (lang, servers) in [
|
||||
("python", vec!["basedpyright", "pyright", "ty", "pyrefly"]),
|
||||
("typescript", vec!["vtsls", "typescript-language-server"]),
|
||||
("java", vec!["jdtls", "kmp-lsp"]),
|
||||
] {
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
let got: Vec<(&str, bool)> = cfg
|
||||
|
||||
@@ -14,6 +14,8 @@ const SCAN_LIMIT: usize = 100_000;
|
||||
/// tsserver turns its language service off past 20 MiB of JavaScript in a project.
|
||||
const SCRIPT_BYTES_LIMIT: u64 = 16 << 20;
|
||||
const REFRESH_DELAY: Duration = Duration::from_millis(300);
|
||||
/// Bounds the loading phase reported after registering a project.
|
||||
const LOADING_LIMIT: Duration = Duration::from_secs(60);
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -47,7 +49,13 @@ fn is_source(ext: &str) -> bool {
|
||||
|
||||
/// All-or-nothing at the caps: a partial project could displace an inferred
|
||||
/// project while omitting some of its files. Configured trees stay with tsserver.
|
||||
fn source_files(root: &Path, exclude_root: &Path, excludes: Vec<String>, limit: usize) -> Vec<PathBuf> {
|
||||
fn source_files(
|
||||
root: &Path,
|
||||
exclude_root: &Path,
|
||||
excludes: Vec<String>,
|
||||
extra: &[String],
|
||||
limit: usize,
|
||||
) -> Vec<PathBuf> {
|
||||
if root.ancestors().any(configured) {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -80,8 +88,9 @@ fn source_files(root: &Path, exclude_root: &Path, excludes: Vec<String>, limit:
|
||||
return Vec::new();
|
||||
}
|
||||
let ext = entry.path().extension().and_then(|s| s.to_str()).unwrap_or_default();
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) && is_source(ext) {
|
||||
if is_script(ext) {
|
||||
let plugin = extra.iter().any(|e| e == ext);
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) && (is_source(ext) || plugin) {
|
||||
if is_script(ext) || plugin {
|
||||
script_bytes += entry.metadata().map_or(0, |m| m.len());
|
||||
if script_bytes > SCRIPT_BYTES_LIMIT {
|
||||
tracing::debug!("external TypeScript project exceeds its script size; retaining inferred projects");
|
||||
@@ -104,16 +113,22 @@ fn project_name(server: &Server) -> PathBuf {
|
||||
}
|
||||
|
||||
async fn request(run: &Running, command: &str, args: Value) -> bool {
|
||||
send(run, command, args, false, TIMEOUT).await
|
||||
}
|
||||
|
||||
/// `is_async`: a command tsserver answers with events, such as `geterr` (vtsls returns once
|
||||
/// they all arrived).
|
||||
async fn send(run: &Running, command: &str, args: Value, is_async: bool, timeout: Duration) -> bool {
|
||||
let request = run.peer.request::<_, Value>(
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"command": COMMAND,
|
||||
"arguments": [command, args, { "isAsync": false, "expectsResult": true }]
|
||||
"arguments": [command, args, { "isAsync": is_async, "expectsResult": true }]
|
||||
}),
|
||||
None,
|
||||
);
|
||||
match tokio::time::timeout(TIMEOUT, request).await {
|
||||
Ok(Ok(result)) if result.get("success").and_then(Value::as_bool) == Some(true) => true,
|
||||
match tokio::time::timeout(timeout, request).await {
|
||||
Ok(Ok(result)) if is_async || result.get("success").and_then(Value::as_bool) == Some(true) => true,
|
||||
result => {
|
||||
tracing::debug!("tsserver {command}: {result:?}");
|
||||
false
|
||||
@@ -126,7 +141,7 @@ impl LspManager {
|
||||
*self.excludes_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_external_project(&self, server: &Server, run: &Running) {
|
||||
pub(crate) async fn refresh_external_project(&self, server: &Arc<Server>, run: &Running) {
|
||||
if !supported(server, run) {
|
||||
return;
|
||||
}
|
||||
@@ -135,11 +150,13 @@ impl LspManager {
|
||||
*state = State { generation: run.generation, files: Vec::new() };
|
||||
server.external_diagnostics.store(false, Ordering::Release);
|
||||
}
|
||||
let extras = server.effective_config().tsserver_project_extras;
|
||||
let root = server.root.clone();
|
||||
let exclude_root = self.project_root_for(&root);
|
||||
let hook = self.excludes_hook.read().clone();
|
||||
let extensions = extras.extensions.clone();
|
||||
let files = tokio::task::spawn_blocking(move || {
|
||||
source_files(&root, &exclude_root, hook.map(|h| h()).unwrap_or_default(), LIMIT)
|
||||
source_files(&root, &exclude_root, hook.map(|h| h()).unwrap_or_default(), &extensions, LIMIT)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
@@ -155,17 +172,19 @@ impl LspManager {
|
||||
}
|
||||
server.external_diagnostics.store(true, Ordering::Release);
|
||||
let roots: Vec<_> = files.iter().map(|p| json!({ "fileName": p })).collect();
|
||||
// What an inferred project assumes, so sharing a project changes no diagnostics.
|
||||
let mut options = json!({ "allowJs": true, "target": "ES2022", "module": "ESNext",
|
||||
"moduleResolution": "Node", "allowNonTsExtensions": true, "jsx": "preserve",
|
||||
"allowSyntheticDefaultImports": true, "strictNullChecks": true,
|
||||
"strictFunctionTypes": true, "moduleDetection": "force" });
|
||||
// Absolute targets need no `baseUrl` (deprecated in TypeScript 6).
|
||||
if !extras.paths.is_empty() {
|
||||
options["paths"] = json!(extras.paths);
|
||||
}
|
||||
if request(
|
||||
run,
|
||||
"openExternalProject",
|
||||
json!({
|
||||
"projectFileName": project_name(server), "rootFiles": roots,
|
||||
// What an inferred project assumes, so sharing a project changes no diagnostics.
|
||||
"options": { "allowJs": true, "target": "ES2022", "module": "ESNext",
|
||||
"moduleResolution": "Node", "allowNonTsExtensions": true, "jsx": "preserve",
|
||||
"allowSyntheticDefaultImports": true, "strictNullChecks": true,
|
||||
"strictFunctionTypes": true, "moduleDetection": "force" }
|
||||
}),
|
||||
json!({ "projectFileName": project_name(server), "rootFiles": roots, "options": options }),
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -175,24 +194,32 @@ impl LspManager {
|
||||
files.len(),
|
||||
server.root.display()
|
||||
);
|
||||
if state.files.is_empty() {
|
||||
self.await_external_project(server, run.generation, files[0].clone());
|
||||
}
|
||||
state.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-registers config-less projects after sources or configurations changed on disk.
|
||||
pub fn project_files_changed<'a>(&self, paths: impl IntoIterator<Item = &'a PathBuf>) {
|
||||
let relevant = paths.into_iter().any(|p| {
|
||||
p.extension().and_then(|s| s.to_str()).is_some_and(is_source)
|
||||
|| p.file_name().is_some_and(|n| n == "tsconfig.json" || n == "jsconfig.json")
|
||||
});
|
||||
if !relevant {
|
||||
return;
|
||||
}
|
||||
for server in self.servers.lock().iter().filter(|s| s.config.tsserver_project) {
|
||||
let paths: Vec<&PathBuf> = paths.into_iter().collect();
|
||||
let servers: Vec<_> = self.servers.lock().iter().filter(|s| s.config.tsserver_project).cloned().collect();
|
||||
for server in servers {
|
||||
let extensions = server.effective_config().tsserver_project_extras.extensions;
|
||||
let relevant = paths.iter().any(|p| {
|
||||
p.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.is_some_and(|ext| is_source(ext) || extensions.iter().any(|e| e == ext))
|
||||
|| p.file_name().is_some_and(|n| n == "tsconfig.json" || n == "jsconfig.json")
|
||||
});
|
||||
if !relevant {
|
||||
continue;
|
||||
}
|
||||
if server.external_refresh_queued.swap(true, Ordering::AcqRel) {
|
||||
continue;
|
||||
}
|
||||
let (me, server) = (self.me.clone(), server.clone());
|
||||
let me = self.me.clone();
|
||||
self.runtime.spawn(async move {
|
||||
tokio::time::sleep(REFRESH_DELAY).await;
|
||||
server.external_refresh_queued.store(false, Ordering::Release);
|
||||
@@ -203,6 +230,36 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// vtsls answers requests from its single-file syntax server until the semantic server
|
||||
/// reports a project loaded or diagnostics; a project registered this way reports no
|
||||
/// loading, so the first usage counts would all be zero. Until the diagnostics of an open
|
||||
/// file arrive, the server is loading: empty answers are incomplete and asked again.
|
||||
fn await_external_project(&self, server: &Arc<Server>, generation: u64, fallback: PathBuf) {
|
||||
server.external_loading.store(generation, Ordering::Release);
|
||||
server.set_loading(&self.sink, true);
|
||||
let (me, server) = (self.me.clone(), server.clone());
|
||||
self.runtime.spawn(async move {
|
||||
// Documents are (re)opened once the instance is ready. An unopened file has no
|
||||
// project in tsserver until one of its files is opened: no diagnostics come.
|
||||
if let Some(run) = server.wait_ready(LOADING_LIMIT).await.filter(|r| r.generation == generation)
|
||||
&& let Some(file) = me.upgrade().map(|me| {
|
||||
me.docs
|
||||
.lock()
|
||||
.values()
|
||||
.find(|d| d.servers.iter().any(|a| a.server.id == server.id))
|
||||
.map_or(fallback, |d| d.path.clone())
|
||||
})
|
||||
{
|
||||
send(&run, "geterr", json!({ "files": [file], "delay": 0 }), true, LOADING_LIMIT).await;
|
||||
}
|
||||
if server.external_loading.compare_exchange(generation, 0, Ordering::AcqRel, Ordering::Acquire).is_ok()
|
||||
&& let Some(me) = me.upgrade()
|
||||
{
|
||||
server.set_loading(&me.sink, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) async fn close_external_project(&self, server: &Server, run: &Running) {
|
||||
let mut state = server.external_project.lock().await;
|
||||
if state.generation == run.generation && !state.files.is_empty() {
|
||||
@@ -241,17 +298,32 @@ mod tests {
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
|
||||
assert_eq!(
|
||||
source_files(root, root, vec!["excluded".into()], LIMIT),
|
||||
source_files(root, root, vec!["excluded".into()], &[], LIMIT),
|
||||
vec![root.join("a.ts"), root.join("src/b.js"), root.join("src/c.tsx")]
|
||||
);
|
||||
assert!(source_files(root, root, vec![], 1).is_empty());
|
||||
assert!(source_files(root, root, vec![], &[], 1).is_empty());
|
||||
std::fs::File::create(root.join("large.js")).unwrap().set_len(SCRIPT_BYTES_LIMIT + 1).unwrap();
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
assert!(source_files(root, root, vec![], &[], LIMIT).is_empty());
|
||||
std::fs::remove_file(root.join("large.js")).unwrap();
|
||||
std::fs::File::create(root.join("large.ts")).unwrap().set_len(SCRIPT_BYTES_LIMIT + 1).unwrap();
|
||||
assert_eq!(source_files(root, root, vec!["excluded".into()], LIMIT).len(), 4);
|
||||
assert_eq!(source_files(root, root, vec!["excluded".into()], &[], LIMIT).len(), 4);
|
||||
std::fs::remove_file(root.join("large.ts")).unwrap();
|
||||
assert_eq!(source_files(&root.join("src"), root, vec![], LIMIT).len(), 2);
|
||||
assert_eq!(source_files(&root.join("src"), root, vec![], &[], LIMIT).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_extensions_join_the_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for path in ["src/main.js", "src/App.vue", "src/page.svelte"] {
|
||||
write(dir.path(), path);
|
||||
}
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], &[], LIMIT), vec![dir.path().join("src/main.js")]);
|
||||
assert_eq!(
|
||||
source_files(dir.path(), dir.path(), vec![], &["vue".into()], LIMIT),
|
||||
vec![dir.path().join("src/App.vue"), dir.path().join("src/main.js")]
|
||||
);
|
||||
std::fs::File::create(dir.path().join("src/Big.vue")).unwrap().set_len(SCRIPT_BYTES_LIMIT + 1).unwrap();
|
||||
assert!(source_files(dir.path(), dir.path(), vec![], &["vue".into()], LIMIT).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -261,13 +333,13 @@ mod tests {
|
||||
let root = dir.path();
|
||||
write(root, "a.ts");
|
||||
write(root, "pkg/b.js");
|
||||
assert_eq!(source_files(root, root, vec![], LIMIT).len(), 2);
|
||||
assert_eq!(source_files(root, root, vec![], &[], LIMIT).len(), 2);
|
||||
write(root, &format!("pkg/{name}"));
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
assert!(source_files(root, root, vec![], &[], LIMIT).is_empty());
|
||||
std::fs::remove_file(root.join("pkg").join(name)).unwrap();
|
||||
write(root, name);
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
assert!(source_files(&root.join("pkg"), root, vec![], LIMIT).is_empty());
|
||||
assert!(source_files(root, root, vec![], &[], LIMIT).is_empty());
|
||||
assert!(source_files(&root.join("pkg"), root, vec![], &[], LIMIT).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,12 +347,12 @@ mod tests {
|
||||
fn additions_deletions_and_renames_change_membership() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "a.js");
|
||||
let first = source_files(dir.path(), dir.path(), vec![], LIMIT);
|
||||
let first = source_files(dir.path(), dir.path(), vec![], &[], LIMIT);
|
||||
write(dir.path(), "b.ts");
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], LIMIT).len(), 2);
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], &[], LIMIT).len(), 2);
|
||||
std::fs::rename(dir.path().join("b.ts"), dir.path().join("b.txt")).unwrap();
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], LIMIT), first);
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], &[], LIMIT), first);
|
||||
std::fs::remove_file(dir.path().join("a.js")).unwrap();
|
||||
assert!(source_files(dir.path(), dir.path(), vec![], LIMIT).is_empty());
|
||||
assert!(source_files(dir.path(), dir.path(), vec![], &[], LIMIT).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -797,6 +797,9 @@ impl LspManager {
|
||||
if server.name == "gopls" {
|
||||
params["capabilities"]["experimental"]["interactiveResolve"] = json!({ "inputTypes": ["string"] });
|
||||
}
|
||||
if server.name == "csharp-ls" {
|
||||
params["capabilities"]["experimental"]["csharp"]["metadataUris"] = json!(true);
|
||||
}
|
||||
if !init_options.is_null() {
|
||||
params["initializationOptions"] = init_options;
|
||||
}
|
||||
@@ -1092,7 +1095,15 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
timeout: Duration,
|
||||
) -> IdeResult<R> {
|
||||
let fut = t.run.peer.request::<P, R>(method, params, cancel.cloned());
|
||||
let fut = async {
|
||||
if t.server.name == "csharp-ls" {
|
||||
let mut value = t.run.peer.request::<P, Value>(method, params, cancel.cloned()).await?;
|
||||
virtual_doc::normalize_csharp_uris(&mut value);
|
||||
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
|
||||
} else {
|
||||
t.run.peer.request::<P, R>(method, params, cancel.cloned()).await
|
||||
}
|
||||
};
|
||||
match tokio::time::timeout(timeout, fut).await {
|
||||
Ok(r) => r.map_err(|e| rpc_err(&t.server.name, method, e)),
|
||||
Err(_) => Err(rpc_err(&t.server.name, method, RpcError::Timeout)),
|
||||
@@ -1353,8 +1364,14 @@ impl LspManager {
|
||||
let mut first = Vec::new();
|
||||
if method == "textDocument/implementation" {
|
||||
let (locs, complete) = self.java_source_implementations(snap, t, pos, cancel).await;
|
||||
if complete && !locs.is_empty() {
|
||||
return Ok(locs);
|
||||
// A type declared in the sources has no implementations in the dependencies:
|
||||
// none found there is the whole answer, without a type hierarchy over every jar.
|
||||
if complete {
|
||||
if !locs.is_empty() {
|
||||
return Ok(locs);
|
||||
}
|
||||
out.value = Some(Vec::new());
|
||||
continue;
|
||||
}
|
||||
if let Some(partial) = partial
|
||||
&& !locs.is_empty()
|
||||
@@ -1412,9 +1429,9 @@ impl LspManager {
|
||||
self.references_streaming(doc, pos, include_declaration, project_wide, true, cancel, None).await
|
||||
}
|
||||
|
||||
/// [`Self::references`]. Java, `project_wide`: without `libraries`, only the
|
||||
/// workspace's sources are searched (`libraries_skipped`); with it, those found
|
||||
/// there arrive on `partial` before the dependencies and the JDK are searched.
|
||||
/// [`Self::references`]. Java: without `libraries`, only the workspace's sources are
|
||||
/// searched (`libraries_skipped` when `project_wide`); with it and `project_wide`, those
|
||||
/// found there arrive on `partial` before the dependencies and the JDK are searched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn references_streaming(
|
||||
&self,
|
||||
@@ -1567,7 +1584,10 @@ impl LspManager {
|
||||
};
|
||||
scope::Widened { first: all, second: Some(found), incomplete: sources.incomplete }
|
||||
} else {
|
||||
let first = query(false).await?;
|
||||
// Bulk probes (usage counts, Safe Delete) ask about the sources' own symbols,
|
||||
// which no dependency uses: searching every jar and the JDK only adds seconds
|
||||
// per symbol and delays the searches the user asks for.
|
||||
let first = query(!libraries).await?;
|
||||
let empty = first.is_empty();
|
||||
scope::Widened::only(first, empty, &t.server)
|
||||
};
|
||||
@@ -2630,7 +2650,14 @@ impl LspManager {
|
||||
};
|
||||
if let Some((entry, text)) = found {
|
||||
let title = entry.rsplit('/').next().unwrap_or(&entry).to_owned();
|
||||
return Ok(self.store_virtual(uri, text, Some(title), &[], self.origin_server(uri).map(|s| s.id)));
|
||||
return Ok(self.store_virtual(
|
||||
uri,
|
||||
text,
|
||||
Some(title),
|
||||
None,
|
||||
&[],
|
||||
self.origin_server(uri).map(|s| s.id),
|
||||
));
|
||||
}
|
||||
}
|
||||
let class_file = scheme == "jdt" || (scheme == "file" && uri.ends_with(".class"));
|
||||
@@ -2641,6 +2668,7 @@ impl LspManager {
|
||||
let mut error = None;
|
||||
for t in &targets {
|
||||
let languages = t.server.languages();
|
||||
let mut description = None;
|
||||
let serves_scheme = t.caps().content_schemes().contains(&scheme);
|
||||
let result: IdeResult<Option<String>> = if serves_scheme && !class_file {
|
||||
self.call::<_, Option<Value>>(
|
||||
@@ -2655,6 +2683,21 @@ impl LspManager {
|
||||
} else if class_file && languages.iter().any(|l| l.as_str() == "java") {
|
||||
self.call::<_, Option<String>>(t, "java/classFileContents", json!({ "uri": uri }), None, LONG_TIMEOUT)
|
||||
.await
|
||||
} else if scheme == "csharp" && t.server.name == "csharp-ls" {
|
||||
self.call::<_, Option<virtual_doc::CSharpMetadata>>(
|
||||
t,
|
||||
"csharp/metadata",
|
||||
json!({ "textDocument": { "uri": uri } }),
|
||||
None,
|
||||
LONG_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.map(|metadata| {
|
||||
metadata.map(|m| {
|
||||
description = m.assembly_name.filter(|name| !name.is_empty());
|
||||
m.source
|
||||
})
|
||||
})
|
||||
} else if jar_class && t.caps().commands().iter().any(|c| c == "decompile") {
|
||||
// The official Kotlin LSP: `decompile` answers `{ code, language }`.
|
||||
self.call::<_, Option<Value>>(
|
||||
@@ -2685,7 +2728,7 @@ impl LspManager {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
return Ok(self.store_virtual(uri, text, None, &languages, Some(t.server.id)));
|
||||
return Ok(self.store_virtual(uri, text, None, description, &languages, Some(t.server.id)));
|
||||
}
|
||||
if jar_class && error.is_none() {
|
||||
return Err(IdeError::not_found(format!(
|
||||
@@ -2702,10 +2745,15 @@ impl LspManager {
|
||||
uri: &str,
|
||||
text: String,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
languages: &[LanguageId],
|
||||
server: Option<ide_core::ServerId>,
|
||||
) -> VirtualDocument {
|
||||
let decompiled = virtual_doc::is_decompiled(&text);
|
||||
let decompiled = if virtual_doc::scheme(uri) == "csharp" {
|
||||
virtual_doc::is_csharp_decompiled(uri)
|
||||
} else {
|
||||
virtual_doc::is_decompiled(&text)
|
||||
};
|
||||
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
|
||||
let detected = self.languages.detect(Path::new(&title), None);
|
||||
let language_id = if detected == LanguageId::plain_text() {
|
||||
@@ -2718,7 +2766,7 @@ impl LspManager {
|
||||
text,
|
||||
language_id,
|
||||
title,
|
||||
description: virtual_doc::description(uri),
|
||||
description: description.or_else(|| virtual_doc::description(uri)),
|
||||
decompiled,
|
||||
};
|
||||
if let Some(server) = server {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! and shown together.
|
||||
|
||||
use crate::server::{Running, Server};
|
||||
use crate::{LspManager, convert};
|
||||
use crate::{LspManager, convert, virtual_doc};
|
||||
use ide_core::{DocId, IdeEvent};
|
||||
use ide_jsonrpc::RpcError;
|
||||
use lsp_types as lsp;
|
||||
@@ -43,6 +43,10 @@ impl LspManager {
|
||||
let targets: Vec<PullTarget> = {
|
||||
let docs = self.docs.lock();
|
||||
let Some(d) = docs.get(&doc) else { return };
|
||||
// Decompiled C# is a source view, not compilable project code (e.g. Unity's older language version).
|
||||
if virtual_doc::is_csharp_decompiled(d.uri.as_str()) {
|
||||
return;
|
||||
}
|
||||
d.servers
|
||||
.iter()
|
||||
.filter(|a| only.is_none_or(|s| s.id == a.server.id))
|
||||
|
||||
@@ -121,6 +121,9 @@ pub struct Server {
|
||||
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
|
||||
pub external_diagnostics: std::sync::atomic::AtomicBool,
|
||||
pub external_refresh_queued: std::sync::atomic::AtomicBool,
|
||||
/// The instance whose just registered external project is loading, until an open file's
|
||||
/// diagnostics arrive (0: none).
|
||||
pub external_loading: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
@@ -157,6 +160,7 @@ impl Server {
|
||||
external_project: tokio::sync::Mutex::new(Default::default()),
|
||||
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
|
||||
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
|
||||
external_loading: std::sync::atomic::AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,7 +416,8 @@ impl Server {
|
||||
*self.loading.lock() == Some(true)
|
||||
}
|
||||
|
||||
/// Records `experimental/serverStatus`: `quiescent` false while the project loads.
|
||||
/// Records `experimental/serverStatus`: `quiescent` false while the project loads (also
|
||||
/// set while vtsls loads an external project, see `external_project`).
|
||||
pub fn set_loading(&self, sink: &SharedSink, loading: bool) {
|
||||
if self.loading.lock().replace(loading) == Some(loading) {
|
||||
return;
|
||||
@@ -533,6 +538,7 @@ impl Server {
|
||||
|
||||
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
|
||||
*self.loading.lock() = None;
|
||||
self.external_loading.store(0, std::sync::atomic::Ordering::Release);
|
||||
self.progress.lock().drain().map(|(_, p)| (p.task, p.title)).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,68 @@
|
||||
//! URI (library classes from `jdt://`, disk classes from `file://`, or
|
||||
//! `workspace/textDocumentContent`).
|
||||
|
||||
use percent_encoding::percent_decode_str;
|
||||
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
|
||||
|
||||
const URI_ESCAPES: &AsciiSet = &CONTROLS
|
||||
.add(b' ')
|
||||
.add(b'"')
|
||||
.add(b'<')
|
||||
.add(b'>')
|
||||
.add(b'[')
|
||||
.add(b']')
|
||||
.add(b'\\')
|
||||
.add(b'^')
|
||||
.add(b'`')
|
||||
.add(b'{')
|
||||
.add(b'|')
|
||||
.add(b'}');
|
||||
|
||||
/// csharp-ls uses .NET Uri.ToString(), which can leave spaces and Unicode unescaped.
|
||||
/// Normalize only document URI fields, before lsp-types' strict URI deserialization.
|
||||
pub(crate) fn normalize_csharp_uris(value: &mut serde_json::Value) {
|
||||
match value {
|
||||
serde_json::Value::Array(values) => values.iter_mut().for_each(normalize_csharp_uris),
|
||||
serde_json::Value::Object(fields) => {
|
||||
for (key, value) in fields {
|
||||
// Opaque payloads must survive resolve/execute round trips unchanged.
|
||||
if matches!(key.as_str(), "data" | "arguments") {
|
||||
continue;
|
||||
}
|
||||
if matches!(key.as_str(), "uri" | "targetUri")
|
||||
&& let Some(uri) = value.as_str().filter(|s| s.starts_with("csharp:"))
|
||||
{
|
||||
*value = utf8_percent_encode(uri, URI_ESCAPES).to_string().into();
|
||||
} else {
|
||||
normalize_csharp_uris(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct CSharpMetadata {
|
||||
pub source: String,
|
||||
pub assembly_name: Option<String>,
|
||||
}
|
||||
|
||||
/// csharp-ls serves both decompiled and source-generated documents through metadata.
|
||||
pub(crate) fn is_csharp_decompiled(uri: &str) -> bool {
|
||||
if scheme(uri) != "csharp" {
|
||||
return false;
|
||||
}
|
||||
let segs = segments(uri);
|
||||
// The kind follows the project file, not a directory that happens to have this name.
|
||||
if let Some(kind) = segs.windows(2).find_map(|s| {
|
||||
(s[0].ends_with(".csproj") && matches!(s[1].as_str(), "decompiled" | "generated")).then_some(s[1].as_str())
|
||||
}) {
|
||||
return kind == "decompiled";
|
||||
}
|
||||
// Older csharp-ls versions used csharp:/metadata/... for decompiled symbols.
|
||||
segs.first().is_some_and(|s| s == "metadata")
|
||||
}
|
||||
|
||||
/// Recognize decompiler headers, without treating disassembler stubs as Java source.
|
||||
pub fn is_decompiled(text: &str) -> bool {
|
||||
@@ -107,6 +168,48 @@ mod tests {
|
||||
|
||||
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
|
||||
|
||||
#[test]
|
||||
fn csharp_metadata_titles_and_kinds() {
|
||||
for (uri, expected) in [
|
||||
("csharp:/D:/My%20Game/Game.csproj/decompiled/UnityEngine.MonoBehaviour.cs", true),
|
||||
("csharp:/home/me/%E9%A1%B9%E7%9B%AE/App.csproj/decompiled/System.String.cs", true),
|
||||
("csharp:/metadata/projects/App/assemblies/System.Runtime/symbols/System.String.cs", true),
|
||||
("csharp:/work/App.csproj/generated/Generator/Player.g.cs", false),
|
||||
("csharp:/work/decompiled/App.csproj/generated/Generator/Player.g.cs", false),
|
||||
("csharp:/metadata/App.csproj/generated/Player.g.cs", false),
|
||||
("csharp:/work/App.csproj/generated/decompiled/Player.g.cs", false),
|
||||
("file:///work/App.csproj/decompiled/Player.cs", false),
|
||||
] {
|
||||
assert_eq!(is_csharp_decompiled(uri), expected, "{uri}");
|
||||
}
|
||||
assert_eq!(
|
||||
title("csharp:/D:/My%20Game/Game.csproj/decompiled/UnityEngine.MonoBehaviour.cs", true),
|
||||
"UnityEngine.MonoBehaviour.cs"
|
||||
);
|
||||
assert_eq!(title("csharp:/home/me/App.csproj/decompiled/Example.%E7%B1%BB.cs", true), "Example.类.cs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharp_uri_encoding_preserves_escapes_and_other_response_fields() {
|
||||
let uri = "csharp:/D:/My Game/项目 [1]/App%23%25.csproj/decompiled/Example.C%601.cs";
|
||||
let encoded = "csharp:/D:/My%20Game/%E9%A1%B9%E7%9B%AE%20%5B1%5D/App%23%25.csproj/decompiled/Example.C%601.cs";
|
||||
let mut response = serde_json::json!([
|
||||
{ "uri": uri, "source": uri },
|
||||
{ "location": { "targetUri": uri } },
|
||||
{ "uri": encoded },
|
||||
{ "uri": "file:///D:/project/App.cs" },
|
||||
{ "uri": "jdt://contents/a.jar/p/C.class?=p/%5C/a.jar" },
|
||||
{ "data": { "uri": uri }, "command": { "arguments": [{ "targetUri": uri }] } }
|
||||
]);
|
||||
let original = response.clone();
|
||||
normalize_csharp_uris(&mut response);
|
||||
assert_eq!(response[0]["uri"], encoded);
|
||||
assert_eq!(response[0]["source"], uri);
|
||||
assert_eq!(response[1]["location"]["targetUri"], encoded);
|
||||
assert_eq!(response.as_array().unwrap()[2..], original.as_array().unwrap()[2..]);
|
||||
assert!(encoded.parse::<lsp_types::Uri>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdt_titles() {
|
||||
assert_eq!(title(JDT, true), "SpringApplication.class");
|
||||
|
||||
@@ -238,6 +238,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -1672,6 +1673,18 @@ async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
|
||||
assert_eq!(asked[0], json!({ "command": "decompile", "arguments": [thing] }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn alternative_java_server_uses_lsp_without_jdt_commands() {
|
||||
let h = harness_for("java", "java", &[("kmp-lsp", incremental_caps())], &[]);
|
||||
let (doc, path) = h.open("Sample.java", "class Sample {}");
|
||||
h.wait_status("kmp-lsp", ServerStatus::Ready).await;
|
||||
assert!(h.mgr.hover(doc, Pos::new(0, 7), Default::default()).await.is_ok());
|
||||
let error = h.mgr.java_debug_server(&path).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("jdtls"));
|
||||
assert!(h.launcher.state("kmp-lsp").requested("workspace/executeCommand").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
// Preferred installed: the alternative is never started.
|
||||
@@ -1823,10 +1836,11 @@ async fn java_implementations_come_from_sources_first() {
|
||||
.collect::<Value>()
|
||||
};
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, params| match method {
|
||||
// Line 0 is declared in the sources; line 2 in a dependency, which implements it on line 3.
|
||||
// Lines 0 and 1 are declared in the sources; 2 and 3 in a dependency, which implements 2 on line 3.
|
||||
"workspace/executeCommand" => Some(match params["arguments"][1].as_u64() {
|
||||
Some(0) => json!({ "locations": at(&[1]), "complete": true }),
|
||||
Some(2) => json!({ "locations": at(&[1]), "complete": false }),
|
||||
Some(3) => json!({ "locations": [], "complete": false }),
|
||||
_ => json!({ "locations": [], "complete": true }),
|
||||
}),
|
||||
"textDocument/implementation" => Some(at(&[3, 1])),
|
||||
@@ -1857,7 +1871,14 @@ async fn java_implementations_come_from_sources_first() {
|
||||
assert_eq!(lines(&found), vec![3, 1]);
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 2);
|
||||
|
||||
// None in the sources: the standard request, with the dependencies.
|
||||
// Declared in the sources and implemented nowhere there: no search through the dependencies.
|
||||
let found = h.mgr.goto(doc, Pos::new(1, 6), GotoKind::Implementation).await.unwrap();
|
||||
assert!(found.is_empty());
|
||||
let markers = h.mgr.implementations(doc, &[Pos::new(1, 6)], Default::default()).await.unwrap();
|
||||
assert!(markers[0].is_empty());
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 2);
|
||||
|
||||
// None in the sources of a dependency's type: the standard request, with the dependencies.
|
||||
let partial = Mutex::new(Vec::new());
|
||||
let found = h
|
||||
.mgr
|
||||
@@ -2252,6 +2273,106 @@ async fn noop_handler_is_usable_for_raw_peers() {
|
||||
|
||||
// ------------------------------------------------------------------ virtual documents
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn csharp_metadata_navigation_and_generated_documents() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["diagnosticProvider"] = json!({ "interFileDependencies": false, "workspaceDiagnostics": false });
|
||||
let h = harness_for("csharp", "cs", &[("other-csharp", incremental_caps()), ("csharp-ls", caps)], &[]);
|
||||
let (doc, path) = h.open("Player.cs", "class Player : MonoBehaviour {}\n");
|
||||
h.wait_status("other-csharp", ServerStatus::Ready).await;
|
||||
h.wait_status("csharp-ls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("csharp-ls");
|
||||
let other = h.launcher.state("other-csharp");
|
||||
eventually(|| !s.requested("textDocument/diagnostic").is_empty()).await;
|
||||
assert_eq!(s.requested("initialize")[0]["capabilities"]["experimental"]["csharp"]["metadataUris"], true);
|
||||
assert!(other.requested("initialize")[0]["capabilities"]["experimental"]["csharp"].is_null());
|
||||
|
||||
let uri = "csharp:/D:/My%20Game/Game.csproj/decompiled/UnityEngine.MonoBehaviour.cs";
|
||||
let text = "namespace UnityEngine;\npublic class MonoBehaviour {\n public void CancelInvoke() {}\n}\n";
|
||||
s.respond("csharp/metadata", json!({ "assemblyName": "UnityEngine.CoreModule", "source": text }));
|
||||
// Both Location and LocationLink preserve the server's type/member selection.
|
||||
for (response, range) in [
|
||||
(
|
||||
json!({ "uri": uri.replace("%20", " "), "range": {"start":{"line":1,"character":13},"end":{"line":1,"character":26}} }),
|
||||
rng(1, 13, 1, 26),
|
||||
),
|
||||
(
|
||||
json!([{ "targetUri": uri, "targetRange": {"start":{"line":0,"character":0},"end":{"line":3,"character":1}}, "targetSelectionRange": {"start":{"line":2,"character":16},"end":{"line":2,"character":28}} }]),
|
||||
rng(2, 16, 2, 28),
|
||||
),
|
||||
] {
|
||||
s.respond("textDocument/definition", response);
|
||||
let defs = h.mgr.goto(doc, Pos::new(0, 16), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(defs, vec![ide_core::Location { path: uri.into(), range, uri: Some(uri.into()) }]);
|
||||
let vd = h.mgr.virtual_document(uri).await.unwrap();
|
||||
assert_eq!(vd.text, text);
|
||||
assert_eq!(vd.title, "UnityEngine.MonoBehaviour.cs");
|
||||
assert_eq!(vd.language_id.as_str(), "csharp");
|
||||
assert_eq!(vd.description.as_deref(), Some("UnityEngine.CoreModule"));
|
||||
assert!(vd.decompiled);
|
||||
}
|
||||
assert_eq!(s.requested("csharp/metadata"), vec![json!({"textDocument":{"uri":uri}})]);
|
||||
assert!(other.requested("csharp/metadata").is_empty());
|
||||
|
||||
let vdoc = DocId::next();
|
||||
h.mgr.did_open_virtual(vdoc, uri, &h.lang, 0, text);
|
||||
eventually(|| s.docs.lock().contains_key(uri)).await;
|
||||
s.respond("textDocument/hover", json!({"contents":"class MonoBehaviour"}));
|
||||
h.mgr.hover(vdoc, Pos::new(1, 13), Default::default()).await.unwrap();
|
||||
assert_eq!(s.requested("textDocument/hover").last().unwrap()["textDocument"]["uri"], uri);
|
||||
assert!(other.requested("textDocument/hover").is_empty());
|
||||
h.mgr.did_close(vdoc);
|
||||
eventually(|| !s.docs.lock().contains_key(uri)).await;
|
||||
assert!(s.notified("textDocument/didChange").is_empty());
|
||||
|
||||
// Generated sources use the same request but are not decompiled, even under a directory named decompiled.
|
||||
let generated = "csharp:/work/decompiled/Game.csproj/generated/Generator/Player.g.cs";
|
||||
s.respond("csharp/metadata", json!({"source":"partial class Player {}"}));
|
||||
let vd = h.mgr.virtual_document(generated).await.unwrap();
|
||||
assert_eq!(vd.title, "Player.g.cs");
|
||||
assert_eq!(vd.language_id.as_str(), "csharp");
|
||||
assert!(vd.description.is_none());
|
||||
assert!(!vd.decompiled);
|
||||
// Generated and ordinary source still get diagnostics; decompiled assemblies do not.
|
||||
let generated_doc = DocId::next();
|
||||
h.mgr.did_open_virtual(generated_doc, generated, &vd.language_id, 0, &vd.text);
|
||||
eventually(|| s.requested("textDocument/diagnostic").iter().any(|p| p["textDocument"]["uri"] == generated)).await;
|
||||
assert!(s.requested("textDocument/diagnostic").iter().all(|p| p["textDocument"]["uri"] != uri));
|
||||
h.mgr.did_close(generated_doc);
|
||||
|
||||
// Ordinary definitions still resolve to a disk path.
|
||||
s.respond(
|
||||
"textDocument/definition",
|
||||
json!({"uri":uri_of(&path),"range":{"start":{"line":0,"character":6},"end":{"line":0,"character":12}}}),
|
||||
);
|
||||
let defs = h.mgr.goto(doc, Pos::new(0, 6), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(defs[0].path, path);
|
||||
assert!(defs[0].uri.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn csharp_metadata_failures_can_be_retried() {
|
||||
let h = harness_for("csharp", "cs", &[("csharp-ls", incremental_caps())], &[]);
|
||||
h.open("App.cs", "class App {}\n");
|
||||
h.wait_status("csharp-ls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("csharp-ls");
|
||||
let uri = "csharp:/work/App.csproj/decompiled/System.String.cs";
|
||||
for response in [Value::Null, json!({"source":""})] {
|
||||
s.respond("csharp/metadata", response);
|
||||
let err = h.mgr.virtual_document(uri).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
assert!(err.message.contains("System.String.cs"));
|
||||
}
|
||||
s.errors.lock().insert("csharp/metadata".into(), (-32603, "decompilation failed".into()));
|
||||
assert!(h.mgr.virtual_document(uri).await.unwrap_err().message.contains("decompilation failed"));
|
||||
s.errors.lock().remove("csharp/metadata");
|
||||
s.respond("csharp/metadata", json!({"source":"public class String {}", "assemblyName":""}));
|
||||
let vd = h.mgr.virtual_document(uri).await.unwrap();
|
||||
assert!(vd.decompiled);
|
||||
assert!(vd.description.is_none());
|
||||
assert_eq!(s.requested("csharp/metadata").len(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn virtual_locations_and_text_document_content() {
|
||||
let mut caps = incremental_caps();
|
||||
@@ -2987,9 +3108,17 @@ async fn java_usages_in_the_sources_arrive_before_the_dependencies() {
|
||||
let scopes: Vec<_> =
|
||||
s.requested("workspace/executeCommand")[3..].iter().map(|p| p["arguments"].get(4).cloned()).collect();
|
||||
assert_eq!(scopes, [Some(json!("sources")), Some(json!("sources"))]);
|
||||
// Scoped probes (code lenses) search everything at once.
|
||||
// Scoped probes with the libraries search everything at once.
|
||||
let scoped = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
|
||||
assert_eq!(scoped.locations.len(), 2);
|
||||
// Usage counts and Safe Delete (no libraries): the sources alone, not widened.
|
||||
let scoped =
|
||||
h.mgr.references_streaming(doc, Pos::new(0, 5), true, false, false, Default::default(), None).await.unwrap();
|
||||
assert_eq!(scoped.locations.len(), 1);
|
||||
assert!(scoped.locations.iter().all(|l| l.uri.is_none()));
|
||||
let scopes: Vec<_> =
|
||||
s.requested("workspace/executeCommand")[5..].iter().map(|p| p["arguments"].get(4).cloned()).collect();
|
||||
assert_eq!(scopes, [None, Some(json!("sources"))]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -3387,6 +3516,11 @@ async fn rename_edits_files_outside_the_analysis_scope() {
|
||||
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
|
||||
}
|
||||
|
||||
/// tsserver project registrations sent through vtsls, without the `geterr` that follows the first.
|
||||
fn project_requests(s: &MockState) -> Vec<Value> {
|
||||
s.requested("workspace/executeCommand").into_iter().filter(|r| r["arguments"][0] != "geterr").collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_projects_are_capability_gated_and_follow_lifecycle() {
|
||||
for capable in [false, true] {
|
||||
@@ -3408,24 +3542,21 @@ async fn external_projects_are_capability_gated_and_follow_lifecycle() {
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
continue;
|
||||
}
|
||||
let requests = s.requested("workspace/executeCommand");
|
||||
let requests = project_requests(&s);
|
||||
assert_eq!(requests[0]["arguments"][0], "openExternalProject");
|
||||
assert_eq!(requests[0]["arguments"][1]["rootFiles"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(s.docs.lock().len(), 1, "registration must not open source documents");
|
||||
std::fs::write(h.root.join("new.ts"), "export const newHelper = 1;").unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("new.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 2).await;
|
||||
assert_eq!(
|
||||
s.requested("workspace/executeCommand")[1]["arguments"][1]["rootFiles"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
eventually(|| project_requests(&s).len() >= 2).await;
|
||||
assert_eq!(project_requests(&s)[1]["arguments"][1]["rootFiles"].as_array().unwrap().len(), 3);
|
||||
std::fs::rename(h.root.join("new.ts"), h.root.join("renamed.ts")).unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("renamed.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 3).await;
|
||||
assert!(s.requested("workspace/executeCommand")[2].to_string().contains("renamed.ts"));
|
||||
eventually(|| project_requests(&s).len() >= 3).await;
|
||||
assert!(project_requests(&s)[2].to_string().contains("renamed.ts"));
|
||||
std::fs::remove_file(h.root.join("renamed.ts")).unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("renamed.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 4).await;
|
||||
eventually(|| project_requests(&s).len() >= 4).await;
|
||||
let id = h.mgr.servers()[0].id;
|
||||
h.mgr.restart(id).await.unwrap();
|
||||
h.wait_status("arbitrary-name", ServerStatus::Ready).await;
|
||||
@@ -3451,6 +3582,55 @@ async fn external_projects_are_capability_gated_and_follow_lifecycle() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_projects_carry_plugin_files_and_module_aliases() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({ "commands": ["typescript.tsserverRequest"] });
|
||||
let h = harness_configured("vue", "vue", &[("vtsls", caps)], |cfg| {
|
||||
cfg.tsserver_project = true;
|
||||
cfg.tsserver_project_extras.extensions = vec!["vue".into()];
|
||||
cfg.tsserver_project_extras.paths.insert("@/*".into(), vec!["/project/src/*".into()]);
|
||||
});
|
||||
let s = h.launcher.state("vtsls");
|
||||
s.respond("workspace/executeCommand", json!({ "success": true, "body": true }));
|
||||
s.respond("textDocument/references", json!([]));
|
||||
// vtsls answers from one file until its project reports diagnostics: loading till then,
|
||||
// so an empty usage count is not final.
|
||||
let diagnostics = Arc::new(Gate::default());
|
||||
let gate = diagnostics.clone();
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, params| {
|
||||
if method == "workspace/executeCommand" && params["arguments"][0] == "geterr" {
|
||||
gate.hold();
|
||||
return Some(Value::Null);
|
||||
}
|
||||
None
|
||||
}));
|
||||
std::fs::write(h.root.join("format.js"), "export const sum = 1;").unwrap();
|
||||
let (doc, app) = h.open("App.vue", "<script>import { sum } from '@/format'</script>");
|
||||
h.wait_status("vtsls", ServerStatus::Busy).await;
|
||||
eventually(|| diagnostics.entered()).await;
|
||||
let geterr = s.requested("workspace/executeCommand").into_iter().find(|r| r["arguments"][0] == "geterr").unwrap();
|
||||
assert_eq!(geterr["arguments"][1]["files"], json!([app]), "an open file has a project in tsserver");
|
||||
assert_eq!(geterr["arguments"][2]["isAsync"], true);
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 18), false, false, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
|
||||
diagnostics.open();
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
let refs = h.mgr.references(doc, Pos::new(0, 18), false, false, Default::default()).await.unwrap();
|
||||
assert_eq!(refs.incomplete, None);
|
||||
let requests = s.requested("workspace/executeCommand");
|
||||
let args = &requests[0]["arguments"][1];
|
||||
assert_eq!(requests[0]["arguments"][0], "openExternalProject");
|
||||
assert_eq!(args["rootFiles"].as_array().unwrap().len(), 2, "{args}");
|
||||
assert_eq!(args["options"]["paths"], json!({ "@/*": ["/project/src/*"] }));
|
||||
std::fs::write(h.root.join("Cart.vue"), "<script></script>").unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("Cart.vue")]);
|
||||
eventually(|| project_requests(&s).len() >= 2).await;
|
||||
assert!(project_requests(&s)[1].to_string().contains("Cart.vue"));
|
||||
assert_eq!(s.requested("workspace/executeCommand").len(), 3, "geterr only after the first registration");
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gopls_interactive_command_validates_before_execution_and_applies_edits() {
|
||||
let mut caps = incremental_caps();
|
||||
|
||||
@@ -63,6 +63,55 @@ fn lang(id: &str, ext: &str, server: LanguageServerConfig) -> LanguageConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires kmp-lsp on PATH (or OPENIDEA_TEST_KMP_LSP)"]
|
||||
async fn kmp_lsp_java_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let path = root.join("Sample.java");
|
||||
let source = "class Sample {\n static String greet() { return \"Hello\"; }\n void run() { greet(); }\n}\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
|
||||
java.language_servers.retain(|s| s.name == "kmp-lsp");
|
||||
assert_eq!(java.language_servers.len(), 1);
|
||||
if let Ok(bin) = std::env::var("OPENIDEA_TEST_KMP_LSP") {
|
||||
java.language_servers[0].command = bin;
|
||||
}
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("java"), 1, source);
|
||||
retry("kmp-lsp ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "kmp-lsp");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("kmp-lsp failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
let hover = retry("Java hover", Duration::from_secs(30), || async {
|
||||
mgr.hover(doc, Pos::new(2, 18), Default::default()).await.ok().flatten()
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("greet"), "{}", hover.contents.value);
|
||||
let defs = retry("Java definition", Duration::from_secs(30), || async {
|
||||
mgr.goto(doc, Pos::new(2, 18), GotoKind::Definition).await.ok().filter(|d| !d.is_empty())
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs[0].path, path);
|
||||
assert_eq!(defs[0].range.start.line, 1);
|
||||
retry("Java completion", Duration::from_secs(30), || async {
|
||||
let list = mgr.completion(doc, Pos::new(2, 20), None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label.starts_with("greet")).then_some(())
|
||||
})
|
||||
.await;
|
||||
let tokens = mgr.semantic_tokens(doc).await.unwrap().unwrap();
|
||||
assert!(!tokens.data.is_empty() && tokens.data.len() % 5 == 0);
|
||||
let error = mgr.java_debug_server(&path).await.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("jdtls"));
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires jdtls on PATH and a compatible JDK"]
|
||||
async fn intellij_java_formatter_preserves_manual_breaks_and_wraps_long_lines() {
|
||||
@@ -135,6 +184,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -405,6 +455,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -455,6 +506,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -3,15 +3,21 @@
|
||||
//! sandbox goes through [`HostApi`], implemented by the host; the imports
|
||||
//! themselves are in `wit_host`.
|
||||
|
||||
use crate::types::{CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, ProviderDocument};
|
||||
use crate::types::{
|
||||
CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, ProviderDocument, SemanticToken,
|
||||
};
|
||||
use crate::types::{
|
||||
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput, Prompt,
|
||||
RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol, SyntaxToken, WorkbenchEvent,
|
||||
};
|
||||
use crate::types::{
|
||||
FieldValue, View, ViewBody, ViewButton, ViewEvent, ViewField, ViewListItem, ViewTable, ViewTreeItem, Viewport,
|
||||
FieldValue, ServiceLog, ServiceLogToggle, ServicePane, ServiceTab, View, ViewBody, ViewButton, ViewEvent,
|
||||
ViewField, ViewListItem, ViewTable, ViewTreeItem, Viewport,
|
||||
};
|
||||
use crate::wit_host::{
|
||||
bindings, indexing_bindings, providers_bindings, semantic_bindings, services_bindings, syntax_bindings,
|
||||
views_bindings,
|
||||
};
|
||||
use crate::wit_host::{bindings, indexing_bindings, providers_bindings, syntax_bindings, views_bindings};
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_extension::Capability;
|
||||
@@ -29,12 +35,15 @@ use bindings::openidea::plugin::events as wit_events;
|
||||
use bindings::openidea::plugin::types as wit_types;
|
||||
use indexing_bindings::exports::openidea::plugin::document_indexer as wit_index;
|
||||
use providers_bindings::exports::openidea::plugin::providers as wit_prov;
|
||||
use semantic_bindings::exports::openidea::plugin::semantic_tokens_provider as wit_sem;
|
||||
use services_bindings::exports::openidea::plugin::service_provider as wit_svc;
|
||||
use services_bindings::openidea::plugin::service_types as wit_st;
|
||||
use syntax_bindings::exports::openidea::plugin::syntax_provider as wit_syntax;
|
||||
use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.2";
|
||||
pub const API_VERSION: &str = "1.3";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
pub(crate) const MAX_TITLE: usize = 256;
|
||||
@@ -513,6 +522,8 @@ struct Exports {
|
||||
providers: Option<wit_prov::Guest>,
|
||||
indexer: Option<wit_index::Guest>,
|
||||
views: Option<wit_view::Guest>,
|
||||
semantic: Option<wit_sem::Guest>,
|
||||
services: Option<wit_svc::Guest>,
|
||||
}
|
||||
|
||||
/// Most results one syntax call may return (more are dropped).
|
||||
@@ -592,6 +603,8 @@ impl Runtime {
|
||||
let index_indices = wit_index::GuestIndices::new(&pre).ok();
|
||||
let provider_indices = wit_prov::GuestIndices::new(&pre).ok();
|
||||
let view_indices = wit_view::GuestIndices::new(&pre).ok();
|
||||
let semantic_indices = wit_sem::GuestIndices::new(&pre).ok();
|
||||
let service_indices = wit_svc::GuestIndices::new(&pre).ok();
|
||||
let instance = pre.instantiate(&mut store).map_err(api_hint)?;
|
||||
let plugin = plugin_indices.load(&mut store, &instance).map_err(api_hint)?;
|
||||
let syntax = match syntax_indices {
|
||||
@@ -610,9 +623,17 @@ impl Runtime {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
};
|
||||
let semantic = match semantic_indices {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
};
|
||||
let services = match service_indices {
|
||||
Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Self {
|
||||
store,
|
||||
exports: Exports { plugin, syntax, providers, views, indexer },
|
||||
exports: Exports { plugin, syntax, providers, views, indexer, semantic, services },
|
||||
limits: setup.limits,
|
||||
version: setup.version,
|
||||
})
|
||||
@@ -842,6 +863,34 @@ impl Runtime {
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn provide_semantic_tokens(
|
||||
&mut self,
|
||||
doc: &ProviderDocument,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<SemanticToken>, CallError> {
|
||||
if self.exports.semantic.is_none() {
|
||||
return Err(CallError::missing_export("semantic-tokens-provider"));
|
||||
}
|
||||
let d = wit_sem::Document {
|
||||
path: to_ipc(&doc.path),
|
||||
language: doc.language.clone(),
|
||||
version: doc.version,
|
||||
text: doc.text.clone(),
|
||||
};
|
||||
let tokens = self.call(Invocation::default(), timeout, |e, store| {
|
||||
e.semantic.as_ref().expect("checked").call_semantic_tokens(store, &d)
|
||||
})?;
|
||||
Ok(tokens
|
||||
.into_iter()
|
||||
.take(MAX_SEMANTIC_TOKENS)
|
||||
.map(|t| SemanticToken {
|
||||
range: range_from_wit(t.range),
|
||||
kind: clip(t.kind, 32),
|
||||
modifiers: t.modifiers.into_iter().take(MAX_TOKEN_MODIFIERS).map(|m| clip(m, 32)).collect(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn activate(&mut self) -> Result<(), CallError> {
|
||||
let data = self.store.data();
|
||||
let ctx = wit_types::Context {
|
||||
@@ -907,6 +956,29 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Services pane of node `key` of the plugin's services view `view`.
|
||||
pub fn service_detail(
|
||||
&mut self,
|
||||
view: &str,
|
||||
key: &str,
|
||||
invocation: Invocation,
|
||||
) -> Result<Vec<ServiceTab>, CallError> {
|
||||
if self.exports.services.is_none() {
|
||||
return Err(CallError::missing_export("service-provider"));
|
||||
}
|
||||
let result = self.call(invocation, self.limits.timeout, |e, store| {
|
||||
let ctx = store.data_mut().new_invocation()?;
|
||||
let services = e.services.as_ref().expect("checked");
|
||||
let r = services.call_detail(&mut *store, view, key, wasmtime::component::Resource::new_borrow(ctx.rep()));
|
||||
store.data_mut().drop_invocation(ctx);
|
||||
r
|
||||
})?;
|
||||
match result {
|
||||
Ok(tabs) => Ok(tabs.into_iter().take(MAX_SERVICE_TABS).map(service_tab_from_wit).collect()),
|
||||
Err(e) => Err(CallError::Guest(e.into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A user action in a view or custom editor.
|
||||
pub fn view_event(&mut self, view: &str, event: ViewEvent, invocation: Invocation) -> Result<(), CallError> {
|
||||
if self.exports.views.is_none() {
|
||||
@@ -994,6 +1066,8 @@ impl Runtime {
|
||||
|
||||
/// Most items one provider call may return (more are dropped).
|
||||
const MAX_PROVIDER_ITEMS: usize = 10_000;
|
||||
const MAX_SEMANTIC_TOKENS: usize = 1 << 16;
|
||||
const MAX_TOKEN_MODIFIERS: usize = 8;
|
||||
|
||||
fn pos_to_wit(p: ide_core::Pos) -> wit_types::Position {
|
||||
wit_types::Position { line: p.line, character: p.col }
|
||||
@@ -1102,6 +1176,40 @@ fn opt_clip(s: Option<String>, max: usize) -> Option<String> {
|
||||
s.map(|s| clip(s, max))
|
||||
}
|
||||
|
||||
const MAX_SERVICE_TABS: usize = 8;
|
||||
const MAX_LOG_TOGGLES: usize = 8;
|
||||
const MAX_LOG_ARGS: usize = 256;
|
||||
const MAX_LOG_ARG: usize = 4096;
|
||||
|
||||
fn service_tab_from_wit(t: wit_st::Tab) -> ServiceTab {
|
||||
let body = match t.body {
|
||||
wit_st::Pane::Message(m) => ServicePane::Message(clip(m, 16 << 10)),
|
||||
wit_st::Pane::Text(text) => ServicePane::Text(clip(text, MAX_TEXT)),
|
||||
wit_st::Pane::Log(log) => {
|
||||
let args_fit = |args: &[String]| args.len() <= MAX_LOG_ARGS && args.iter().all(|a| a.len() <= MAX_LOG_ARG);
|
||||
if args_fit(&log.args)
|
||||
&& log.toggles.len() <= MAX_LOG_TOGGLES
|
||||
&& log.toggles.iter().all(|t| args_fit(&t.args))
|
||||
{
|
||||
ServicePane::Log(ServiceLog {
|
||||
program: clip(log.program, 256),
|
||||
args: log.args,
|
||||
toggles: log
|
||||
.toggles
|
||||
.into_iter()
|
||||
.map(|t| ServiceLogToggle { id: clip(t.id, 64), label: clip(t.label, MAX_TITLE), args: t.args })
|
||||
.collect(),
|
||||
})
|
||||
} else {
|
||||
ServicePane::Message(format!(
|
||||
"This log asks for more than {MAX_LOG_ARGS} arguments of {MAX_LOG_ARG} bytes or {MAX_LOG_TOGGLES} toggles."
|
||||
))
|
||||
}
|
||||
}
|
||||
};
|
||||
ServiceTab { id: clip(t.id, 64), label: clip(t.label, MAX_TITLE), body }
|
||||
}
|
||||
|
||||
fn view_from_wit(v: wit_vt::View) -> View {
|
||||
let body = match v.body {
|
||||
wit_vt::Body::Message(m) => ViewBody::Message(clip(m, 16 << 10)),
|
||||
|
||||
@@ -419,6 +419,13 @@ pub struct LineMarker {
|
||||
pub target: Option<Location>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SemanticToken {
|
||||
pub range: ide_core::Range,
|
||||
pub kind: String,
|
||||
pub modifiers: Vec<String>,
|
||||
}
|
||||
|
||||
// ---- declarative views (wit/views.wit) ---------------------------------------
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -498,6 +505,42 @@ pub struct View {
|
||||
pub status: Option<String>,
|
||||
}
|
||||
|
||||
/// A tab of the Services pane of a plugin's node (`service-provider.detail`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServiceTab {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub body: ServicePane,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
|
||||
pub enum ServicePane {
|
||||
Message(String),
|
||||
/// Read-only text that can be selected and copied.
|
||||
Text(String),
|
||||
/// A program the IDE runs (with the plugin's `process:` grant), followed in a log.
|
||||
Log(ServiceLog),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServiceLog {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub toggles: Vec<ServiceLogToggle>,
|
||||
}
|
||||
|
||||
/// A switch above the log; when on, `args` are appended and the program restarts.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServiceLogToggle {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
/// The table rows the UI shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -814,3 +814,23 @@ pub(crate) mod indexing_bindings {
|
||||
with: { "openidea:plugin/types": super::bindings::openidea::plugin::types },
|
||||
});
|
||||
}
|
||||
|
||||
/// The optional `service-provider` export.
|
||||
pub(crate) mod services_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
world: "services", path: "../../wit",
|
||||
with: {
|
||||
"openidea:plugin/types": super::bindings::openidea::plugin::types,
|
||||
"openidea:plugin/workspace": super::bindings::openidea::plugin::workspace,
|
||||
"openidea:plugin/editor": super::bindings::openidea::plugin::editor,
|
||||
"openidea:plugin/invocation": super::bindings::openidea::plugin::invocation,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) mod semantic_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
world: "semantic-tokens", path: "../../wit",
|
||||
with: { "openidea:plugin/types": super::bindings::openidea::plugin::types },
|
||||
});
|
||||
}
|
||||
@@ -28,6 +28,7 @@ fn components() -> Vec<PathBuf> {
|
||||
let mut out = vec![
|
||||
repo().join("crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm"),
|
||||
repo().join("crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm"),
|
||||
];
|
||||
let official = repo().join("plugins/official");
|
||||
let mut dirs: Vec<_> = std::fs::read_dir(&official).unwrap().map(|e| e.unwrap().path()).collect();
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
20ce53ecb41ad94e9c7d59cd4ac51f63081c9f150832fd7febe07887fa3c07ab
|
||||
670aec4d79e92537efb7048698bbb8f236cd6006524c74459891b03c9b613450
|
||||
+10
-1
@@ -1,6 +1,7 @@
|
||||
//! Sample OpenIDEA plugin, written with the `openidea-plugin` SDK.
|
||||
//! Build with `openidea-plugin build crates/ide-plugin/tests/fixtures/hello` (see plugins/README.md).
|
||||
|
||||
use openidea_plugin::services::{Pane, ProcessLog, Services, Tab};
|
||||
use openidea_plugin::views::{Body, Button, TreeItem, View, ViewEvent, Viewport, Views};
|
||||
use openidea_plugin::{Context, Error, Invocation, LogLevel, NotificationLevel, Plugin, host, register_plugin};
|
||||
use std::collections::BTreeSet;
|
||||
@@ -96,7 +97,15 @@ impl Views for Hello {
|
||||
}
|
||||
}
|
||||
|
||||
register_plugin!(Hello, views);
|
||||
/// As a services view (tests): a node's key is the `sh -c` script its Log tab runs.
|
||||
impl Services for Hello {
|
||||
fn detail(&mut self, view: &str, key: &str, _ctx: &Invocation) -> Result<Vec<Tab>, Error> {
|
||||
let log = ProcessLog::new("sh", &["-c", key]).toggle("named", "Named", &["named"]);
|
||||
Ok(vec![Tab::new("log", "Log", log), Tab::new("info", "Info", Pane::Text(format!("{view}: {key}")))])
|
||||
}
|
||||
}
|
||||
|
||||
register_plugin!(Hello, views, services);
|
||||
|
||||
/// Today's UTC date as `YYYY-MM-DD` (WASI wall clock).
|
||||
fn today() -> String {
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
2e7d8932329d9383ecd4938225a111851f8a9805c6da558431dea84b7cecbe1c
|
||||
c913c2c94fecb43d00f73f3171cc2fda54caf7a28f170424b0addb1d40ed4cae
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7f58bace9b60d8b6b87c97e78dd8cca4955bd13d5f0737efe9d9a362cd1552bf
|
||||
911388ae62843d7b1e4c40d91307fbe507535c60680a9626cc07d724b75a9dfb
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ee5ba9209eaf963ccc423828ca2e8ba221345c9c246635283214562668a872ad
|
||||
a3818b6ec40df8f141290537a7c024aadb02d7be1eb063ca9170799ca3271898
|
||||
@@ -5,8 +5,8 @@ wit_bindgen::generate!({
|
||||
inline: "
|
||||
package fixture:misbehave;
|
||||
world misbehave {
|
||||
include openidea:plugin/plugin-syntax@1.2.0;
|
||||
export openidea:plugin/providers@1.2.0;
|
||||
include openidea:plugin/plugin-syntax@1.3.0;
|
||||
export openidea:plugin/providers@1.3.0;
|
||||
}
|
||||
",
|
||||
path: "../../../../../wit",
|
||||
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "macro-string"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openidea-test-semantic-tokens"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.63.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"macro-string",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hashbrown",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-ident",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "openidea-test-semantic-tokens"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
@@ -0,0 +1,7 @@
|
||||
# Semantic tokens test fixture
|
||||
|
||||
Colours the name after every `->` in PHP documents that is not called: `method`
|
||||
when the document declares `function <name>(`, `property` otherwise.
|
||||
|
||||
Used by `cargo test -p ide-host --test plugin_semantic_tokens` to exercise the
|
||||
optional `semantic-tokens-provider` export. It is not a marketplace plugin.
|
||||
Бінарний файл не відображається.
@@ -0,0 +1 @@
|
||||
9e4c12fdf905227128d97e92639cf336124929c37384e5f5796e27ebfc5a7b37
|
||||
@@ -0,0 +1,9 @@
|
||||
id = "test.semantic-tokens"
|
||||
name = "Semantic tokens fixture"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.3"
|
||||
wasm = "dist/plugin.wasm"
|
||||
|
||||
[[contributes.providers]]
|
||||
kinds = ["semantic-tokens"]
|
||||
languages = ["php"]
|
||||
@@ -0,0 +1,37 @@
|
||||
use openidea_plugin::semantic_tokens::{Document, SemanticToken, SemanticTokens, TokenKind};
|
||||
use openidea_plugin::{Error, Invocation, Plugin, Range, register_plugin, text};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fixture;
|
||||
|
||||
impl Plugin for Fixture {
|
||||
fn run_command(&mut self, id: &str, _: &Invocation, _: Option<&str>) -> Result<Option<String>, Error> {
|
||||
Err(Error::NotFound(id.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl SemanticTokens for Fixture {
|
||||
fn semantic_tokens(&mut self, doc: &Document) -> Vec<SemanticToken> {
|
||||
let text = doc.text.as_str();
|
||||
let mut out = Vec::new();
|
||||
let mut rest = 0;
|
||||
while let Some(i) = text[rest..].find("->") {
|
||||
let start = rest + i + 2;
|
||||
let end = text[start..]
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.map_or(text.len(), |n| start + n);
|
||||
rest = end;
|
||||
if end == start || text[end..].starts_with('(') {
|
||||
continue;
|
||||
}
|
||||
let name = &text[start..end];
|
||||
let kind =
|
||||
if text.contains(&format!("function {name}(")) { TokenKind::Method } else { TokenKind::Property };
|
||||
let range = Range { start: text::position(text, start), end: text::position(text, end) };
|
||||
out.push(SemanticToken::new(range, kind));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
register_plugin!(Fixture, semantic_tokens);
|
||||
@@ -835,6 +835,9 @@ enum PyEnv {
|
||||
Runner(&'static str),
|
||||
/// A project-local virtualenv directory (relative to root).
|
||||
Venv(String),
|
||||
/// A pixi environment directory `.pixi/envs/<env>` (relative to root); tools
|
||||
/// also run as `pixi run …`, the interpreter directly for the debugger.
|
||||
Pixi(String),
|
||||
System,
|
||||
}
|
||||
|
||||
@@ -854,9 +857,25 @@ impl PyEnv {
|
||||
return Self::Venv(venv.to_owned());
|
||||
}
|
||||
}
|
||||
if let Some(env) = Self::pixi_env(root) {
|
||||
return Self::Pixi(env);
|
||||
}
|
||||
Self::System
|
||||
}
|
||||
|
||||
/// The first pixi environment `.pixi/envs/<env>` holding a Python, relative
|
||||
/// to the root, in name order.
|
||||
fn pixi_env(root: &Path) -> Option<String> {
|
||||
let envs = root.join(".pixi/envs");
|
||||
let mut dirs: Vec<_> =
|
||||
std::fs::read_dir(&envs).into_iter().flatten().flatten().map(|e| e.path()).filter(|d| d.is_dir()).collect();
|
||||
dirs.sort_by_key(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
|
||||
dirs.iter()
|
||||
.find(|d| d.join(Self::python_exe()).is_file() || d.join("bin").join(Self::python_exe()).is_file())
|
||||
.and_then(|d| d.strip_prefix(root).ok())
|
||||
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn bin_dir() -> &'static str {
|
||||
if cfg!(windows) { "Scripts" } else { "bin" }
|
||||
}
|
||||
@@ -880,6 +899,18 @@ impl PyEnv {
|
||||
}
|
||||
}
|
||||
Self::System => (tool.to_owned(), Vec::new()),
|
||||
// A pixi env's executables sit in `bin` (Unix) or `Scripts` (Windows)
|
||||
// like a venv's; else `pixi run` finds the tool.
|
||||
Self::Pixi(v) => {
|
||||
let exe = if cfg!(windows) { format!("{tool}.exe") } else { tool.to_owned() };
|
||||
for bin in ["Scripts", "bin"] {
|
||||
let rel = format!("{v}/{bin}/{exe}");
|
||||
if root.join(&rel).is_file() {
|
||||
return (rel, Vec::new());
|
||||
}
|
||||
}
|
||||
("pixi".to_owned(), vec!["run".into(), tool.into()])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -894,9 +925,19 @@ impl PyEnv {
|
||||
match self {
|
||||
Self::Runner(r) => ((*r).to_owned(), vec!["run".into(), "python".into()]),
|
||||
Self::Venv(v) => (format!("{v}/{}/{}", Self::bin_dir(), Self::python_exe()), Vec::new()),
|
||||
Self::Pixi(v) => (Self::pixi_python(v), Vec::new()),
|
||||
Self::System => ((if cfg!(windows) { "python" } else { "python3" }).to_owned(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<env>/python.exe` (Windows) or `<env>/bin/python` of a pixi environment.
|
||||
fn pixi_python(env: &str) -> String {
|
||||
if cfg!(windows) {
|
||||
format!("{env}/{}", Self::python_exe())
|
||||
} else {
|
||||
format!("{env}/bin/{}", Self::python_exe())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The interpreter an imported debugger configuration runs with, as `(command, leading args)`:
|
||||
@@ -909,6 +950,9 @@ pub(crate) fn project_python(root: &Path) -> (String, Vec<String>) {
|
||||
return (rel, Vec::new());
|
||||
}
|
||||
}
|
||||
if let Some(env) = PyEnv::pixi_env(root) {
|
||||
return (PyEnv::pixi_python(&env), Vec::new());
|
||||
}
|
||||
PyEnv::detect(root).python()
|
||||
}
|
||||
|
||||
@@ -943,8 +987,9 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
fn detect_python(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
|
||||
let env = PyEnv::detect(root);
|
||||
// A project virtualenv marks a Python project too (scripts + tests without packaging files).
|
||||
let venv = matches!(env, PyEnv::Venv(_));
|
||||
// A project virtualenv or pixi environment marks a Python project too
|
||||
// (scripts + tests without packaging files).
|
||||
let venv = matches!(env, PyEnv::Venv(_) | PyEnv::Pixi(_));
|
||||
if !venv && !markers.iter().any(|m| root.join(m).is_file()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -633,15 +633,18 @@ impl ProcessManager {
|
||||
self.stop_with_grace(id, STOP_GRACE)
|
||||
}
|
||||
|
||||
/// [`Self::stop`] with an explicit grace period before the kill. A configuration's
|
||||
/// stop command runs first; signals follow only if the process outlives it.
|
||||
/// [`Self::stop`] with an explicit grace period for the configured stop command. The
|
||||
/// first stop only asks the process tree to exit (stop command, then `SIGINT`) and waits;
|
||||
/// a second stop kills it.
|
||||
pub fn stop_with_grace(&self, id: RunId, grace: Duration) -> IdeResult<()> {
|
||||
let entry = self.entry(id)?;
|
||||
if entry.exited.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
let already_stopping = entry.stopping.swap(true, Ordering::AcqRel);
|
||||
let Some(pid) = *entry.pid.lock() else { return Ok(()) };
|
||||
// A run that ended by itself can leave members of its group behind: a Stop must
|
||||
// still be able to reach them.
|
||||
if entry.exited.load(Ordering::Acquire) && !group_alive(pid, &entry) {
|
||||
return Ok(());
|
||||
}
|
||||
if already_stopping {
|
||||
// Second stop request: don't wait out the grace period.
|
||||
kill_tree(pid, true);
|
||||
@@ -671,9 +674,11 @@ impl ProcessManager {
|
||||
}
|
||||
kill_tree(pid, false);
|
||||
}
|
||||
if !exits_within(grace) {
|
||||
tracing::debug!(id = %entry.id, pid, "process ignored interrupt; killing");
|
||||
kill_tree(pid, true);
|
||||
// A first Stop only asks the process tree to exit, as IDEA does: it waits for
|
||||
// the shutdown to finish (a Spring Boot app can take seconds) and a second Stop
|
||||
// is what kills. Killing on a timer here cut shutdown logs off with SIGKILL.
|
||||
while group_alive(pid, &entry) {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("failed to start stop thread: {e}")))?;
|
||||
@@ -1061,6 +1066,18 @@ fn spawn_pump(
|
||||
if let Some(pty) = &entry.pty {
|
||||
pty.lock().take();
|
||||
}
|
||||
// A stopped run is over when the whole process group is gone, not when the child we
|
||||
// spawned exits: a shell or `mvn` can end while the application it started keeps its
|
||||
// port, and reporting "finished" then would let Run start into an occupied port.
|
||||
// A second Stop kills the group, which ends this wait.
|
||||
#[cfg(unix)]
|
||||
if entry.stopping.load(Ordering::Acquire)
|
||||
&& let Some(pid) = *entry.pid.lock()
|
||||
{
|
||||
while group_alive(pid, &entry) {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
tracing::debug!(id = %entry.id, ?code, "run exited");
|
||||
sink.emit(IdeEvent::RunExited { run: entry.id, code });
|
||||
|
||||
@@ -204,6 +204,9 @@ fn stop_kills_whole_process_group() {
|
||||
let grandchild: i32 = out.trim().parse().expect("pid");
|
||||
assert!(alive(grandchild));
|
||||
|
||||
// The first Stop only asks the group to exit (and waits); the second one kills it.
|
||||
h.pm.stop(id).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
h.pm.stop(id).unwrap();
|
||||
wait_exit(&h, id, Duration::from_secs(10));
|
||||
let deadline = Instant::now() + Duration::from_secs(8);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! A stopped run reports its exit only once the whole process group is gone, so the next
|
||||
//! start cannot meet a port the previous process still holds.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::{IdeEvent, RunId, SharedSink};
|
||||
use ide_run::{ProcessManager, RunConfig, StartOptions};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn channel_sink() -> (SharedSink, Receiver<IdeEvent>) {
|
||||
let (tx, events) = mpsc::channel();
|
||||
let tx = Mutex::new(tx);
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
|
||||
let _ = tx.lock().send(e);
|
||||
});
|
||||
(sink, events)
|
||||
}
|
||||
|
||||
fn wait_exit(events: &Receiver<IdeEvent>, id: RunId, timeout: Duration) -> Option<i32> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match events.recv_timeout(left).expect("RunExited event") {
|
||||
IdeEvent::RunExited { run, code } if run == id => return code,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !ready() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_still_running(events: &Receiver<IdeEvent>, timeout: Duration) {
|
||||
let event = events.recv_timeout(timeout);
|
||||
assert!(
|
||||
matches!(event, Err(mpsc::RecvTimeoutError::Timeout)),
|
||||
"run exited before shutdown was released: {event:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_run_keeps_its_port_until_the_group_is_gone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (sink, events) = channel_sink();
|
||||
let pm = ProcessManager::new();
|
||||
// The `mvn`-starts-a-JVM shape: the direct child dies on SIGINT while the process it
|
||||
// started ignores it and keeps its socket open until the test releases it.
|
||||
let script = tmp.path().join("hold.py");
|
||||
std::fs::write(
|
||||
&script,
|
||||
"import pathlib, signal, socket, sys, time\n\
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
|
||||
s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen()\n\
|
||||
open(sys.argv[1], 'w').write(str(s.getsockname()[1]))\n\
|
||||
while not pathlib.Path(sys.argv[2]).exists(): time.sleep(0.01)\n",
|
||||
)
|
||||
.unwrap();
|
||||
let port_file = tmp.path().join("port");
|
||||
let release_file = tmp.path().join("release");
|
||||
let config = RunConfig {
|
||||
id: "boot".into(),
|
||||
name: "boot".into(),
|
||||
kind: "shell".into(),
|
||||
command: "/bin/sh".into(),
|
||||
args: vec![
|
||||
"-c".into(),
|
||||
"python3 \"$1\" \"$2\" \"$3\" & sleep 60".into(),
|
||||
"sh".into(),
|
||||
script.display().to_string(),
|
||||
port_file.display().to_string(),
|
||||
release_file.display().to_string(),
|
||||
],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
|
||||
wait_for("the listening port", || {
|
||||
std::fs::read_to_string(&port_file).ok().is_some_and(|text| text.trim().parse::<u16>().is_ok())
|
||||
});
|
||||
let port: u16 = std::fs::read_to_string(&port_file).expect("port").trim().parse().unwrap();
|
||||
|
||||
pm.stop(info.id).unwrap();
|
||||
let pid = info.pid.expect("child pid") as libc::pid_t;
|
||||
wait_for("the direct child to exit", || unsafe { libc::kill(pid, 0) != 0 });
|
||||
let exit = events.recv_timeout(Duration::from_secs(1));
|
||||
let port_held = std::net::TcpStream::connect(("127.0.0.1", port)).is_ok();
|
||||
std::fs::write(&release_file, "").unwrap();
|
||||
assert!(
|
||||
matches!(exit, Err(mpsc::RecvTimeoutError::Timeout)),
|
||||
"run exited while its descendant held the port: {exit:?}"
|
||||
);
|
||||
assert!(port_held, "the descendant still holds its port");
|
||||
let code = wait_exit(&events, info.id, Duration::from_secs(20));
|
||||
assert!(code.is_some(), "the run reports its exit");
|
||||
assert!(
|
||||
std::net::TcpStream::connect(("127.0.0.1", port)).is_err(),
|
||||
"the port is still bound when the run reports finished"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_stop_does_not_kill_a_program_that_is_still_shutting_down() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (sink, events) = channel_sink();
|
||||
let pm = ProcessManager::new();
|
||||
// Ignores SIGINT until stdin releases the shutdown, like a slow Spring Boot shutdown.
|
||||
// A first Stop must wait even past the grace period instead of killing it (exit code 137).
|
||||
let script = tmp.path().join("slow.py");
|
||||
let ready_file = tmp.path().join("ready");
|
||||
std::fs::write(
|
||||
&script,
|
||||
"import pathlib, signal, sys\n\
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
|
||||
pathlib.Path(sys.argv[1]).touch()\n\
|
||||
sys.stdin.readline()\n",
|
||||
)
|
||||
.unwrap();
|
||||
let config = RunConfig {
|
||||
id: "slow".into(),
|
||||
name: "slow".into(),
|
||||
kind: "shell".into(),
|
||||
command: "python3".into(),
|
||||
args: vec![script.display().to_string(), ready_file.display().to_string()],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
|
||||
wait_for("the SIGINT handler", || ready_file.exists());
|
||||
pm.stop_with_grace(info.id, Duration::from_millis(100)).unwrap();
|
||||
assert_still_running(&events, Duration::from_secs(1));
|
||||
pm.write_stdin(info.id, "finish shutdown\n").unwrap();
|
||||
let code = wait_exit(&events, info.id, Duration::from_secs(10));
|
||||
assert_eq!(code, Some(0), "the program exited by itself, not by SIGKILL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_stop_kills_a_program_that_ignores_the_first() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (sink, events) = channel_sink();
|
||||
let pm = ProcessManager::new();
|
||||
let script = tmp.path().join("stuck.py");
|
||||
let ready_file = tmp.path().join("ready");
|
||||
std::fs::write(
|
||||
&script,
|
||||
"import pathlib, signal, sys\n\
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)\n\
|
||||
pathlib.Path(sys.argv[1]).touch()\n\
|
||||
sys.stdin.readline()\n",
|
||||
)
|
||||
.unwrap();
|
||||
let config = RunConfig {
|
||||
id: "stuck".into(),
|
||||
name: "stuck".into(),
|
||||
kind: "shell".into(),
|
||||
command: "python3".into(),
|
||||
args: vec![script.display().to_string(), ready_file.display().to_string()],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
let info = pm.start(tmp.path(), &config, &StartOptions::default(), sink, Box::new(|_| {})).expect("start");
|
||||
wait_for("the SIGINT handler", || ready_file.exists());
|
||||
pm.stop(info.id).unwrap();
|
||||
assert_still_running(&events, Duration::from_millis(200));
|
||||
pm.stop(info.id).unwrap();
|
||||
let code = wait_exit(&events, info.id, Duration::from_secs(10));
|
||||
assert_eq!(code, Some(137), "the second Stop SIGKILLs");
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! language servers, run configurations and terminals.
|
||||
|
||||
use crate::discover::{project_venv_python, workspace_tsdk};
|
||||
use crate::exec::{path_with, search_path};
|
||||
use crate::exec::{path_with, search_path, which};
|
||||
use crate::{angular, godot, pinned, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings};
|
||||
@@ -64,7 +64,8 @@ pub fn ruff_configuration(root: &Path, configured: &str) -> IdeResult<Option<Pat
|
||||
}
|
||||
|
||||
/// The project interpreter: the configured one, else a project virtualenv
|
||||
/// (`.venv`, `venv`, …) in the project root, else the Python the project pins for mise / asdf.
|
||||
/// (`.venv`, `venv`, …) or pixi environment (`.pixi/envs/<env>`) in the project
|
||||
/// root, else the Python the project pins for mise / asdf.
|
||||
pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.python.interpreter)
|
||||
.or_else(|| project_venv_python(root))
|
||||
@@ -370,8 +371,8 @@ pub fn gradle_env(
|
||||
env
|
||||
}
|
||||
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`
|
||||
/// and `-Dmaven.repo.local=<dir>`.
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
|
||||
/// `-Dmaven.repo.local=<dir>` and `-T <count>` (the thread count).
|
||||
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
let m = &s.languages.java.maven;
|
||||
let mut out = Vec::new();
|
||||
@@ -381,6 +382,9 @@ pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
if let Some(dir) = setting_path(root, &m.local_repository) {
|
||||
out.push(format!("-Dmaven.repo.local={}", dir.to_string_lossy()));
|
||||
}
|
||||
if let Some(threads) = m.thread_count() {
|
||||
out.extend(["-T".to_owned(), threads.to_owned()]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -388,7 +392,7 @@ fn maven_settings_prefixes(args: &[String]) -> Vec<usize> {
|
||||
let mut prefixes = vec![0];
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
if arg == "-s" && args.get(i + 1).is_some() {
|
||||
if (arg == "-s" || arg == "-T") && args.get(i + 1).is_some() {
|
||||
i += 2;
|
||||
} else if arg.starts_with("-Dmaven.repo.local=") {
|
||||
i += 1;
|
||||
@@ -833,6 +837,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
{
|
||||
let plugin = vue::tsserver_plugin(&vue);
|
||||
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
|
||||
cfg.tsserver_project_extras.extensions = vec![vue::EXTENSION.into()];
|
||||
}
|
||||
if name == "vtsls"
|
||||
&& cfg.tsserver_project
|
||||
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
|
||||
{
|
||||
let node = node_dir(root, s).map(|d| d.join(exe("node"))).filter(|p| p.is_file()).or_else(|| which("node"));
|
||||
cfg.tsserver_project_extras.paths = vue::cli_paths(server_root, node.as_deref());
|
||||
}
|
||||
if name == vue::SERVER {
|
||||
configure_vue_typescript(cfg, root, server_root, s);
|
||||
@@ -932,6 +944,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -1034,22 +1047,28 @@ fn is_python_command(cmd: &str) -> bool {
|
||||
|
||||
const PY_RUNNERS: [&str; 3] = ["uv", "poetry", "pdm"];
|
||||
|
||||
/// [`maven_options`] as the groups they are passed in (`-s <file>`, `-Dmaven.repo.local=…`).
|
||||
/// [`maven_options`] as the groups they are passed in (`-s <file>`, `-Dmaven.repo.local=…`,
|
||||
/// `-T <count>`).
|
||||
fn maven_option_groups(options: &[String]) -> Vec<&[String]> {
|
||||
let mut groups = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < options.len() {
|
||||
let n = if options[i] == "-s" { 2.min(options.len() - i) } else { 1 };
|
||||
let n = if options[i] == "-s" || options[i] == "-T" { 2.min(options.len() - i) } else { 1 };
|
||||
groups.push(&options[i..i + n]);
|
||||
i += n;
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Whether `args` set what `group` sets: a user settings file, or the local repository.
|
||||
/// Whether `args` set what `group` sets: a user settings file, the local
|
||||
/// repository, or the thread count.
|
||||
fn sets_maven_option(args: &[String], group: &[String]) -> bool {
|
||||
match group.first().map(String::as_str) {
|
||||
Some("-s") => args.iter().any(|a| a == "-s" || a == "--settings" || a.starts_with("--settings=")),
|
||||
// `-T 4`, `--threads 4`, `-T4` and `--threads=4` all set the thread count.
|
||||
Some("-T") => args.iter().any(|a| {
|
||||
a == "-T" || a == "--threads" || a.starts_with("--threads=") || (a.starts_with("-T") && a.len() > 2)
|
||||
}),
|
||||
Some(flag) => {
|
||||
let key = flag.split_once('=').map_or(flag, |(k, _)| k);
|
||||
args.iter().any(|a| a.split_once('=').map_or(a.as_str(), |(k, _)| k) == key)
|
||||
|
||||
@@ -73,7 +73,7 @@ fn dedupe_by_real_path(paths: Vec<(PathBuf, &'static str)>) -> Vec<(PathBuf, &'s
|
||||
/// Project-local virtualenv directories checked by auto-detection, in order.
|
||||
pub(crate) const PROJECT_VENVS: [&str; 4] = [".venv", "venv", "env", ".env"];
|
||||
|
||||
/// `<root>/<venv>/bin/python` of the first project virtualenv.
|
||||
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment.
|
||||
pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
|
||||
PROJECT_VENVS
|
||||
.iter()
|
||||
@@ -81,6 +81,11 @@ pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
|
||||
.filter(|v| v.join("pyvenv.cfg").is_file())
|
||||
.map(|v| v.join(bin_dir()).join(exe("python")))
|
||||
.find(|p| p.is_file())
|
||||
.or_else(|| {
|
||||
subdirs(&root.join(".pixi/envs")).iter().find_map(|env| {
|
||||
[env.join(exe("python")), env.join("bin").join(exe("python"))].into_iter().find(|p| p.is_file())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `/usr/bin/python3` on macOS is a stub that opens an installer dialog when
|
||||
@@ -110,6 +115,14 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
|
||||
found.push((dir.join(bin_dir()).join(exe("python")), "venv"));
|
||||
}
|
||||
}
|
||||
// pixi environments (`.pixi/envs/<env>`), which are no virtualenvs.
|
||||
for env in subdirs(&root.join(".pixi/envs")) {
|
||||
let python =
|
||||
[env.join(exe("python")), env.join("bin").join(exe("python"))].into_iter().find(|p| p.is_file());
|
||||
if let Some(python) = python {
|
||||
found.push((python, "pixi"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(venv) = std::env::var("VIRTUAL_ENV") {
|
||||
found.push((Path::new(&venv).join(bin_dir()).join(exe("python")), "venv"));
|
||||
@@ -215,6 +228,10 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
|
||||
.map(|n| n.to_string_lossy().into_owned());
|
||||
format!("Python {short} (conda: {})", env.unwrap_or_default())
|
||||
}
|
||||
(None, "pixi") => {
|
||||
let env = pixi_env_name(path).unwrap_or_default();
|
||||
format!("Python {short} (pixi: {env})")
|
||||
}
|
||||
(None, "pyenv") => format!("Python {short} (pyenv)"),
|
||||
(None, tool @ ("uv" | "mise" | "asdf")) => format!("Python {short} ({tool})"),
|
||||
_ => format!("Python {short}"),
|
||||
@@ -224,11 +241,26 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
|
||||
name: label,
|
||||
version: Some(version),
|
||||
source: source.to_owned(),
|
||||
home: venv.or_else(|| path.parent().and_then(Path::parent).map(Path::to_path_buf)).map(Into::into),
|
||||
home: venv
|
||||
.or_else(|| (source == "pixi").then(|| pixi_env_home(path)).flatten())
|
||||
.or_else(|| path.parent().and_then(Path::parent).map(Path::to_path_buf))
|
||||
.map(Into::into),
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `.pixi/envs/<env>` of a pixi interpreter (`<env>/python`, `<env>/bin/python`).
|
||||
fn pixi_env_home(python: &Path) -> Option<PathBuf> {
|
||||
let dir = python.parent()?;
|
||||
let env = if dir.file_name().is_some_and(|n| n == "bin") { dir.parent()? } else { dir };
|
||||
(env.parent()?.file_name()? == "envs" && env.parent()?.parent()?.file_name()? == ".pixi").then(|| env.to_path_buf())
|
||||
}
|
||||
|
||||
/// The name of a pixi interpreter's environment (`<env>` of `.pixi/envs/<env>`).
|
||||
fn pixi_env_name(python: &Path) -> Option<String> {
|
||||
pixi_env_home(python)?.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn pyvenv_version(python: &Path) -> Option<String> {
|
||||
let cfg = std::fs::read_to_string(venv_of(python)?.join("pyvenv.cfg")).ok()?;
|
||||
cfg.lines().find_map(|l| {
|
||||
@@ -706,12 +738,20 @@ mod maven_path_tests {
|
||||
struct Subst {
|
||||
name: String,
|
||||
root: PathBuf,
|
||||
_lock: std::fs::File,
|
||||
}
|
||||
|
||||
impl Subst {
|
||||
fn new(target: &Path) -> Self {
|
||||
// Tests run in parallel and may race for the same free letter; only a drive that
|
||||
// shows this target's marker is ours.
|
||||
// Drive letters are shared across nextest's test processes; hold the lock until unmapping.
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(std::env::temp_dir().join("openidea-sdk-subst.lock"))
|
||||
.unwrap();
|
||||
lock.lock().unwrap();
|
||||
let marker = format!("{}.subst", target.file_name().unwrap().to_string_lossy());
|
||||
std::fs::write(target.join(&marker), "").unwrap();
|
||||
for letter in (b'D'..=b'Z').rev() {
|
||||
@@ -722,7 +762,7 @@ mod maven_path_tests {
|
||||
}
|
||||
let output = Command::new("subst").arg(&name).arg(target).output().unwrap();
|
||||
if output.status.success() && root.join(&marker).exists() {
|
||||
return Self { name, root };
|
||||
return Self { name, root, _lock: lock };
|
||||
}
|
||||
}
|
||||
panic!("no free drive for Maven path verification");
|
||||
@@ -781,3 +821,34 @@ mod maven_path_tests {
|
||||
assert_eq!(home, dunce::canonicalize(real.path()).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pixi_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_pixi_env_is_a_project_python_and_an_sdk_home() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let env = root.path().join(".pixi/envs/default");
|
||||
let bin = if cfg!(windows) { env.clone() } else { env.join("bin") };
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let python = bin.join(exe("python"));
|
||||
std::fs::write(&python, "").unwrap();
|
||||
|
||||
assert_eq!(project_venv_python(root.path()), Some(python.clone()));
|
||||
assert_eq!(pixi_env_home(&python), Some(env.clone()));
|
||||
assert_eq!(pixi_env_name(&python).as_deref(), Some("default"));
|
||||
|
||||
// A second env sorts after; the first with a Python wins.
|
||||
let other = root.path().join(".pixi/envs/aaa-empty");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
assert_eq!(project_venv_python(root.path()), Some(python));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_pixi_paths_have_no_pixi_home() {
|
||||
assert_eq!(pixi_env_home(Path::new("/usr/bin/python3")), None);
|
||||
assert_eq!(pixi_env_home(Path::new("/p/.venv/bin/python")), None);
|
||||
assert_eq!(pixi_env_home(Path::new("/p/envs/x/bin/python")), None);
|
||||
}
|
||||
}
|
||||
@@ -55,12 +55,16 @@ pub(crate) fn query_in(
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
if !env.iter().any(|(k, _)| *k == "PATH") {
|
||||
cmd.args(args).envs(env.iter().copied());
|
||||
query_command(cmd, timeout)
|
||||
}
|
||||
|
||||
/// [`query`] of a command built by the caller; `PATH` is the search path unless it sets one.
|
||||
pub(crate) fn query_command(mut cmd: Command, timeout: Duration) -> Option<String> {
|
||||
if !cmd.get_envs().any(|(k, _)| k == "PATH") {
|
||||
cmd.env("PATH", search_path());
|
||||
}
|
||||
let mut child = ide_core::process::prepare(&mut cmd)
|
||||
.args(args)
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
|
||||
@@ -82,7 +82,7 @@ pub fn project_libraries(root: &Path, settings: &Settings, dependencies: &[Build
|
||||
// ------------------------------------------------------------------ cache
|
||||
|
||||
/// Size and modification time of each manifest (`None`: missing).
|
||||
type Stamp = Vec<(PathBuf, Option<(SystemTime, u64)>)>;
|
||||
pub(crate) type Stamp = Vec<(PathBuf, Option<(SystemTime, u64)>)>;
|
||||
|
||||
struct Cached {
|
||||
/// Settings the result depends on.
|
||||
@@ -97,7 +97,7 @@ pub fn invalidate_go(root: &Path) {
|
||||
CACHE.lock().unwrap_or_else(|e| e.into_inner()).remove(&(root.to_path_buf(), "go"));
|
||||
}
|
||||
|
||||
fn stamp(files: &[PathBuf]) -> Stamp {
|
||||
pub(crate) fn stamp(files: &[PathBuf]) -> Stamp {
|
||||
files
|
||||
.iter()
|
||||
.map(|f| {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
//! The PHP language level: the one chosen in Settings › PHP, else the one the root
|
||||
//! `composer.json` declares (`config.platform.php`, else the lowest version `require.php` allows);
|
||||
//! the Intelephense storage that goes with it; the stub sets and include paths Intelephense indexes;
|
||||
//! and the PHPStan run that checks saved files.
|
||||
//! the PHPStan run that checks saved files; and whether an interpreter loads Xdebug.
|
||||
|
||||
use crate::apply::{merge, merge_init_options, setting_path};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
/// A PHP version and where it comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
@@ -205,6 +207,60 @@ pub fn phpstan_command(root: &Path, s: &Settings, files: &[PathBuf]) -> Option<C
|
||||
Some(cmd)
|
||||
}
|
||||
|
||||
/// A PHP interpreter's version and the Xdebug it loads.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PhpXdebug {
|
||||
pub php: ide_core::IpcPath,
|
||||
/// `PHP_VERSION`.
|
||||
pub php_version: String,
|
||||
/// The Xdebug version; `None`: not loaded, so PHP ignores the `xdebug.*` options a debug session sets.
|
||||
pub xdebug: Option<String>,
|
||||
}
|
||||
|
||||
const XDEBUG_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
|
||||
/// `php` printing its version and the loaded Xdebug's (nothing without one), with Xdebug off: a
|
||||
/// php.ini with `xdebug.start_with_request=yes` would connect to a listening debugger. Xdebug stays
|
||||
/// loaded in mode `off`, so it still reports its version. Run in `cwd`, where a version manager's
|
||||
/// `php` shim (asdf, mise, phpenv) picks the PHP it starts.
|
||||
fn xdebug_command(php: &Path, cwd: Option<&Path>) -> Command {
|
||||
let mut cmd = Command::new(php);
|
||||
cmd.args(["-r", r#"echo PHP_VERSION, "\n", phpversion("xdebug") ?: "";"#]).env("XDEBUG_MODE", "off");
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The version of `php` and of the Xdebug it loads, run in `cwd`. An error when `php` doesn't run,
|
||||
/// times out or prints something else.
|
||||
pub fn xdebug(php: &Path, cwd: Option<&Path>) -> IdeResult<PhpXdebug> {
|
||||
let out = crate::exec::query_command(xdebug_command(php, cwd), XDEBUG_TIMEOUT)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("cannot run {}", php.display())))?;
|
||||
let (php_version, xdebug) = parse_xdebug(&out)
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} printed no PHP version: {out}", php.display())))?;
|
||||
Ok(PhpXdebug { php: php.to_path_buf().into(), php_version, xdebug })
|
||||
}
|
||||
|
||||
/// The PHP version, then the Xdebug version when one is loaded: the last lines of the output, after
|
||||
/// the startup warnings PHP prints first with `display_startup_errors` (as a broken Xdebug build does).
|
||||
fn parse_xdebug(out: &str) -> Option<(String, Option<String>)> {
|
||||
let lines: Vec<&str> = out.lines().map(str::trim).collect();
|
||||
match lines[..] {
|
||||
[.., php, xdebug] if is_version(php) && is_version(xdebug) => Some((php.into(), Some(xdebug.into()))),
|
||||
[.., php] if is_version(php) => Some((php.into(), None)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `8.3.14`, `8.1.2-1ubuntu2.14`, `3.5.0alpha3`.
|
||||
fn is_version(s: &str) -> bool {
|
||||
s.starts_with(|c: char| c.is_ascii_digit())
|
||||
&& s.contains('.')
|
||||
&& s.chars().all(|c| c.is_ascii_alphanumeric() || ".-+~_".contains(c))
|
||||
}
|
||||
|
||||
type Version = (u32, u32, u32);
|
||||
|
||||
impl PhpLanguageLevel {
|
||||
@@ -521,6 +577,43 @@ mod tests {
|
||||
assert!(!args(" ").iter().any(|a| a.starts_with("--configuration")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_xdebug_probe_runs_with_xdebug_off() {
|
||||
let php = Path::new("/opt/homebrew/opt/[email protected]/bin/php");
|
||||
let project = Path::new("/work/app");
|
||||
let cmd = xdebug_command(php, Some(project));
|
||||
assert_eq!(cmd.get_program(), php.as_os_str());
|
||||
assert_eq!(cmd.get_current_dir(), Some(project), "where a php shim picks the version");
|
||||
assert_eq!(
|
||||
cmd.get_args().map(text).collect::<Vec<_>>(),
|
||||
["-r", r#"echo PHP_VERSION, "\n", phpversion("xdebug") ?: "";"#]
|
||||
);
|
||||
assert_eq!(env(&cmd), [("XDEBUG_MODE".to_string(), Some("off".to_string()))]);
|
||||
assert_eq!(xdebug_command(php, None).get_current_dir(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_xdebug_probe_reads_both_versions() {
|
||||
let found = |php: &str, xdebug: Option<&str>| Some((php.to_string(), xdebug.map(str::to_string)));
|
||||
assert_eq!(parse_xdebug("8.3.14\n3.4.7"), found("8.3.14", Some("3.4.7")));
|
||||
assert_eq!(parse_xdebug("8.1.33"), found("8.1.33", None));
|
||||
assert_eq!(parse_xdebug("8.1.2-1ubuntu2.14\r\n3.5.0alpha3"), found("8.1.2-1ubuntu2.14", Some("3.5.0alpha3")));
|
||||
assert_eq!(parse_xdebug("5.6.40\n2.5.5"), found("5.6.40", Some("2.5.5")));
|
||||
// display_startup_errors prints startup warnings before the script's output.
|
||||
let warning = "\nWarning: PHP Startup: Unable to load dynamic library 'xdebug.so' in Unknown on line 0";
|
||||
assert_eq!(parse_xdebug(&format!("{warning}\n8.1.33")), found("8.1.33", None));
|
||||
assert_eq!(parse_xdebug(&format!("{warning}\n8.3.14\n3.4.7")), found("8.3.14", Some("3.4.7")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_xdebug_probe_fails_on_other_output() {
|
||||
for out in ["", " ", "Could not open input file: -r", "8.3.14\nnot a version", "PHP", "8"] {
|
||||
assert_eq!(parse_xdebug(out), None, "{out:?}");
|
||||
}
|
||||
let missing = Path::new("/nonexistent/bin/php");
|
||||
assert!(xdebug(missing, None).is_err(), "no PHP is an error, not a PHP without Xdebug");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_level_names_its_source() {
|
||||
let found = |version: &str, source| Some(PhpLanguageLevel { version: version.into(), source });
|
||||
|
||||
@@ -16,25 +16,144 @@ pub struct PythonPackage {
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// Creates a virtualenv at `location` with `base -m venv` and returns its interpreter.
|
||||
/// The tool that creates a new Python environment in "Add Python Interpreter".
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum VenvTool {
|
||||
/// `base -m venv <location>`.
|
||||
Venv,
|
||||
/// `uv venv <location> --python <base>` (uv must be on PATH).
|
||||
Uv,
|
||||
/// `poetry env use <base>` in the project, then `poetry env info --path`.
|
||||
Poetry,
|
||||
/// `conda create -p <location> -y` (conda must be on PATH).
|
||||
Conda,
|
||||
}
|
||||
|
||||
/// Creates a virtualenv at `location` with `tool` and returns its interpreter.
|
||||
/// `base` is the interpreter uv / venv build on, or the one poetry's env uses.
|
||||
pub fn create_venv(
|
||||
tool: VenvTool,
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
if location.join("pyvenv.cfg").is_file() {
|
||||
create_venv_with(tool, base, location, which, cancel, on_line)
|
||||
}
|
||||
|
||||
/// [`create_venv`] with the tool lookup injectable (tests fake `uv` / `poetry`).
|
||||
pub(crate) fn create_venv_with(
|
||||
tool: VenvTool,
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
which: impl Fn(&str) -> Option<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
match tool {
|
||||
VenvTool::Venv | VenvTool::Uv => {
|
||||
if location.join("pyvenv.cfg").is_file() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::AlreadyExists,
|
||||
format!("{} already contains a virtual environment", location.display()),
|
||||
));
|
||||
}
|
||||
if let Some(parent) = location.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let (program, args) = match tool {
|
||||
VenvTool::Uv => {
|
||||
let uv = which("uv").ok_or_else(|| {
|
||||
IdeError::unavailable("uv is not installed (install it from https://docs.astral.sh/uv)")
|
||||
})?;
|
||||
(
|
||||
uv,
|
||||
vec![
|
||||
"venv".to_owned(),
|
||||
location.to_string_lossy().into_owned(),
|
||||
"--python".to_owned(),
|
||||
base.to_string_lossy().into_owned(),
|
||||
],
|
||||
)
|
||||
}
|
||||
_ => (base.to_path_buf(), venv_args(location)),
|
||||
};
|
||||
stream(&program, &args, None, &[], cancel, on_line)?;
|
||||
let python = location.join(bin_dir()).join(exe("python"));
|
||||
crate::discover::python_sdk(&python, "venv", location.parent().and_then(Path::parent))
|
||||
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
|
||||
}
|
||||
VenvTool::Poetry => create_poetry_env(base, location, &which, cancel, on_line),
|
||||
VenvTool::Conda => create_conda_env(base, location, &which, cancel, on_line),
|
||||
}
|
||||
}
|
||||
|
||||
/// `poetry env use <base>` in the project directory (the parent of `location`, which the
|
||||
/// dialog fills with `<root>/.venv` only as a hint — poetry keeps its envs under its own
|
||||
/// cache), then `poetry env info --path` for the interpreter it made or reused.
|
||||
fn create_poetry_env(
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
which: &dyn Fn(&str) -> Option<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
let poetry = which("poetry")
|
||||
.ok_or_else(|| IdeError::unavailable("Poetry is not installed (install it from https://python-poetry.org)"))?;
|
||||
let project = location
|
||||
.parent()
|
||||
.filter(|p| p.is_dir())
|
||||
.ok_or_else(|| IdeError::invalid("Poetry environments need an open project directory"))?;
|
||||
stream(
|
||||
&poetry,
|
||||
&["env".to_owned(), "use".to_owned(), base.to_string_lossy().into_owned()],
|
||||
Some(project),
|
||||
&[],
|
||||
cancel,
|
||||
on_line,
|
||||
)?;
|
||||
let home = query_in(&poetry, &["env", "info", "--path"], Some(project), &[], Duration::from_secs(30))
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| IdeError::internal("poetry created no environment".to_owned()))?;
|
||||
let python = home.join(bin_dir()).join(exe("python"));
|
||||
crate::discover::python_sdk(&python, "venv", Some(project))
|
||||
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
|
||||
}
|
||||
|
||||
/// `conda create -p <location> -y` builds an environment at the requested prefix.
|
||||
/// `base` pins the Python version (`python=<major.minor>`) when it reports one, so the
|
||||
/// created env matches the interpreter the user picked rather than conda's default.
|
||||
fn create_conda_env(
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
which: &dyn Fn(&str) -> Option<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
if location.join("conda-meta").is_dir() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::AlreadyExists,
|
||||
format!("{} already contains a virtual environment", location.display()),
|
||||
format!("{} already contains a conda environment", location.display()),
|
||||
));
|
||||
}
|
||||
let conda = which("conda")
|
||||
.ok_or_else(|| IdeError::unavailable("conda is not installed (install it from https://docs.conda.io)"))?;
|
||||
if let Some(parent) = location.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
stream(base, &venv_args(location), None, &[], cancel, on_line)?;
|
||||
let mut args = vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned(), "-y".to_owned()];
|
||||
if let Some(version) = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
|
||||
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned))
|
||||
{
|
||||
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
|
||||
if !short.is_empty() {
|
||||
args.push(format!("python={short}"));
|
||||
}
|
||||
}
|
||||
stream(&conda, &args, None, &[], cancel, on_line)?;
|
||||
let python = location.join(bin_dir()).join(exe("python"));
|
||||
crate::discover::python_sdk(&python, "venv", location.parent().and_then(Path::parent))
|
||||
crate::discover::python_sdk(&python, "conda", location.parent().and_then(Path::parent))
|
||||
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ fn server(name: &str) -> LanguageServerConfig {
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -291,6 +292,41 @@ fn project_jdk_and_maven_settings() {
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_options_carry_the_thread_count_into_the_command_line() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
assert!(maven_options(tmp.path(), &s).is_empty(), "empty settings add nothing");
|
||||
|
||||
s.languages.java.maven.user_settings = "m2/settings.xml".into();
|
||||
s.languages.java.maven.local_repository = "m2/repo".into();
|
||||
s.languages.java.maven.threads = "4".into();
|
||||
let settings_file = tmp.path().join("m2/settings.xml").to_string_lossy().into_owned();
|
||||
let repo = tmp.path().join("m2/repo").to_string_lossy().into_owned();
|
||||
assert_eq!(
|
||||
maven_options(tmp.path(), &s),
|
||||
["-s", settings_file.as_str(), &format!("-Dmaven.repo.local={repo}"), "-T", "4"]
|
||||
);
|
||||
|
||||
// A core multiplier passes through; anything Maven would reject is dropped
|
||||
// rather than failing every build.
|
||||
s.languages.java.maven.threads = "2.5C".into();
|
||||
assert!(maven_options(tmp.path(), &s).ends_with(&["-T".to_owned(), "2.5C".to_owned()]));
|
||||
s.languages.java.maven.threads = "abc".into();
|
||||
assert!(!maven_options(tmp.path(), &s).iter().any(|a| a == "-T"));
|
||||
|
||||
// Run configurations get the options ahead of the goals, once per launch.
|
||||
s.languages.java.maven.threads = "2C".into();
|
||||
let mut configs = vec![run("maven", "./mvnw", &["package"]), run("maven", "./mvnw", &["-T", "8", "package"])];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
let args: Vec<String> = configs[0].args.clone();
|
||||
assert_eq!(args[args.len() - 3..].join(" "), "-T 2C package", "the settings' thread count leads the goals");
|
||||
let args: Vec<String> = configs[1].args.clone();
|
||||
assert_eq!(args[args.len() - 3..].join(" "), "-T 8 package", "the configuration's own -T wins");
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].args.iter().filter(|a| a.as_str() == "-T").count(), 1, "applied once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_maven_goal_configs_take_the_configured_launcher() {
|
||||
if cfg!(windows) {
|
||||
@@ -684,6 +720,82 @@ fn venv_creation_ignores_modules_in_the_working_directory() {
|
||||
assert!(location.join("pyvenv.cfg").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_tools_are_reported_missing_before_they_run() {
|
||||
// Without uv / Poetry on PATH the error names the install, not a spawn failure.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let location = dir.path().join(".venv");
|
||||
let base = dir.path().join("python");
|
||||
fn none(_: &str) -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
let uv = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Uv,
|
||||
&base,
|
||||
&location,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(uv.message.contains("uv is not installed"), "{}", uv.message);
|
||||
let poetry = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Poetry,
|
||||
&base,
|
||||
&location,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(poetry.message.contains("Poetry is not installed"), "{}", poetry.message);
|
||||
let conda = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Conda,
|
||||
&base,
|
||||
&location,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(conda.message.contains("conda is not installed"), "{}", conda.message);
|
||||
// An existing environment is refused before any tool runs.
|
||||
std::fs::create_dir_all(&location).unwrap();
|
||||
std::fs::write(location.join("pyvenv.cfg"), "home = /python").unwrap();
|
||||
let again = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Uv,
|
||||
&base,
|
||||
&location,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(again.message.contains("already contains a virtual environment"), "{}", again.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_existing_conda_environment_is_not_recreated() {
|
||||
// `conda-meta/` marks a conda prefix: refuse before `conda create` would fail obscurely.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let location = dir.path().join("envs").join("ds");
|
||||
let base = dir.path().join("python");
|
||||
std::fs::create_dir_all(location.join("conda-meta")).unwrap();
|
||||
fn none(_: &str) -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
let err = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Conda,
|
||||
&base,
|
||||
&location,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("already contains a conda environment"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_dir_is_fresh_and_empty() {
|
||||
let a = crate::python::neutral_dir().unwrap();
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
//! Vue Language Server (Volar 3): the TypeScript it loads as a library, and the
|
||||
//! `@vue/typescript-plugin` that vtsls' tsserver hosts for it (hybrid mode).
|
||||
|
||||
use crate::libraries::{Stamp, package_dependencies, stamp};
|
||||
use crate::npm::{find_command, package_dir};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) const SERVER: &str = "vue-language-server";
|
||||
const PACKAGE: &str = "@vue/language-server";
|
||||
const PLUGIN: &str = "@vue/typescript-plugin";
|
||||
/// The file extension the plugin adds to tsserver.
|
||||
pub(crate) const EXTENSION: &str = "vue";
|
||||
const CLI_SERVICE: &str = "@vue/cli-service";
|
||||
const CLI_CONFIG_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const ALIASES_MARKER: &str = "openidea-webpack-aliases:";
|
||||
/// Prints the `resolve.alias` of the webpack configuration module `argv[1]`, after whatever
|
||||
/// the configuration itself prints.
|
||||
const PRINT_ALIASES: &str = "const c = require(process.argv[1]); const a = (c.resolve && c.resolve.alias) || {}; \
|
||||
const e = Array.isArray(a) ? a.map((x) => [x.name, x.alias]) : Object.entries(a); \
|
||||
process.stdout.write('\\n' + process.argv[2] + JSON.stringify(e));";
|
||||
|
||||
type Paths = BTreeMap<String, Vec<String>>;
|
||||
static CLI_PATHS: LazyLock<Mutex<HashMap<PathBuf, (Stamp, Paths)>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// The TypeScript `lib` directory has the language-service API (`typescript.js`).
|
||||
/// TypeScript 7, the native port, ships only `tsc`.
|
||||
@@ -36,6 +53,81 @@ pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// `compilerOptions.paths` for the webpack aliases of a Vue CLI project at `root` (`@/*` →
|
||||
/// `<root>/src/*`), for its tsserver project when it has no `jsconfig.json`: tsserver can't
|
||||
/// read webpack configurations, so `@/` imports resolve to nothing, and a mixin imported
|
||||
/// that way makes the component's whole `this` `any`. Like IntelliJ, evaluates the
|
||||
/// configuration `@vue/cli-service` resolves with the project's `vue.config.js` (the project
|
||||
/// is trusted: language servers only run then); else the alias Vue CLI always adds.
|
||||
/// Empty for other projects.
|
||||
pub(crate) fn cli_paths(root: &Path, node: Option<&Path>) -> Paths {
|
||||
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else { return Paths::new() };
|
||||
if !package_dependencies(&manifest).iter().any(|d| d == CLI_SERVICE) {
|
||||
return Paths::new();
|
||||
}
|
||||
let config = root
|
||||
.ancestors()
|
||||
.map(|dir| dir.join("node_modules").join(CLI_SERVICE).join("webpack.config.js"))
|
||||
.find(|f| f.is_file());
|
||||
let mut inputs: Vec<PathBuf> =
|
||||
["package.json", "vue.config.js", "vue.config.cjs", "vue.config.mjs"].iter().map(|f| root.join(f)).collect();
|
||||
inputs.extend(config.iter().cloned());
|
||||
inputs.extend(node.map(Path::to_path_buf));
|
||||
let now = stamp(&inputs);
|
||||
if let Some((then, paths)) = CLI_PATHS.lock().unwrap_or_else(|e| e.into_inner()).get(root)
|
||||
&& *then == now
|
||||
{
|
||||
return paths.clone();
|
||||
}
|
||||
let aliases = config
|
||||
.zip(node)
|
||||
.and_then(|(config, node)| webpack_aliases(root, &config, node))
|
||||
.unwrap_or_else(|| vec![("@".into(), root.join("src").to_string_lossy().into_owned())]);
|
||||
let paths = alias_paths(&aliases);
|
||||
CLI_PATHS.lock().unwrap_or_else(|e| e.into_inner()).insert(root.to_path_buf(), (now, paths.clone()));
|
||||
paths
|
||||
}
|
||||
|
||||
/// `[alias, target]` pairs of the webpack configuration module `config`.
|
||||
fn webpack_aliases(root: &Path, config: &Path, node: &Path) -> Option<Vec<(String, String)>> {
|
||||
let root_s = root.to_string_lossy();
|
||||
let out = crate::exec::query_in(
|
||||
node,
|
||||
&["-e", PRINT_ALIASES, &config.to_string_lossy(), ALIASES_MARKER],
|
||||
Some(root),
|
||||
&[("VUE_CLI_CONTEXT", &root_s), ("NODE_ENV", "development")],
|
||||
CLI_CONFIG_TIMEOUT,
|
||||
);
|
||||
let json = out.as_deref().and_then(|o| o.rsplit_once(ALIASES_MARKER)).map(|(_, json)| json);
|
||||
let Some(pairs) = json.and_then(|j| serde_json::from_str::<Vec<(serde_json::Value, serde_json::Value)>>(j).ok())
|
||||
else {
|
||||
tracing::debug!("no webpack aliases from {}", config.display());
|
||||
return None;
|
||||
};
|
||||
Some(
|
||||
pairs
|
||||
.into_iter()
|
||||
.filter_map(|(name, target)| Some((name.as_str()?.to_owned(), target.as_str()?.to_owned())))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Directory aliases as `paths`; `name$` (exact module) and file aliases have no equivalent.
|
||||
fn alias_paths(aliases: &[(String, String)]) -> Paths {
|
||||
let mut paths = Paths::new();
|
||||
for (name, target) in aliases {
|
||||
let dir = Path::new(target);
|
||||
if name.is_empty() || name.ends_with('$') || name.contains('*') || !dir.is_absolute() || !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let dir = target.replace('\\', "/");
|
||||
let dir = dir.trim_end_matches('/');
|
||||
paths.insert(format!("{name}/*"), vec![format!("{dir}/*")]);
|
||||
paths.insert(name.clone(), vec![dir.to_owned()]);
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
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@6 \
|
||||
@@ -80,6 +172,59 @@ mod tests {
|
||||
assert_eq!(server_package("not-installed", &path), None);
|
||||
}
|
||||
|
||||
fn cli_project(t: &Path) {
|
||||
std::fs::create_dir_all(t.join("src/components")).unwrap();
|
||||
std::fs::write(t.join("package.json"), r#"{"devDependencies":{"@vue/cli-service":"~5.0.0"}}"#).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vue_cli_projects_get_the_at_alias_without_their_webpack_configuration() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
std::fs::write(t.join("package.json"), r#"{"dependencies":{"vue":"^2.6.14"}}"#).unwrap();
|
||||
assert!(cli_paths(t, None).is_empty());
|
||||
cli_project(t);
|
||||
let src = t.join("src").to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(
|
||||
cli_paths(t, None),
|
||||
Paths::from([("@".into(), vec![src.clone()]), ("@/*".into(), vec![format!("{src}/*")])])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vue_cli_aliases_come_from_the_resolved_webpack_configuration() {
|
||||
let Some(node) = crate::exec::which("node") else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
cli_project(t);
|
||||
let service = t.join("node_modules/@vue/cli-service");
|
||||
std::fs::create_dir_all(&service).unwrap();
|
||||
// What `vue.config.js` can add, and what the configuration may print while loading.
|
||||
std::fs::write(
|
||||
service.join("webpack.config.js"),
|
||||
r#"const path = require('path');
|
||||
console.log('loading plugins');
|
||||
module.exports = { resolve: { alias: {
|
||||
'@': path.join(process.env.VUE_CLI_CONTEXT, 'src'),
|
||||
comps: path.join(process.env.VUE_CLI_CONTEXT, 'src/components'),
|
||||
vue$: 'vue/dist/vue.runtime.esm.js',
|
||||
missing: path.join(process.env.VUE_CLI_CONTEXT, 'nowhere'),
|
||||
} } };"#,
|
||||
)
|
||||
.unwrap();
|
||||
let slash = |p: PathBuf| p.to_string_lossy().replace('\\', "/");
|
||||
let (src, comps) = (slash(t.join("src")), slash(t.join("src/components")));
|
||||
assert_eq!(
|
||||
cli_paths(t, Some(&node)),
|
||||
Paths::from([
|
||||
("@".into(), vec![src.clone()]),
|
||||
("@/*".into(), vec![format!("{src}/*")]),
|
||||
("comps".into(), vec![comps.clone()]),
|
||||
("comps/*".into(), vec![format!("{comps}/*")]),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_typescript_skips_typescript_7() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
//!
|
||||
//! zsh starts with `ZDOTDIR` pointing at generated startup files that source
|
||||
//! the user's own ones first; bash gets an `--init-file` that replays the
|
||||
//! login sequence; fish gets an `--init-command`.
|
||||
//! login sequence; fish gets an `--init-command`. The generated `.zshrc` hands
|
||||
//! `ZDOTDIR` (and, if a startup file resolved it against the generated
|
||||
//! directory, `HISTFILE`) back to the user for login shells too, so history
|
||||
//! lands in `~/.zsh_history` despite the `zsh -l` start.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -36,14 +39,20 @@ _openidea_preexec() { printf '\e]133;C\a' }
|
||||
# First, so the command counts as finished before other hooks set the prompt's title.
|
||||
precmd_functions=(_openidea_osc7 ${precmd_functions:#_openidea_osc7})
|
||||
preexec_functions+=(_openidea_preexec)
|
||||
if [[ ! -o login ]]; then
|
||||
ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
|
||||
# Startup files that ran before this one (e.g. /etc/zshrc's
|
||||
# HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history) resolved HISTFILE against this
|
||||
# generated directory, since OpenIDEA starts zsh as a login shell (-l) and the
|
||||
# restore below used to be gated on non-login. Hand both back to the user: a
|
||||
# HISTFILE they configured themselves is never under $_openidea_dir and is kept.
|
||||
if [[ $HISTFILE == "$_openidea_dir"/* ]]; then
|
||||
HISTFILE=${OPENIDEA_USER_ZDOTDIR:-$HOME}/.zsh_history
|
||||
fi
|
||||
ZDOTDIR=${OPENIDEA_USER_ZDOTDIR:-$HOME}
|
||||
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
|
||||
"#;
|
||||
|
||||
const ZLOGIN: &str = r#"# OpenIDEA shell integration (generated)
|
||||
ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
ZDOTDIR=${OPENIDEA_USER_ZDOTDIR:-$HOME}
|
||||
[[ -f $ZDOTDIR/.zlogin ]] && . $ZDOTDIR/.zlogin
|
||||
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
|
||||
"#;
|
||||
@@ -183,4 +192,28 @@ mod tests {
|
||||
assert_eq!(env["OPENIDEA_USER_ZDOTDIR"], "/home/me/zsh");
|
||||
assert_eq!(args, vec!["-l"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zsh_restores_zdotdir_and_histfile_for_login_shells() {
|
||||
// OpenIDEA starts zsh as a login shell (`zsh -l`), so the restore at the
|
||||
// end of the generated .zshrc must not be gated on non-login shells,
|
||||
// and HISTFILE resolved against the generated directory (e.g. by
|
||||
// /etc/zshrc's `HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history`) must be
|
||||
// re-pointed at the user's directory.
|
||||
assert!(!ZSHRC.contains("[[ ! -o login ]]"));
|
||||
assert!(ZSHRC.contains("HISTFILE=${OPENIDEA_USER_ZDOTDIR:-$HOME}/.zsh_history"));
|
||||
assert!(ZSHRC.contains("ZDOTDIR=${OPENIDEA_USER_ZDOTDIR:-$HOME}"));
|
||||
assert!(ZSHRC.contains("unset OPENIDEA_USER_ZDOTDIR _openidea_dir"));
|
||||
// Login shells that never read .zshrc (non-interactive ones) restore via .zlogin.
|
||||
assert!(ZLOGIN.contains("ZDOTDIR=${OPENIDEA_USER_ZDOTDIR:-$HOME}"));
|
||||
assert!(ZLOGIN.contains("unset OPENIDEA_USER_ZDOTDIR _openidea_dir"));
|
||||
if cfg!(windows) {
|
||||
return; // apply() only integrates on Unix
|
||||
}
|
||||
let mut args = vec!["-l".to_owned()];
|
||||
let mut env = BTreeMap::from([("ZDOTDIR".to_owned(), "/home/me/zsh".to_owned())]);
|
||||
assert!(apply("zsh", &mut args, &mut env));
|
||||
let zshrc = std::fs::read_to_string(PathBuf::from(&env["ZDOTDIR"]).join(".zshrc")).unwrap();
|
||||
assert!(zshrc.contains("HISTFILE=${OPENIDEA_USER_ZDOTDIR:-$HOME}/.zsh_history"));
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,36 @@ mod tests {
|
||||
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kmp_lsp_assets_include_the_native_jar_indexer() {
|
||||
let names = [
|
||||
"kmp-lsp-darwin-aarch64.gz",
|
||||
"kmp-lsp-darwin-aarch64.tar.gz",
|
||||
"kmp-lsp-darwin-x86_64.tar.gz",
|
||||
"kmp-lsp-linux-aarch64.tar.gz",
|
||||
"kmp-lsp-linux-x86_64.tar.gz",
|
||||
"kmp-lsp-windows-x86_64.zip",
|
||||
"kmp-lsp-windows-aarch64.zip",
|
||||
"kmp-lsp-v0.27.0.vsix",
|
||||
"kmp-lsp-win32-x64-v0.27.0.vsix",
|
||||
"kmp-lsp-win32-arm64-v0.27.0.vsix",
|
||||
];
|
||||
let rules = crate::registry::find("kmp-lsp").unwrap().asset_rules();
|
||||
for (os, arch, expected) in [
|
||||
(Os::Mac, Arch::Arm64, names[1]),
|
||||
(Os::Mac, Arch::X64, names[2]),
|
||||
(Os::Linux, Arch::Arm64, names[3]),
|
||||
(Os::Linux, Arch::X64, names[4]),
|
||||
(Os::Windows, Arch::X64, names[8]),
|
||||
(Os::Windows, Arch::Arm64, names[9]),
|
||||
] {
|
||||
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
|
||||
}
|
||||
// The plain gzip, Windows zip and universal VSIX omit the sidecar or server.
|
||||
assert_eq!(select_asset(&[names[0]], rules, MAC_ARM), None);
|
||||
assert_eq!(select_asset(&names[5..8], rules, WIN), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rosetta_fallback_and_missing() {
|
||||
let names = ["zls-x86_64-macos.tar.xz", "zls-x86_64-linux.tar.xz", "zls-x86_64-windows.zip"];
|
||||
|
||||
@@ -618,6 +618,30 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/eclipse-jdtls/eclipse.jdt.ls",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "kmp-lsp",
|
||||
display: "kmp-lsp",
|
||||
kind: LanguageServer,
|
||||
commands: &["kmp-lsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "Hessesian/kmp-lsp" },
|
||||
// These distributions include the native JAR indexer next to the server.
|
||||
// The single-binary .gz and Windows .zip assets do not.
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "kmp-lsp-darwin-aarch64.tar.gz"),
|
||||
rule(Mac, X64, "kmp-lsp-darwin-x86_64.tar.gz"),
|
||||
rule(Linux, Arm64, "kmp-lsp-linux-aarch64.tar.gz"),
|
||||
rule(Linux, X64, "kmp-lsp-linux-x86_64.tar.gz"),
|
||||
rule(Windows, Arm64, "kmp-lsp-win32-arm64-*.vsix"),
|
||||
rule(Windows, X64, "kmp-lsp-win32-x64-*.vsix"),
|
||||
],
|
||||
locate: &["kmp-lsp"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("kmp-lsp"),
|
||||
homepage: "https://github.com/Hessesian/kmp-lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "java-debug",
|
||||
display: "Java Debugger (Microsoft java-debug)",
|
||||
|
||||
@@ -170,6 +170,10 @@ fn interchangeable_servers_list_their_alternatives() {
|
||||
assert_eq!(find(&list, name).alternatives, python);
|
||||
}
|
||||
assert_eq!(find(&list, "vtsls").alternatives, ["vtsls", "typescript-language-server"]);
|
||||
for name in ["jdtls", "kmp-lsp"] {
|
||||
assert_eq!(find(&list, name).alternatives, ["jdtls", "kmp-lsp"]);
|
||||
assert_eq!(find(&list, name).languages, ["Java"]);
|
||||
}
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
|
||||
@@ -1087,8 +1087,19 @@ impl Repo {
|
||||
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
|
||||
/// remote-tracking start point (`origin/x`) becomes the new branch's upstream.
|
||||
pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
|
||||
self.create_branch_with_overwrite(name, start, checkout, false)
|
||||
}
|
||||
|
||||
/// Creates a branch or moves its tip when overwrite is explicitly enabled.
|
||||
pub fn create_branch_with_overwrite(
|
||||
&self,
|
||||
name: &str,
|
||||
start: Option<&str>,
|
||||
checkout: bool,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::create_branch(self, name, start, checkout)
|
||||
write::create_branch(self, name, start, checkout, overwrite)
|
||||
}
|
||||
/// Undo Commit: resets the current branch to the parent of `commit` (which must be
|
||||
/// HEAD and not a merge) keeping its changes staged; undoing the initial commit
|
||||
|
||||
@@ -641,7 +641,13 @@ fn stash_count(r: &Repo) -> IdeResult<usize> {
|
||||
}
|
||||
|
||||
/// Creates `name` at `start` (default HEAD); a remote-tracking start point is tracked.
|
||||
pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
|
||||
pub(crate) fn create_branch(
|
||||
r: &Repo,
|
||||
name: &str,
|
||||
start: Option<&str>,
|
||||
checkout: bool,
|
||||
overwrite: bool,
|
||||
) -> IdeResult<()> {
|
||||
let name = name.trim();
|
||||
let valid = !name.is_empty()
|
||||
&& !name.starts_with('-')
|
||||
@@ -658,7 +664,12 @@ pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout:
|
||||
let repo = r.gix()?;
|
||||
resolve(&repo, s)?;
|
||||
}
|
||||
let mut args = if checkout { vec!["switch", "-c", name] } else { vec!["branch", "--", name] };
|
||||
let mut args = match (checkout, overwrite) {
|
||||
(true, false) => vec!["switch", "-c", name],
|
||||
(true, true) => vec!["switch", "-C", name],
|
||||
(false, false) => vec!["branch", "--", name],
|
||||
(false, true) => vec!["branch", "--force", "--", name],
|
||||
};
|
||||
args.extend(start);
|
||||
run(r.root(), &args, None).map(|_| ())
|
||||
}
|
||||
|
||||
@@ -950,6 +950,36 @@ fn branch_create_checkout_merge_rebase_delete() {
|
||||
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "unmerged"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_overwrite_preserves_the_ref_if_checkout_fails() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "base\n");
|
||||
let base = fx.commit_all("base");
|
||||
fx.write("a.txt", "main\n");
|
||||
let tip = fx.commit_all("main");
|
||||
let repo = fx.repo();
|
||||
repo.create_branch("topic", None, false).unwrap();
|
||||
|
||||
repo.create_branch_with_overwrite("topic", Some(&base), false, true).unwrap();
|
||||
assert_eq!(fx.git(&["rev-parse", "topic"]), base);
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD"]), tip);
|
||||
|
||||
repo.create_branch_with_overwrite("topic", Some(&tip), false, true).unwrap();
|
||||
fx.write("a.txt", "dirty\n");
|
||||
assert!(repo.create_branch_with_overwrite("topic", Some(&base), true, true).is_err());
|
||||
assert_eq!(fx.git(&["rev-parse", "topic"]), tip);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("a.txt"), "dirty\n");
|
||||
|
||||
fx.write("a.txt", "main\n");
|
||||
repo.create_branch_with_overwrite("topic", Some(&base), true, true).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD"]), base);
|
||||
|
||||
repo.create_branch_with_overwrite("topic", Some(&tip), true, true).unwrap();
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD"]), tip);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_branch_from_remote_branch_tracks_it() {
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Java language servers
|
||||
|
||||
Settings › Languages & Frameworks › Language Servers lists Eclipse JDT Language
|
||||
Server (`jdtls`) and [kmp-lsp](https://github.com/Hessesian/kmp-lsp). Select either
|
||||
tool and use **Language server for Java** to choose one. The choice can be global
|
||||
or limited to the current project. **Automatic** prefers jdtls and falls back to
|
||||
kmp-lsp when jdtls is not installed; **None** disables both.
|
||||
|
||||
Install kmp-lsp from that page, or point its executable path at an existing
|
||||
installation. The IDE downloads a platform distribution containing both kmp-lsp
|
||||
and its native JAR indexer. Reinstall and uninstall manage both together.
|
||||
|
||||
kmp-lsp offers syntax-based Java code insight without running a JVM. It does not
|
||||
provide JDT's compiler analysis, Lombok integration, or JDT-specific refactorings.
|
||||
Java Application builds, classpath discovery and the Microsoft Java debugger still
|
||||
require jdtls; use jdtls for those flows. Maven and Gradle build tasks can run
|
||||
independently of the selected code-insight server.
|
||||
|
||||
This built-in choice applies to Java. Kotlin and Swift keep their existing server
|
||||
choices. To use another server, add it with **New Language Server**, assign its
|
||||
languages, and disable the servers it replaces.
|
||||
@@ -19,6 +19,7 @@ const TASK = {
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
capabilities: { fork: true, rollback: true, steer: true, images: true },
|
||||
};
|
||||
|
||||
const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
||||
@@ -65,7 +66,15 @@ async function openReply(page: Page, text: string, imageData?: string) {
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, [{ type: "agent", text }]]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{ type: "user", text: "Show Markdown", attachments: [], sentMs: 0, doneMs: 1, steered: false },
|
||||
{ type: "agent", text },
|
||||
],
|
||||
],
|
||||
]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
@@ -149,3 +158,182 @@ test("loads local and web reply images", async ({ page }) => {
|
||||
.toBe(1);
|
||||
}
|
||||
});
|
||||
|
||||
test("copies reply Markdown with the keyboard and keeps code copying separate", async ({ page, context }) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const reply = await openReply(page, REPLY);
|
||||
const copy = page.getByRole("button", { name: "Copy Markdown", exact: true });
|
||||
const actions = copy.locator("..");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(actions).toHaveCSS("opacity", "0");
|
||||
await copy.focus();
|
||||
await expect(actions).toHaveCSS("opacity", "1");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("button", { name: "Copied", exact: true })).toBeVisible();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(REPLY);
|
||||
await reply.getByRole("button", { name: "Copy Code", exact: true }).click();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("const a = 1;");
|
||||
});
|
||||
|
||||
test("reveals message actions on hover without shifting content and quotes into the draft", async ({ page }) => {
|
||||
const reply = await openReply(page, REPLY);
|
||||
const copy = page.getByRole("button", { name: "Copy Markdown", exact: true });
|
||||
const actions = copy.locator("..");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(actions).toHaveCSS("opacity", "0");
|
||||
const before = await reply.boundingBox();
|
||||
await reply.hover();
|
||||
await expect(actions).toHaveCSS("opacity", "1");
|
||||
expect(await reply.boundingBox()).toEqual(before);
|
||||
await expect(actions.getByRole("button")).toHaveCount(4);
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(actions).toHaveCSS("opacity", "0");
|
||||
const userCopy = page.getByRole("button", { name: "Copy", exact: true });
|
||||
await expect(userCopy.locator("..")).toHaveCSS("opacity", "0");
|
||||
await page.getByText("Show Markdown", { exact: true }).hover();
|
||||
await expect(userCopy.locator("..")).toHaveCSS("opacity", "1");
|
||||
await reply.hover();
|
||||
await page.getByRole("button", { name: "Quote Reply", exact: true }).click();
|
||||
const draft = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await expect(draft).toBeFocused();
|
||||
await expect(draft).toHaveValue(
|
||||
REPLY.trimEnd()
|
||||
.split("\n")
|
||||
.map((line) => (line ? `> ${line}` : ">"))
|
||||
.join("\n") + "\n\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps chat history readable and selections free of timestamps and status labels", async ({ page, context }) => {
|
||||
await page.setViewportSize({ width: 1800, height: 1000 });
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await openReply(page, "Hi! What would you like to work on?");
|
||||
await page.evaluate(async (task) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
const user = (text: string) => ({ type: "user", text, attachments: [], sentMs: 1, doneMs: 5001, steered: false });
|
||||
store.useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
user("hi"),
|
||||
{ type: "agent", text: "Hi! What would you like to work on?" },
|
||||
user("im bob"),
|
||||
{ type: "agent", text: "Hi Bob! What are we working on today?" },
|
||||
user("yes"),
|
||||
{ type: "thought", text: "**Requesting task context**" },
|
||||
{ type: "agent", text: "What would you like me to proceed with?" },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
}, TASK);
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
const replies = stream.locator("[class*='_reply_']");
|
||||
await expect(replies).toHaveCount(3);
|
||||
const geometry = await stream.evaluate((root) => {
|
||||
const reply = root.querySelector<HTMLElement>("[class*='_reply_']")!;
|
||||
const bubble = root.querySelector<HTMLElement>("[class*='_user_']")!;
|
||||
const composer = root
|
||||
.closest("[class*='_conversation_']")!
|
||||
.querySelector<HTMLElement>("[class*='_composerArea_']")!;
|
||||
const rr = reply.getBoundingClientRect();
|
||||
const br = bubble.getBoundingClientRect();
|
||||
const cr = composer.getBoundingClientRect();
|
||||
return {
|
||||
reply: rr.width,
|
||||
root: root.clientWidth,
|
||||
bubbleLeft: br.left,
|
||||
replyLeft: rr.left,
|
||||
bubbleRight: br.right,
|
||||
replyRight: rr.right,
|
||||
columnCenter: (rr.left + rr.right) / 2,
|
||||
composerCenter: (cr.left + cr.right) / 2,
|
||||
};
|
||||
});
|
||||
expect(geometry.reply).toBe(900);
|
||||
expect(geometry.reply).toBeLessThan(geometry.root);
|
||||
expect(Math.abs(geometry.bubbleRight - geometry.replyRight)).toBeLessThan(1);
|
||||
expect(Math.abs(geometry.bubbleLeft - geometry.replyLeft)).toBeLessThan(1);
|
||||
expect(Math.abs(geometry.columnCenter - geometry.composerCenter)).toBeLessThan(1);
|
||||
await stream.getByText("hi", { exact: true }).hover();
|
||||
await expect(stream.locator("[class*='_messageMeta_']").first()).toHaveCSS("opacity", "1");
|
||||
const selected = await stream.evaluate((root) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(root);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
return selection.toString();
|
||||
});
|
||||
expect(selected).toContain("hi");
|
||||
expect(selected).toContain("Hi Bob!");
|
||||
expect(selected).toContain("What would you like me to proceed with?");
|
||||
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
|
||||
await stream.locator("[class*='_thought_'] > summary").click();
|
||||
await expect(stream.getByText("Requesting task context", { exact: true })).toBeVisible();
|
||||
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
|
||||
await page.evaluate(async (id) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.dockTask(id);
|
||||
}, TASK.id);
|
||||
await expect(stream).toBeVisible();
|
||||
const narrow = await stream.evaluate((root) => ({
|
||||
width: root.clientWidth,
|
||||
content: root.scrollWidth,
|
||||
reply: root.querySelector<HTMLElement>("[class*='_reply_']")!.getBoundingClientRect().width,
|
||||
padding:
|
||||
Number.parseFloat(getComputedStyle(root).paddingLeft) + Number.parseFloat(getComputedStyle(root).paddingRight),
|
||||
}));
|
||||
expect(narrow.width).toBeGreaterThan(0);
|
||||
expect(narrow.content).toBeLessThanOrEqual(narrow.width);
|
||||
expect(Math.abs(narrow.reply - (narrow.width - narrow.padding))).toBeLessThan(1);
|
||||
});
|
||||
|
||||
test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const reply = await openReply(page, "A short answer.");
|
||||
const copy = page.getByRole("button", { name: "Copy Markdown", exact: true });
|
||||
await reply.hover();
|
||||
const box = await copy.boundingBox();
|
||||
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2, { steps: 20 });
|
||||
await expect(copy.locator("..")).toHaveCSS("opacity", "1");
|
||||
await copy.click();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("A short answer.");
|
||||
});
|
||||
|
||||
test("selects through code blocks and tables while keeping copy controls outside the code", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const tree = "rust/\n├── Cargo.toml\n└── src/\n └── main.rs";
|
||||
const flow = "内置文本 SAMPLE\n ↓ parser::parse\nVec<Item>\n ↓ Inventory::add\n终端输出";
|
||||
const text = `项目结构:\n\n\`\`\`text\n${tree}\n\`\`\`\n\n| 模块 | 职责 |\n| --- | --- |\n| main.rs | 程序入口 |\n\n数据流是:\n\n\`\`\`text\n${flow}\n\`\`\``;
|
||||
const reply = await openReply(page, text);
|
||||
await expect(reply.getByRole("button", { name: "Copy Code", exact: true })).toHaveCount(2);
|
||||
const selected = await reply.evaluate((root) => {
|
||||
const codes = [...root.querySelectorAll("pre > code")];
|
||||
if (codes.some((code) => code.parentElement!.querySelector("button"))) throw new Error("Control in code selection");
|
||||
const start = root.querySelector("p")!.firstChild!;
|
||||
const end = codes.at(-1)!.lastChild!;
|
||||
window.getSelection()!.setBaseAndExtent(start, 0, end, end.textContent!.length);
|
||||
return window.getSelection()!.toString();
|
||||
});
|
||||
expect(selected).toContain(tree);
|
||||
expect(selected).toContain("程序入口");
|
||||
expect(selected).toContain(flow);
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
|
||||
await page.evaluate(() => window.getSelection()!.removeAllRanges());
|
||||
const copies = reply.getByRole("button", { name: "Copy Code", exact: true });
|
||||
await copies.first().click();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(tree);
|
||||
await copies.last().click();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(flow);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "long-chat",
|
||||
title: "Long conversation",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
provider: "codex",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[] => [
|
||||
{ type: "user", text: `Request ${turn}`, attachments: [], steered: false },
|
||||
...["read", "execute", "edit"].map((kind): AgentEntry => ({
|
||||
type: "tool",
|
||||
id: `${turn}-${kind}`,
|
||||
kind,
|
||||
title: `${kind} src/module-${turn}.ts`,
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: Array.from({ length: 80 }, (_, line) => `output ${turn}:${line}`).join("\n"),
|
||||
diffs: [],
|
||||
})),
|
||||
{ type: "thought", text: `Checking module ${turn}.\n\n${"Details of the investigation. ".repeat(30)}` },
|
||||
{
|
||||
type: "agent",
|
||||
text: `Reply ${turn}\n\n- Checked the module.\n- Updated the implementation.\n\n\`\`\`text\nmodule-${turn}\n src/\n tests/\n\`\`\``,
|
||||
},
|
||||
]).flat();
|
||||
|
||||
async function openHistory(page: Page) {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task, entries }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries },
|
||||
);
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
await expect(stream.locator(":scope > *")).toHaveCount(entries.length);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
return stream;
|
||||
}
|
||||
|
||||
for (const selected of [false, true]) {
|
||||
test(`keeps long-chat scroll geometry stable while jumping through history (selected: ${selected})`, async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const stream = await openHistory(page);
|
||||
const result = await stream.evaluate(async (el, selected) => {
|
||||
let text = "";
|
||||
if (selected) {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
window.getSelection()!.removeAllRanges();
|
||||
window.getSelection()!.addRange(range);
|
||||
text = window.getSelection()!.toString();
|
||||
}
|
||||
await new Promise(requestAnimationFrame);
|
||||
const initialHeight = el.scrollHeight;
|
||||
const samples: Array<{ height: number; drift: number }> = [];
|
||||
// A thumb can jump into previously unvisited rows in either direction.
|
||||
for (const fraction of [0, 0.75, 0.25, 1, 0.5, 0.1, 0.9, 0]) {
|
||||
el.scrollTop = fraction * (initialHeight - el.clientHeight);
|
||||
const target = el.scrollTop;
|
||||
await new Promise(requestAnimationFrame);
|
||||
await new Promise(requestAnimationFrame);
|
||||
samples.push({ height: el.scrollHeight, drift: Math.abs(el.scrollTop - target) });
|
||||
}
|
||||
return { initialHeight, samples, text, after: window.getSelection()!.toString() };
|
||||
}, selected);
|
||||
expect(result.initialHeight).toBeGreaterThan(10_000);
|
||||
for (const sample of result.samples) {
|
||||
expect(Math.abs(sample.height - result.initialHeight)).toBeLessThanOrEqual(1);
|
||||
expect(sample.drift).toBeLessThanOrEqual(1);
|
||||
}
|
||||
if (selected) {
|
||||
expect(result.text).toContain("Request 0");
|
||||
expect(result.text).toContain("Reply 79");
|
||||
expect(result.after).toBe(result.text);
|
||||
await stream.focus();
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(result.text);
|
||||
await page.evaluate(() => window.getSelection()!.removeAllRanges());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("opens a commit's branch menu and acts in its linked repository", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const primary = "/dev/acme-api";
|
||||
const linked = "/dev/acme-web";
|
||||
const tip = "1".repeat(40);
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () =>
|
||||
[
|
||||
{ root: primary, head: "main" },
|
||||
{ root: linked, head: "release" },
|
||||
].map((repo) => ({ ...repo, operation: null, headCommit: tip }));
|
||||
h.vcs_branch_info = ({ repo }) => ({
|
||||
head: repo === linked ? "release" : "main",
|
||||
headCommit: tip,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_branches = ({ repo }) =>
|
||||
[repo === linked ? "origin/dev" : "origin/other"].map((name) => ({
|
||||
name,
|
||||
commit: tip,
|
||||
remote: true,
|
||||
current: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
}));
|
||||
h.vcs_log = ({ repo }) => {
|
||||
const summary = repo === linked ? "Linked repository commit" : "Primary repository commit";
|
||||
return [
|
||||
{
|
||||
id: tip,
|
||||
shortId: tip.slice(0, 8),
|
||||
parents: [],
|
||||
refs: [repo === linked ? "origin/dev" : "origin/other"],
|
||||
author: "A",
|
||||
email: "[email protected]",
|
||||
timeMs: 0,
|
||||
summary,
|
||||
message: summary,
|
||||
},
|
||||
];
|
||||
};
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_log_details_batch = ({ revisions }) =>
|
||||
(revisions as string[]).map(() => ({
|
||||
message: "Linked repository commit",
|
||||
containingBranches: [],
|
||||
signature: "N",
|
||||
signer: "",
|
||||
key: "",
|
||||
fingerprint: "",
|
||||
}));
|
||||
h.vcs_commit_files = () => [];
|
||||
h.vcs_config_get = () => null;
|
||||
h.vcs_tags = () => [];
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_create_branch = () => null;
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({ available: true, root: primary, repo: primary });
|
||||
await refreshNow();
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.showLog");
|
||||
});
|
||||
|
||||
await page.getByRole("option", { name: /Linked repository commit/ }).click({ button: "right" });
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
await expect(menu.getByRole("menuitem", { name: "Branch 'origin/other'" })).toHaveCount(0);
|
||||
await menu.getByRole("menuitem", { name: "Branch 'origin/dev'" }).hover();
|
||||
await expect(page.getByRole("menuitem", { name: "Pull into 'release' Using Rebase" })).toBeVisible();
|
||||
const newBranch = page.getByRole("menuitem", { name: "New Branch from 'origin/dev'…" });
|
||||
await newBranch.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Create New Branch from origin/dev" });
|
||||
await dialog.getByRole("textbox", { name: "New branch name:" }).fill("test-branch");
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_create_branch"))
|
||||
.toMatchObject([{ repo: "/dev/acme-web", name: "test-branch", start: "origin/dev", checkout: true }]);
|
||||
});
|
||||
@@ -7,30 +7,47 @@ import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
|
||||
async function openNewBranchDialog(page: Page) {
|
||||
async function openNewBranchDialog(page: Page, from?: string) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (root) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: "1111111",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_create_branch = () => null;
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
void executeAction("vcs.newBranch");
|
||||
}, ROOT);
|
||||
const dialog = page.getByRole("dialog", { name: "Create New Branch" });
|
||||
await page.evaluate(
|
||||
async ({ root, from }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: "1111111",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_branches = () => [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: null,
|
||||
commit: "1111111",
|
||||
},
|
||||
];
|
||||
h.vcs_create_branch = () => null;
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
await loadBranches();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
if (from) void executeAction("vcs.log.newBranch", { id: from, summary: "Selected commit", repo: root });
|
||||
else void executeAction("vcs.newBranch");
|
||||
},
|
||||
{ root: ROOT, from },
|
||||
);
|
||||
const dialog = page.getByRole("dialog", { name: from ? `Create New Branch from ${from}` : "Create New Branch" });
|
||||
const input = dialog.getByRole("textbox", { name: "New branch name:" });
|
||||
await expect(input).toBeVisible();
|
||||
return { dialog, input };
|
||||
@@ -48,6 +65,29 @@ test("a typed space becomes a separator and Create stays enabled", async ({ work
|
||||
expect(call).toMatchObject({ name: "fix-login-redirect" });
|
||||
});
|
||||
|
||||
test("overwrites a local branch only after explicitly opting in", async ({ workbench: page }) => {
|
||||
const from = "2".repeat(40);
|
||||
const { dialog, input } = await openNewBranchDialog(page, from);
|
||||
await input.fill("main");
|
||||
const create = dialog.getByRole("button", { name: "Create", exact: true });
|
||||
await expect(create).toBeDisabled();
|
||||
const overwrite = dialog.getByRole("checkbox", { name: "Overwrite existing branch" });
|
||||
await expect(overwrite).toBeVisible();
|
||||
await expect(overwrite).not.toBeChecked();
|
||||
await overwrite.check();
|
||||
await expect(create).toBeEnabled();
|
||||
await input.fill("new-branch");
|
||||
await expect(overwrite).toHaveCount(0);
|
||||
await input.fill("main");
|
||||
await expect(overwrite).not.toBeChecked();
|
||||
await expect(create).toBeDisabled();
|
||||
await overwrite.check();
|
||||
await create.click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_create_branch"))
|
||||
.toEqual([{ repo: ROOT, name: "main", start: from, checkout: true, overwrite: true }]);
|
||||
});
|
||||
|
||||
test("a space typed in the middle keeps the caret after it", async ({ workbench: page }) => {
|
||||
const { input } = await openNewBranchDialog(page);
|
||||
await input.fill("ab");
|
||||
|
||||
@@ -58,3 +58,10 @@ generatesMetadataFilesAtProjectRoot = false
|
||||
exclusions = ["**/node_modules/**", "**/.metadata/**", "**/archetype-resources/**", "**/META-INF/maven/**"]
|
||||
maven = { enabled = true }
|
||||
gradle = { enabled = true, wrapper = { enabled = true } }
|
||||
|
||||
[[language-servers]]
|
||||
name = "kmp-lsp"
|
||||
fallback = true
|
||||
command = "kmp-lsp"
|
||||
root-markers = ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "build.xml", ".project"]
|
||||
install-hint = "Install kmp-lsp in Settings › Languages & Frameworks › Language Servers (https://github.com/Hessesian/kmp-lsp)"
|
||||
@@ -18,6 +18,7 @@ install-hint = "npm i -g @vue/language-server typescript@6"
|
||||
# reaches it through `tsserver/request`, which the client forwards to vtsls.
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
command = "vtsls"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
|
||||
|
||||
@@ -26,6 +26,36 @@
|
||||
"typingLarge.mainThreadMsPerKey": 20,
|
||||
"typingLarge.tbtMs": 50,
|
||||
|
||||
"typingAngular.openMs": 200,
|
||||
"typingAngular.p95Ms": 30,
|
||||
"typingAngular.maxMs": 40,
|
||||
"typingAngular.mainThreadMsPerKey": 30,
|
||||
"typingAngular.tbtMs": 50,
|
||||
|
||||
"completion.openMs": 150,
|
||||
"completion.narrowP95Ms": 20,
|
||||
"completion.narrowMissedFramePct": 2,
|
||||
"completion.narrowMainThreadMsPerKey": 35,
|
||||
"completion.arrowP95Ms": 20,
|
||||
"completion.arrowMissedFramePct": 2,
|
||||
"completion.tbtMs": 50,
|
||||
|
||||
"consoleOutput.streamMs": 4600,
|
||||
"consoleOutput.droppedFramesPct": 2,
|
||||
"consoleOutput.keyP95Ms": 20,
|
||||
"consoleOutput.keyMissedFramePct": 10,
|
||||
"consoleOutput.tbtMs": 50,
|
||||
|
||||
"gitLog.showMs": 300,
|
||||
"gitLog.droppedFramesPct": 2,
|
||||
"gitLog.tbtMs": 50,
|
||||
"gitLog.arrowKeyP95Ms": 20,
|
||||
"gitLog.arrowKeyMissedFramePct": 5,
|
||||
|
||||
"resizePanels.droppedFramesPct": 2,
|
||||
"resizePanels.bottomDroppedFramesPct": 2,
|
||||
"resizePanels.tbtMs": 50,
|
||||
|
||||
"keyRepeat.p95Ms": 20,
|
||||
"keyRepeat.maxMs": 33,
|
||||
"keyRepeat.missedFramePct": 2,
|
||||
|
||||
@@ -110,6 +110,88 @@ const typingAngular: Scenario = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Code completion with a language server's 2,000 items: the first letter opens
|
||||
* the popup (after CodeMirror's 100 ms typing delay), each further letter
|
||||
* narrows it, arrows move the selection.
|
||||
*/
|
||||
const completion: Scenario = {
|
||||
id: "completion",
|
||||
title: "Code completion over 2,000 items",
|
||||
async run(h) {
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { fakeCompletion(n: number): void } }).__openideaPerf.fakeCompletion(2_000),
|
||||
);
|
||||
try {
|
||||
await h.openFile(`${ROOT}/src/completion/Orders.ts`, tsSource(2_000, "completion"));
|
||||
const st = await h.editorState();
|
||||
await h.setCursor(Math.floor((st?.length ?? 0) / 2));
|
||||
await h.parserIdle();
|
||||
await h.page.keyboard.press("End");
|
||||
await h.page.keyboard.press("Enter");
|
||||
const refresh = await h.refreshMs();
|
||||
const openMs = await h.measure(() => h.page.keyboard.press("g"), ".cm-tooltip-autocomplete li", "Result<Order>");
|
||||
const t0 = await h.now();
|
||||
const before = await h.counters();
|
||||
const narrow = await h.typeMeasured("etOrd", 150);
|
||||
const work = Harness.delta(before, await h.counters());
|
||||
const arrows = await h.pressMeasured(Array(20).fill("ArrowDown"), 60);
|
||||
await h.page.keyboard.press("Escape");
|
||||
return {
|
||||
openMs,
|
||||
...keySummary(narrow, refresh, "narrow"),
|
||||
narrowMainThreadMsPerKey: work.taskMs / 5,
|
||||
...keySummary(arrows, refresh, "arrow"),
|
||||
tbtMs: totalBlockingTime(await h.longTasksSince(t0)),
|
||||
};
|
||||
} finally {
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { fakeCompletion(n: number): void } }).__openideaPerf.fakeCompletion(0),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A process printing 50,000 log lines (stack frames among them) at 200 lines a
|
||||
* frame (~4 s) into the Run console, while the user types in an editor: the
|
||||
* console must keep up and the editor must stay responsive.
|
||||
*/
|
||||
const consoleOutput: Scenario = {
|
||||
id: "consoleOutput",
|
||||
title: "Type while the Run console streams 50k lines",
|
||||
async run(h) {
|
||||
await h.openFile(SAMPLE);
|
||||
const st = await h.editorState();
|
||||
await h.setCursor(Math.floor((st?.length ?? 0) / 2));
|
||||
await h.page.keyboard.press("End");
|
||||
await h.page.keyboard.press("Enter");
|
||||
const refresh = await h.refreshMs();
|
||||
const t0 = await h.now();
|
||||
await h.inPage((p) => p.startFrames());
|
||||
const streamMs = h.page.evaluate(async () => {
|
||||
const w = window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } };
|
||||
const started = performance.now();
|
||||
await w.__openideaPerf.runAction("run.sampleOutput", { lines: 50_000, perFrame: 200 });
|
||||
return performance.now() - started;
|
||||
});
|
||||
// The console takes focus with it; type back in the editor while it streams.
|
||||
await h.page.waitForTimeout(100);
|
||||
await h.setCursor((await h.editorState())?.head ?? 0);
|
||||
const keys = await h.typeMeasured(TYPED.slice(0, 40), 70);
|
||||
const total = await streamMs;
|
||||
const frames = await h.inPage((p) => p.stopFrames());
|
||||
await h.inPage((p) => p.waitShown("body", "processed order #49998", 5_000));
|
||||
return {
|
||||
// 250 frames of output at the display rate is the floor.
|
||||
streamMs: total,
|
||||
...frameSummary(frames, refresh),
|
||||
...keySummary(keys, refresh, "key"),
|
||||
tbtMs: totalBlockingTime(await h.longTasksSince(t0)),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Held key: auto-repeat at ~30 Hz must never fall behind. */
|
||||
const keyRepeat: Scenario = {
|
||||
id: "keyRepeat",
|
||||
@@ -185,6 +267,107 @@ const scroll: Scenario = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Git Log with 20,000 commits on branching lanes, loaded page by page as the
|
||||
* backend does (150 ms a page, like `git log`): showing it, walking the
|
||||
* selection with the arrow keys (the details pane follows) and wheel-scrolling
|
||||
* through several pages.
|
||||
*/
|
||||
const gitLog: Scenario = {
|
||||
id: "gitLog",
|
||||
title: "Show, navigate and scroll a 20k-commit Git Log",
|
||||
async run(h) {
|
||||
await h.page.evaluate(() =>
|
||||
(
|
||||
window as never as { __openideaPerf: { fakeGitLog(n: number, latencyMs?: number): void } }
|
||||
).__openideaPerf.fakeGitLog(20_000, 150),
|
||||
);
|
||||
const showMs = await h.measure(
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
);
|
||||
const refresh = await h.refreshMs();
|
||||
const list = h.page.getByRole("listbox", { name: "Commits" });
|
||||
await list.getByRole("option").first().click();
|
||||
const keyLat = await h.pressMeasured(Array(40).fill("ArrowDown"), 50);
|
||||
const box = (await list.boundingBox())!;
|
||||
await h.page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
const t0 = await h.now();
|
||||
await h.inPage((p) => p.startFrames());
|
||||
// Far enough to load several more pages on the way.
|
||||
for (let i = 0; i < 160; i++) {
|
||||
await h.page.mouse.wheel(0, i < 120 ? 600 : -600);
|
||||
await h.page.waitForTimeout(16);
|
||||
}
|
||||
await h.page.waitForTimeout(200);
|
||||
const frames = await h.inPage((p) => p.stopFrames());
|
||||
return {
|
||||
showMs,
|
||||
...frameSummary(frames, refresh),
|
||||
tbtMs: totalBlockingTime(await h.longTasksSince(t0)),
|
||||
...keySummary(keyLat, refresh, "arrowKey"),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Dragging the splitters with an editor, the Project tree and the Git Log
|
||||
* open: every pointer move resizes the islands, so each frame relays them out.
|
||||
*/
|
||||
const resizePanels: Scenario = {
|
||||
id: "resizePanels",
|
||||
title: "Drag the tool window splitters",
|
||||
async run(h) {
|
||||
await h.openFile(SAMPLE);
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { fakeGitLog(n: number): void } }).__openideaPerf.fakeGitLog(2_000),
|
||||
);
|
||||
await h.measure(
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
);
|
||||
const refresh = await h.refreshMs();
|
||||
const drag = async (name: string, dx: number, dy: number) => {
|
||||
const box = (await h.page.getByRole("separator", { name }).boundingBox())!;
|
||||
const x = box.x + box.width / 2;
|
||||
const y = box.y + box.height / 2;
|
||||
await h.page.mouse.move(x, y);
|
||||
await h.page.mouse.down();
|
||||
await h.inPage((p) => p.startFrames());
|
||||
// Out and back twice, one pointer move a frame.
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const t = Math.sin((i / 60) * Math.PI);
|
||||
await h.page.mouse.move(x + dx * t, y + dy * t);
|
||||
await h.page.waitForTimeout(16);
|
||||
}
|
||||
await h.page.mouse.up();
|
||||
await h.page.waitForTimeout(200);
|
||||
return frameSummary(await h.inPage((p) => p.stopFrames()), refresh);
|
||||
};
|
||||
const t0 = await h.now();
|
||||
const side = await drag("Resize left tool window", 300, 0);
|
||||
const bottom = await drag("Resize bottom tool window", 0, -250);
|
||||
return {
|
||||
...side,
|
||||
tbtMs: totalBlockingTime(await h.longTasksSince(t0)),
|
||||
bottomFrameP95Ms: bottom.frameP95Ms,
|
||||
bottomDroppedFramesPct: bottom.droppedFramesPct,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Cold load: navigation → Project tree painted. */
|
||||
const startup: Scenario = {
|
||||
id: "startup",
|
||||
@@ -369,6 +552,10 @@ export const SCENARIOS: Scenario[] = [
|
||||
typing,
|
||||
typingLarge,
|
||||
typingAngular,
|
||||
completion,
|
||||
consoleOutput,
|
||||
gitLog,
|
||||
resizePanels,
|
||||
keyRepeat,
|
||||
scroll,
|
||||
tabs,
|
||||
|
||||
+91
-22
@@ -34,10 +34,10 @@ plugins/
|
||||
├─ regex-tester/ # html view talking to its code, settings, the editor's selection
|
||||
└─ license-header/ # file-opened events, quick fix, project scan in a task
|
||||
sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host)
|
||||
crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave
|
||||
crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens
|
||||
```
|
||||
|
||||
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.2.0`, world
|
||||
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.3.0`, world
|
||||
`plugin`).
|
||||
|
||||
## 1. Quick start
|
||||
@@ -137,23 +137,23 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
|
||||
|
||||
### Contribution points
|
||||
|
||||
| Point | Declaration | Code needed |
|
||||
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------- |
|
||||
| `commands` | `id`, `title`, `category?`, `when?` | to run them |
|
||||
| `themes` | `path` (theme JSON), `editor-scheme?` | no |
|
||||
| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no |
|
||||
| `languages` | `path` (`languages/<id>.toml` format, see §6) | no |
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
|
||||
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
|
||||
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
|
||||
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`), `view?`, `command`, `when?` | no |
|
||||
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
|
||||
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
|
||||
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
|
||||
| `views` | `id`, `title`, `icon?` (an icon name, or an SVG of the package), `location` (`left`, `right`, `bottom`), `web?` (see _Web views_) | without `web` |
|
||||
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` |
|
||||
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
|
||||
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
|
||||
| Point | Declaration | Code needed |
|
||||
| --------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------- |
|
||||
| `commands` | `id`, `title`, `category?`, `when?` | to run them |
|
||||
| `themes` | `path` (theme JSON), `editor-scheme?` | no |
|
||||
| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no |
|
||||
| `languages` | `path` (`languages/<id>.toml` format, see §6) | no |
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no |
|
||||
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
|
||||
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
|
||||
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`), `view?`, `command`, `when?` | no |
|
||||
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
|
||||
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
|
||||
| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no |
|
||||
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_) | without `web` |
|
||||
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` |
|
||||
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
|
||||
| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no |
|
||||
|
||||
A `viewItem.context` menu needs `view`, the id of one of the plugin's own
|
||||
views. It adds the commands to the right-click menu of the items in that
|
||||
@@ -402,7 +402,7 @@ declaration matches the file's language are called (and loaded):
|
||||
|
||||
```toml
|
||||
[[contributes.providers]]
|
||||
kinds = ["definition", "line-markers", "completion"] # also "inline-completion", "code-actions"
|
||||
kinds = ["definition", "line-markers", "completion"] # also "inline-completion", "code-actions", "semantic-tokens"
|
||||
languages = ["java", "xml"] # editor language ids; "*" for any
|
||||
```
|
||||
|
||||
@@ -432,6 +432,31 @@ dropped at 50 ms like a slow one. Inline completion is exempt from the 50 ms (it
|
||||
need the network) but is cancelled as soon as the user types on: check
|
||||
`Task::is_cancelled` or just let the host interrupt the call.
|
||||
|
||||
#### Semantic highlighting
|
||||
|
||||
The `semantic-tokens` kind (API 1.3: `engines.openidea = "^1.3"`) colours
|
||||
tokens in documents of the declared languages, including languages the plugin
|
||||
doesn't contribute, such as `php`. Register with
|
||||
`register_plugin!(MyPlugin, semantic_tokens)` (any combination works:
|
||||
`(MyPlugin, providers, views, semantic_tokens)`) and implement
|
||||
`openidea_plugin::semantic_tokens::SemanticTokens`:
|
||||
|
||||
```rust
|
||||
impl SemanticTokens for MyPlugin {
|
||||
fn semantic_tokens(&mut self, doc: &Document) -> Vec<SemanticToken> {
|
||||
let (start, end) = (text::position(&doc.text, 10), text::position(&doc.text, 14));
|
||||
vec![SemanticToken::new(Range { start, end }, TokenKind::Method)]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A token covers part of one line and carries an LSP token kind (`TokenKind`:
|
||||
`method`, `property`, `type`, …) and modifiers (`TokenModifier`: `static`,
|
||||
`deprecated`, …); the WIT takes them as kebab-case strings. The tokens join
|
||||
the language server's semantic tokens and win where they overlap one, so the
|
||||
editor's colour scheme styles them like the server's. They are asked again
|
||||
after each edit, under the edit-path budget; at most 65,536 per document.
|
||||
|
||||
### Network and secrets
|
||||
|
||||
`host::fetch` makes an HTTPS request (plain HTTP only to `localhost`) to a host
|
||||
@@ -518,6 +543,50 @@ Scripts get the same as `openidea.theme` (`{ dark, vars }`) and
|
||||
`openidea.onThemeChange(fn)`, for drawing on a canvas, say. Variables are only
|
||||
ever added.
|
||||
|
||||
#### Services views
|
||||
|
||||
`location = "services"` (API 1.3: `engines.openidea = "^1.3"`) puts a view's
|
||||
tree in the Services tool window, next to Docker and the run configurations,
|
||||
instead of a tool window of its own. Its code renders it (no `web`):
|
||||
|
||||
```toml
|
||||
[[contributes.views]]
|
||||
id = "kube"
|
||||
title = "Kubernetes"
|
||||
icon = "icons/kubernetes.svg"
|
||||
location = "services"
|
||||
|
||||
[capabilities]
|
||||
optional = ["process:kubectl"]
|
||||
```
|
||||
|
||||
The items of the view's `tree` are Services nodes: `render`, `handle` and the
|
||||
toolbar work as in a tool window, the toolbar's buttons acting on the one
|
||||
selected node, and `viewItem.context` menus give the nodes a right-click menu.
|
||||
The pane beside the tree comes from the `service-provider` export: register
|
||||
`register_plugin!(MyPlugin, views, services)` and implement
|
||||
`openidea_plugin::services::Services`, which returns the selected node's tabs
|
||||
(at most 8; asked again after `host::refresh_view("kube")`):
|
||||
|
||||
```rust
|
||||
impl Services for MyPlugin {
|
||||
fn detail(&mut self, view: &str, key: &str, _ctx: &Invocation) -> Result<Vec<Tab>, Error> {
|
||||
let pod = key.trim_start_matches("pod:");
|
||||
let log = ProcessLog::new("kubectl", &["logs", "-f", "--tail=1000", pod])
|
||||
.toggle("ts", "Timestamps", &["--timestamps"]);
|
||||
Ok(vec![Tab::new("log", "Log", log), Tab::new("inspect", "Inspect", Pane::Text(self.describe(pod)?))])
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The IDE switches tabs without calling the plugin. A tab is a `Pane::Message`,
|
||||
read-only `Pane::Text` (at most 1 MiB) or a `ProcessLog`: the IDE asks for the
|
||||
pane again and runs that program (it needs the plugin's `process:<program>`
|
||||
grant) in the project root, following its output in the log Docker containers
|
||||
use (ANSI stripped, the last 5000 lines and 16 KiB per line, Soft-wrap, Clear,
|
||||
the exit code at the end). A toggle appends its `args` and starts the program
|
||||
again. It stops when the node's pane closes or the Services window is hidden.
|
||||
|
||||
#### Web views
|
||||
|
||||
A view or custom editor can instead be a web page of the package, for UIs the
|
||||
@@ -972,8 +1041,8 @@ the API itself follows _Evolving the plugin API_ below.
|
||||
|
||||
## 10. Evolving the plugin API
|
||||
|
||||
Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36 and 1.1.0
|
||||
with 0.1.37. wasmtime decides what stays compatible: it resolves interface names
|
||||
Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36, 1.1.0
|
||||
with 0.1.37 and 1.2.0 with 0.1.38. wasmtime decides what stays compatible: it resolves interface names
|
||||
by semver (a component importing `openidea:plugin/[email protected]` links against a
|
||||
host defining `@1.1.0`, and the host finds its exports the same way), but
|
||||
function types must match exactly — a record with another field count, or a
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
fd5d8c0b9c6828bbeb0a93e394a0468abe83f051d1c20e50a7ac91fe12d5ab68
|
||||
eb76da4bc9db84dcbad34143bac18c9ecf974276f793009791a15aab2eee291d
|
||||
Бінарний файл не відображається.
Loaded 100 of 390 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача